problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
B. Social Distancetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputm chairs are arranged in a circle sequentially. The chairs are numbered from 0 to m-1. n people want to sit in these chairs. The i-th of them wants at least a[i] empty chairs both on his right and left side. More formally, if the i-th person sits in the j-th chair, then no one else should sit in the following chairs: (j-a[i]) \bmod m, (j-a[i]+1) \bmod m, ... (j+a[i]-1) \bmod m, (j+a[i]) \bmod m.Decide if it is possible to sit down for all of them, under the given limitations.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 5 \cdot 10^4) — 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 \leq n \leq 10^5, 1 \leq m \leq 10^9) — the number of people and the number of chairs.The next line contains n integers, a_1, a_2, ... a_n (1 \leq a_i \leq 10^9) — the minimum number of empty chairs, on both sides of the i-th person.It is guaranteed that the sum of n over all test cases will not exceed 10^5.OutputFor each test case print "YES" (without quotes) if it is possible for everyone to sit down and fulfil the restrictions, and "NO" (without quotes) otherwise.You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes" and "YES" will all be recognized as positive answers).ExampleInput 6 3 2 1 1 1 2 4 1 1 2 5 2 1 3 8 1 2 1 4 12 1 2 1 3 4 19 1 2 1 3 Output NO YES NO YES NO YES NoteTest case 1: n>m, so they can not sit down.Test case 2: the first person can sit 2-nd and the second person can sit in the 0-th chair. Both of them want at least 1 empty chair on both sides, chairs 1 and 3 are free, so this is a good solution.Test case 3: if the second person sits down somewhere, he needs 2 empty chairs, both on his right and on his left side, so it is impossible to find a place for the first person, because there are only 5 chairs.Test case 4: they can sit in the 1-st, 4-th, 7-th chairs respectively.
6 3 2 1 1 1 2 4 1 1 2 5 2 1 3 8 1 2 1 4 12 1 2 1 3 4 19 1 2 1 3
NO YES NO YES NO YES
1.5 seconds
256 megabytes
['greedy', 'math', 'sortings', '*900']
A. Direction Changetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a grid with n rows and m columns. Rows and columns are numbered from 1 to n, and from 1 to m. The intersection of the a-th row and b-th column is denoted by (a, b). Initially, you are standing in the top left corner (1, 1). Your goal is to reach the bottom right corner (n, m).You can move in four directions from (a, b): up to (a-1, b), down to (a+1, b), left to (a, b-1) or right to (a, b+1).You cannot move in the same direction in two consecutive moves, and you cannot leave the grid. What is the minimum number of moves to reach (n, m)?InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^3) — the number of the test cases. The description of the test cases follows.The first line of each test case contains two integers n and m (1 \le n, m \le 10^9) — the size of the grid.OutputFor each test case, print a single integer: -1 if it is impossible to reach (n, m) under the given conditions, otherwise the minimum number of moves.ExampleInput 6 1 1 2 1 1 3 4 2 4 6 10 5 Output 0 1 -1 6 10 17 NoteTest case 1: n=1, m=1, and initially you are standing in (1, 1) so 0 move is required to reach (n, m) = (1, 1).Test case 2: you should go down to reach (2, 1).Test case 3: it is impossible to reach (1, 3) without moving right two consecutive times, or without leaving the grid.Test case 4: an optimal moving sequence could be: (1, 1) \to (1, 2) \to (2, 2) \to (2, 1) \to (3, 1) \to (3, 2) \to (4, 2). It can be proved that this is the optimal solution. So the answer is 6.
6 1 1 2 1 1 3 4 2 4 6 10 5
0 1 -1 6 10 17
1 second
256 megabytes
['implementation', 'math', '*800']
F. Yin Yangtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular grid with n rows and m columns. n and m are divisible by 4. Some of the cells are already colored black or white. It is guaranteed that no two colored cells share a corner or an edge.Color the remaining cells in a way that both the black and the white cells becomes orthogonally connected or determine that it is impossible.Consider a graph, where the black cells are the nodes. Two nodes are adjacent if the corresponding cells share an edge. If the described graph is connected, the black cells are orthogonally connected. Same for white cells.InputThe input consists of multiple test cases. The first line of the input contains a single integer t (1 \le t \le 4000) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n, m (8 \le n, m \le 500, n and m are divisible by 4) — the number of rows and columns.Each of the next n lines contains m characters. Each character is either 'B', 'W' or '.', representing black, white or empty cell respectively. Two colored (black or white) cell does not share a corner or an edge.It is guaranteed that the sum of n \cdot m over all test cases does not exceed 250\,000.OutputFor each testcase print "NO" if there is no solution, otherwise print "YES" and a grid with the same format. If there are multiple solutions, you can print any.ExampleInput 4 8 8 .W.W.... .....B.W .W.W.... .....W.W B.B..... ....B.B. B.W..... ....B.B. 8 8 B.W..B.W ........ W.B..W.B ........ ........ B.W..B.W ........ W.B..W.B 8 12 W.B......... ....B...B.W. B.B......... ....B...B.B. .B.......... ........B... .W..B.B...W. ............ 16 16 .W............W. ...W..W..W.W.... .B...........B.W ....W....W...... W......B....W.W. ..W.......B..... ....W...W....B.W .W....W....W.... ...B...........W W.....W...W..B.. ..W.W...W......B ............W... .W.B...B.B....B. .....W.....W.... ..W......W...W.. W...W..W...W...W Output YES BWWWWWWW BWBBBBBW BWBWWWBW BWBWBWBW BWBWBWBW BWBBBWBW BWWWWWBW BBBBBBBW NO YES WWBBBBBBBBBB BWWWBBBBBBWB BBBWBBBWWWWB BBBWBBBWBBBB BBBWBBBWBBBB BBBWWWWWBBBB BWWWBBBWWWWB BBBBBBBBBBBB YES WWWWWWWWWWWWWWWW WWWWWWWWWWWWWWWW WBBBBBBBBBBBBBWW WBBBWBWWWWBWWBWW WBBWWBBBWWBWWBWW WBWWWBWWWWBWWBWW WBBWWBBBWWBWWBWW WWBWWWWWWWWWWWWW WWBBBBBBBBBBBBWW WBBBWWWBWWWBWBWW WWWBWBBBWBBBWBBB WWWBWBWWWWWBWWBW WWWBWBBBWBBBWWBW WWWWWWWWWWWWWWWW WWWWWWWWWWWWWWWW WWWWWWWWWWWWWWWW NoteSolution for test case 1: Test case 2: one can see that the black and the white part can't be connected in the same time. So the answer is "NO".
4 8 8 .W.W.... .....B.W .W.W.... .....W.W B.B..... ....B.B. B.W..... ....B.B. 8 8 B.W..B.W ........ W.B..W.B ........ ........ B.W..B.W ........ W.B..W.B 8 12 W.B......... ....B...B.W. B.B......... ....B...B.B. .B.......... ........B... .W..B.B...W. ............ 16 16 .W............W. ...W..W..W.W.... .B...........B.W ....W....W...... W......B....W.W. ..W.......B..... ....W...W....B.W .W....W....W.... ...B...........W W.....W...W..B.. ..W.W...W......B ............W... .W.B...B.B....B. .....W.....W.... ..W......W...W.. W...W..W...W...W
YES BWWWWWWW BWBBBBBW BWBWWWBW BWBWBWBW BWBWBWBW BWBBBWBW BWWWWWBW BBBBBBBW NO YES WWBBBBBBBBBB BWWWBBBBBBWB BBBWBBBWWWWB BBBWBBBWBBBB BBBWBBBWBBBB BBBWWWWWBBBB BWWWBBBWWWWB BBBBBBBBBBBB YES WWWWWWWWWWWWWWWW WWWWWWWWWWWWWWWW WBBBBBBBBBBBBBWW WBBBWBWWWWBWWBWW WBBWWBBBWWBWWBWW WBWWWBWWWWBWWBWW WBBWWBBBWWBWWBWW WWBWWWWWWWWWWWWW WWBBBBBBBBBBBBWW WBBBWWWBWWWBWBWW WWWBWBBBWBBBWBBB WWWBWBWWWWWBWWBW WWWBWBBBWBBBWWBW WWWWWWWWWWWWWWWW WWWWWWWWWWWWWWWW WWWWWWWWWWWWWWWW
3 seconds
256 megabytes
['implementation', '*3500']
E. Centroid Probabilitiestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider every tree (connected undirected acyclic graph) with n vertices (n is odd, vertices numbered from 1 to n), and for each 2 \le i \le n the i-th vertex is adjacent to exactly one vertex with a smaller index.For each i (1 \le i \le n) calculate the number of trees for which the i-th vertex will be the centroid. The answer can be huge, output it modulo 998\,244\,353.A vertex is called a centroid if its removal splits the tree into subtrees with at most (n-1)/2 vertices each.InputThe first line contains an odd integer n (3 \le n < 2 \cdot 10^5, n is odd) — the number of the vertices in the tree.OutputPrint n integers in a single line, the i-th integer is the answer for the i-th vertex (modulo 998\,244\,353).ExamplesInput 3 Output 1 1 0 Input 5 Output 10 10 4 0 0 Input 7 Output 276 276 132 36 0 0 0 NoteExample 1: there are two possible trees: with edges (1-2), and (1-3) — here the centroid is 1; and with edges (1-2), and (2-3) — here the centroid is 2. So the answer is 1, 1, 0.Example 2: there are 24 possible trees, for example with edges (1-2), (2-3), (3-4), and (4-5). Here the centroid is 3.
3
1 1 0
3 seconds
256 megabytes
['combinatorics', 'dp', 'fft', 'math', '*3000']
D. Edge Eliminationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (connected, undirected, acyclic graph) with n vertices. Two edges are adjacent if they share exactly one endpoint. In one move you can remove an arbitrary edge, if that edge is adjacent to an even number of remaining edges.Remove all of the edges, or determine that it is impossible. If there are multiple solutions, print any.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^5) — 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 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.Then n-1 lines follow. The i-th of them contains two integers u_i, v_i (1 \le u_i,v_i \le n) the endpoints of the i-th edge. It is guaranteed that the given graph is a tree.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print "NO" if it is impossible to remove all the edges.Otherwise print "YES", and in the next n-1 lines print a possible order of the removed edges. For each edge, print its endpoints in any order.ExampleInput 5 2 1 2 3 1 2 2 3 4 1 2 2 3 3 4 5 1 2 2 3 3 4 3 5 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 2 1 NO YES 2 3 3 4 2 1 YES 3 5 2 3 2 1 4 3 NONoteTest case 1: it is possible to remove the edge, because it is not adjacent to any other edge.Test case 2: both edges are adjacent to exactly one edge, so it is impossible to remove any of them. So the answer is "NO".Test case 3: the edge 2-3 is adjacent to two other edges. So it is possible to remove it. After that removal it is possible to remove the remaining edges too.
5 2 1 2 3 1 2 2 3 4 1 2 2 3 3 4 5 1 2 2 3 3 4 3 5 7 1 2 1 3 2 4 2 5 3 6 3 7
YES 2 1 NO YES 2 3 3 4 2 1 YES 3 5 2 3 2 1 4 3 NO
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'dp', 'trees', '*2900']
C. Half Queen Covertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a board with n rows and n columns, numbered from 1 to n. The intersection of the a-th row and b-th column is denoted by (a, b).A half-queen attacks cells in the same row, same column, and on one diagonal. More formally, a half-queen on (a, b) attacks the cell (c, d) if a=c or b=d or a-b=c-d. The blue cells are under attack. What is the minimum number of half-queens that can be placed on that board so as to ensure that each square is attacked by at least one half-queen?Construct an optimal solution.InputThe first line contains a single integer n (1 \le n \le 10^5) — the size of the board.OutputIn the first line print a single integer k — the minimum number of half-queens.In each of the next k lines print two integers a_i, b_i (1 \le a_i, b_i \le n) — the position of the i-th half-queen.If there are multiple solutions, print any.ExamplesInput 1 Output 1 1 1 Input 2 Output 1 1 1 Input 3 Output 2 1 1 1 2 NoteExample 1: one half-queen is enough. Note: a half-queen on (1, 1) attacks (1, 1).Example 2: one half-queen is enough too. (1, 2) or (2, 1) would be wrong solutions, because a half-queen on (1, 2) does not attack the cell (2, 1) and vice versa. (2, 2) is also a valid solution.Example 3: it is impossible to cover the board with one half queen. There are multiple solutions for 2 half-queens; you can print any of them.
1
1 1 1
1 second
256 megabytes
['constructive algorithms', 'math', '*2400']
B. Optimal Partitiontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. You should divide a into continuous non-empty subarrays (there are 2^{n-1} ways to do that).Let s=a_l+a_{l+1}+\ldots+a_r. The value of a subarray a_l, a_{l+1}, \ldots, a_r is: (r-l+1) if s>0, 0 if s=0, -(r-l+1) if s<0. What is the maximum sum of values you can get with a partition?InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 5 \cdot 10^5) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 5 \cdot 10^5).The second line of each test case contains n integers a_1, a_2, ..., a_n (-10^9 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case print a single integer — the maximum sum of values you can get with an optimal parition.ExampleInput 5 3 1 2 -3 4 0 -2 3 -4 5 -1 -2 3 -1 -1 6 -1 2 -3 4 -5 6 7 1 -1 -1 1 -1 -1 1 Output 1 2 1 6 -1 NoteTest case 1: one optimal partition is [1, 2], [-3]. 1+2>0 so the value of [1, 2] is 2. -3<0, so the value of [-3] is -1. 2+(-1)=1.Test case 2: the optimal partition is [0, -2, 3], [-4], and the sum of values is 3+(-1)=2.
5 3 1 2 -3 4 0 -2 3 -4 5 -1 -2 3 -1 -1 6 -1 2 -3 4 -5 6 7 1 -1 -1 1 -1 -1 1
1 2 1 6 -1
4 seconds
256 megabytes
['data structures', 'dp', '*2100']
A. Make it Increasingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n positive integers, and an array b, with length n. Initially b_i=0 for each 1 \leq i \leq n.In one move you can choose an integer i (1 \leq i \leq n), and add a_i to b_i or subtract a_i from b_i. What is the minimum number of moves needed to make b increasing (that is, every element is strictly greater than every element before it)?InputThe first line contains a single integer n (2 \leq n \leq 5000).The second line contains n integers, a_1, a_2, ..., a_n (1 \leq a_i \leq 10^9) — the elements of the array a.OutputPrint a single integer, the minimum number of moves to make b increasing.ExamplesInput 5 1 2 3 4 5 Output 4 Input 7 1 2 1 2 1 2 1 Output 10 Input 8 1 8 2 7 3 6 4 5 Output 16 NoteExample 1: you can subtract a_1 from b_1, and add a_3, a_4, and a_5 to b_3, b_4, and b_5 respectively. The final array will be [-1, 0, 3, 4, 5] after 4 moves.Example 2: you can reach [-3, -2, -1, 0, 1, 2, 3] in 10 moves.
5 1 2 3 4 5
4
2 seconds
256 megabytes
['brute force', 'greedy', 'math', '*1300']
L. Labyrinthtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLeslie and Leon entered a labyrinth. The labyrinth consists of n halls and m one-way passages between them. The halls are numbered from 1 to n.Leslie and Leon start their journey in the hall s. Right away, they quarrel and decide to explore the labyrinth separately. However, they want to meet again at the end of their journey.To help Leslie and Leon, your task is to find two different paths from the given hall s to some other hall t, such that these two paths do not share halls other than the staring hall s and the ending hall t. The hall t has not been determined yet, so you can choose any of the labyrinth's halls as t except s.Leslie's and Leon's paths do not have to be the shortest ones, but their paths must be simple, visiting any hall at most once. Also, they cannot visit any common halls except s and t during their journey, even at different times.InputThe first line contains three integers n, m, and s, where n (2 \le n \le 2 \cdot 10^5) is the number of vertices, m (0 \le m \le 2 \cdot 10^5) is the number of edges in the labyrinth, and s (1 \le s \le n) is the starting hall.Then m lines with descriptions of passages follow. Each description contains two integers u_i, v_i (1 \le u_i, v_i \le n; u_i \neq v_i), denoting a passage from the hall u_i to the hall v_i. The passages are one-way. Each tuple (u_i, v_i) is present in the input at most once. The labyrinth can contain cycles and is not necessarily connected in any way.OutputIf it is possible to find the desired two paths, output "Possible", otherwise output "Impossible".If the answer exists, output two path descriptions. Each description occupies two lines. The first line of the description contains an integer h (2 \le h \le n) — the number of halls in a path, and the second line contains distinct integers w_1, w_2, \dots, w_h (w_1 = s; 1 \le w_j \le n; w_h = t) — the halls in the path in the order of passing. Both paths must end at the same vertex t. The paths must be different, and all intermediate halls in these paths must be distinct.ExamplesInput 5 5 1 1 2 2 3 1 4 4 3 3 5 Output Possible 3 1 2 3 3 1 4 3 Input 5 5 1 1 2 2 3 3 4 2 5 5 4 Output Impossible Input 3 3 2 1 2 2 3 3 1 Output Impossible
5 5 1 1 2 2 3 1 4 4 3 3 5
Possible 3 1 2 3 3 1 4 3
3 seconds
512 megabytes
['dfs and similar', 'graphs', '*1800']
K. Kingdom Partitiontime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe King is gone. After the King's rule, all the roads in the Kingdom are run down and need repair. Three of the King's children, Adrian, Beatrice and Cecilia, are dividing the Kingdom between themselves.Adrian and Beatrice do not like each other and do not plan to maintain any relations between themselves in the future. Cecilia is on good terms with both of them. Moreover, most of the Kingdom's workers support Cecilia, so she has better resources and more opportunity to repair the infrastructure and develop the economy. Cecilia proposes to partition the Kingdom into three districts: A (for Adrian), B (for Beatrice), and C (for Cecilia), and let Adrian and Beatrice to negotiate and choose any towns they want to be in their districts, and agree on how they want to partition the Kingdom into three districts.Adrian's castle is located in town a, and Beatrice's one is located in town b. So Adrian and Beatrice want their castles to be located in districts A and B, respectively. Cecilia doesn't have a castle, so district C can consist of no towns.There is an issue for Adrian and Beatrice. When they choose the towns, they will have to pay for the roads' repair.The cost to repair the road of length l is 2l gold. However, Adrian and Beatrice don't have to bear all the repair costs. The repair cost for the road of length l that they bear depends on what towns it connects: For a road between two towns inside district A, Adrian has to pay 2l gold; For a road between two towns inside district B, Beatrice has to pay 2l gold; For a road between towns from district A and district C, Adrian has to pay l gold, Cecilia bears the remaining cost; For a road between towns from district B and district C, Beatrice has to pay l gold, Cecilia bears the remaining cost. The roads that connect towns from district A and district B won't be repaired, since Adrian and Beatrice are not planning to use them, so no one pays for them. Cecilia herself will repair the roads that connect the towns inside district C, so Adrian and Beatrice won't bear the cost of their repair either.Adrian and Beatrice want to minimize the total cost they spend on roads' repair. Find the cheapest way for them to partition the Kingdom into three districts.InputThe first line contains two integers n and m — the number of towns and the number of roads in the Kingdom (2 \le n \le 1000; 0 \le m \le 2000).The second line contains two integers that represent town a and town b — the towns that have to be located in district A and district B, respectively (1 \le a, b \le n; a \ne b).The following m lines describe the Kingdom roads. The i-th of them consists of three integers u_i, v_i, and l_i representing a road of length l_i between towns u_i and v_i (1 \le u_i, v_i \le n; u_i \ne v_i; 1 \le l_i \le 10^9).Each pair of towns is connected with at most one road.OutputIn the first line output a single integer — the minimum total cost of roads' repair for Adrian and Beatrice.In the second line output a string consisting of n characters 'A', 'B', and 'C', i-th of the characters representing the district that the i-th town should belong to.If several cheapest ways to partition the Kingdom exist, print any of them.ExampleInput 6 7 1 3 1 2 10 2 3 5 1 3 7 4 5 3 3 6 100 4 6 3 5 6 8 Output 16 ABBCBA NoteThe following picture illustrates the example. Adrian and Beatrice don't pay for the dashed roads, they pay 2l for the bold roads, and l for the solid roads.So the total cost is 2 \cdot 5 + 3 + 3 = 16.The castles of Adrian and Beatrice are located in bold towns.
6 7 1 3 1 2 10 2 3 5 1 3 7 4 5 3 3 6 100 4 6 3 5 6 8
16 ABBCBA
3 seconds
512 megabytes
['flows', '*3200']
J. Job Lookuptime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputJulia's n friends want to organize a startup in a new country they moved to. They assigned each other numbers from 1 to n according to the jobs they have, from the most front-end tasks to the most back-end ones. They also estimated a matrix c, where c_{ij} = c_{ji} is the average number of messages per month between people doing jobs i and j.Now they want to make a hierarchy tree. It will be a binary tree with each node containing one member of the team. Some member will be selected as a leader of the team and will be contained in the root node. In order for the leader to be able to easily reach any subordinate, for each node v of the tree, the following should apply: all members in its left subtree must have smaller numbers than v, and all members in its right subtree must have larger numbers than v.After the hierarchy tree is settled, people doing jobs i and j will be communicating via the shortest path in the tree between their nodes. Let's denote the length of this path as d_{ij}. Thus, the cost of their communication is c_{ij} \cdot d_{ij}.Your task is to find a hierarchy tree that minimizes the total cost of communication over all pairs: \sum_{1 \le i < j \le n} c_{ij} \cdot d_{ij}.InputThe first line contains an integer n (1 \le n \le 200) – the number of team members organizing a startup.The next n lines contain n integers each, j-th number in i-th line is c_{ij} — the estimated number of messages per month between team members i and j (0 \le c_{ij} \le 10^9; c_{ij} = c_{ji}; c_{ii} = 0).OutputOutput a description of a hierarchy tree that minimizes the total cost of communication. To do so, for each team member from 1 to n output the number of the member in its parent node, or 0 for the leader. If there are many optimal trees, output a description of any one of them.ExampleInput 4 0 566 1 0 566 0 239 30 1 239 0 1 0 30 1 0 Output 2 4 2 0 NoteThe minimal possible total cost is 566 \cdot 1+239 \cdot 1+30 \cdot 1+1 \cdot 2+1 \cdot 2=839:
4 0 566 1 0 566 0 239 30 1 239 0 1 0 30 1 0
2 4 2 0
3 seconds
512 megabytes
['constructive algorithms', 'dp', 'shortest paths', 'trees', '*2100']
I. Interactive Treasure Hunttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There is a grid of n\times m cells. Two treasure chests are buried in two different cells of the grid. Your task is to find both of them. You can make two types of operations: DIG r c: try to find the treasure in the cell (r, c). The interactor will tell you if you found the treasure or not. SCAN r c: scan from the cell (r, c). The result of this operation is the sum of Manhattan distances from the cell (r, c) to the cells where the treasures are hidden. Manhattan distance from a cell (r_1, c_1) to a cell (r_2, c_2) is calculated as |r_1 - r_2| + |c_1 - c_2|. You need to find the treasures in at most 7 operations. This includes both DIG and SCAN operations in total. To solve the test you need to call DIG operation at least once in both of the cells where the treasures are hidden.InteractionYour program has to process multiple test cases in a single run. First, the testing system writes t — the number of test cases (1\le t \le 100). Then, t test cases should be processed one by one.In each test case, your program should start by reading the integers n and m (2 \le n, m \le 16).Then, your program can make queries of two types: DIG r c (1\le r\le n; 1\le c\le m). The interactor responds with integer 1, if you found the treasure, and 0 if not. If you try to find the treasure in the same cell multiple times, the result will be 0 since the treasure is already found. SCAN r c (1\le r\le n; 1\le c\le m). The interactor responds with an integer that is the sum of Manhattan distances from the cell (r, c) to the cells where the treasures were hidden. The sum is calculated for both cells with treasures, even if you already found one of them. After you found both treasures, i. e. you received 1 for two DIG operations, your program should continue to the next test case or exit if that test case was the last one. ExampleInput 1 2 3 1 1 3 0 1 Output SCAN 1 2 DIG 1 2 SCAN 2 2 DIG 1 1 DIG 1 3
1 2 3 1 1 3 0 1
SCAN 1 2 DIG 1 2 SCAN 2 2 DIG 1 1 DIG 1 3
3 seconds
512 megabytes
['brute force', 'constructive algorithms', 'geometry', 'interactive', 'math', '*2200']
F. Fancy Stacktime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLittle Fiona has a collection of n blocks of various sizes a_1, a_2, \ldots, a_n, where n is even. Some of the blocks can be equal in size. She would like to put all these blocks one onto another to form a fancy stack.Let b_1, b_2, \ldots, b_n be the sizes of blocks in the stack from top to bottom. Since Fiona is using all her blocks, b_1, b_2, \ldots, b_n must be a permutation of a_1, a_2, \ldots, a_n. Fiona thinks the stack is fancy if both of the following conditions are satisfied: The second block is strictly bigger than the first one, and then each block is alternately strictly smaller or strictly bigger than the previous one. Formally, b_1 < b_2 > b_3 < b_4 > \ldots > b_{n-1} < b_n. The sizes of the blocks on even positions are strictly increasing. Formally, b_2 < b_4 < b_6 < \ldots < b_n (remember that n is even). Two stacks are considered different if their corresponding sequences b_1, b_2, \ldots, b_n differ in at least one position.Fiona wants to know how many different fancy stacks she can build with all of her blocks. Since large numbers scare Fiona, find this number modulo 998\,244\,353.InputEach input contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 2500). Description of the test cases follows.The first line of each test case contains a single integer n — the number of blocks at Fiona's disposal (2 \le n \le 5000; n is even). The second line contains n integers a_1, a_2, \ldots, a_n — the sizes of the blocks in non-decreasing order (1 \le a_1 \le a_2 \le \dotsb \le a_n \le n).It is guaranteed that the sum of n over all test cases does not exceed 5000.OutputFor each test case, print the number of ways to build a fancy stack, modulo 998\,244\,353.ExampleInput 241 2 3 481 1 2 3 4 4 6 7Output 2 4
241 2 3 481 1 2 3 4 4 6 7
2 4
3 seconds
512 megabytes
['combinatorics', 'dp', 'implementation', '*2200']
E. Even Splittime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA revolution has recently happened in Segmentland. The new government is committed to equality, and they hired you to help with land redistribution in the country.Segmentland is a segment of length l kilometers, with the capital in one of its ends. There are n citizens in Segmentland, the home of i-th citizen is located at the point a_i kilometers from the capital. No two homes are located at the same point. Each citizen should receive a segment of positive length with ends at integer distances from the capital that contains her home. The union of these segments should be the whole of Segmentland, and they should not have common points besides their ends. To ensure equality, the difference between the lengths of the longest and the shortest segments should be as small as possible.InputThe first line of the input contains two integers l and n (2 \leq l \leq 10^9; 1 \leq n \leq 10^5).The second line contains n integers a_1, a_2, \dots, a_n (0 < a_1 < a_2 < \dots < a_n < l).OutputOutput n pairs of numbers s_i, f_i (0 \leq s_i < f_i \leq l), one pair per line. The pair on i-th line denotes the ends of the [s_i, f_i] segment that i-th citizen receives.If there are many possible arrangements with the same difference between the lengths of the longest and the shortest segments, you can output any of them.ExamplesInput 6 3 1 3 5 Output 0 2 2 4 4 6 Input 10 2 1 2 Output 0 2 2 10 NoteIn the first example, it is possible to make all segments equal. Viva la revolucion! In the second example, citizens live close to the capital, so the length of the shortest segment is 2 and the length of the longest segment is 8.
6 3 1 3 5
0 2 2 4 4 6
3 seconds
512 megabytes
['binary search', 'constructive algorithms', 'greedy', 'math', '*2500']
D. Deletive Editingtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDaisy loves playing games with words. Recently, she has been playing the following Deletive Editing word game with Daniel. Daisy picks a word, for example, "DETERMINED". On each game turn, Daniel calls out a letter, for example, 'E', and Daisy removes the first occurrence of this letter from the word, getting "DTERMINED". On the next turn, Daniel calls out a letter again, for example, 'D', and Daisy removes its first occurrence, getting "TERMINED". They continue with 'I', getting "TERMNED", with 'N', getting "TERMED", and with 'D', getting "TERME". Now, if Daniel calls out the letter 'E', Daisy gets "TRME", but there is no way she can get the word "TERM" if they start playing with the word "DETERMINED".Daisy is curious if she can get the final word of her choice, starting from the given initial word, by playing this game for zero or more turns. Your task it help her to figure this out.InputThe first line of the input contains an integer n — the number of test cases (1 \le n \le 10\,000). The following n lines contain test cases. Each test case consists of two words s and t separated by a space. Each word consists of at least one and at most 30 uppercase English letters; s is the Daisy's initial word for the game; t is the final word that Daisy would like to get at the end of the game.OutputOutput n lines to the output — a single line for each test case. Output "YES" if it is possible for Daisy to get from the initial word s to the final word t by playing the Deletive Editing game. Output "NO" otherwise.ExampleInput 6DETERMINED TRMEDETERMINED TERMPSEUDOPSEUDOHYPOPARATHYROIDISM PEPADEINSTITUTIONALIZATION DONATIONCONTEST CODESOLUTION SOLUTIONOutput YES NO NO YES NO YES
6DETERMINED TRMEDETERMINED TERMPSEUDOPSEUDOHYPOPARATHYROIDISM PEPADEINSTITUTIONALIZATION DONATIONCONTEST CODESOLUTION SOLUTION
YES NO NO YES NO YES
3 seconds
512 megabytes
['greedy', '*900']
C. Connect the Pointstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given three points on a plane. You should choose some segments on the plane that are parallel to coordinate axes, so that all three points become connected. The total length of the chosen segments should be the minimal possible.Two points a and b are considered connected if there is a sequence of points p_0 = a, p_1, \ldots, p_k = b such that points p_i and p_{i+1} lie on the same segment.InputThe input consists of three lines describing three points. Each line contains two integers x and y separated by a space — the coordinates of the point (-10^9 \le x, y \le 10^9). The points are pairwise distinct.OutputOn the first line output n — the number of segments, at most 100.The next n lines should contain descriptions of segments. Output four integers x_1, y_1, x_2, y_2 on a line — the coordinates of the endpoints of the corresponding segment (-10^9 \le x_1, y_1, x_2, y_2 \le 10^9). Each segment should be either horizontal or vertical.It is guaranteed that the solution with the given constraints exists.ExampleInput 1 1 3 5 8 6 Output 3 1 1 1 5 1 5 8 5 8 5 8 6 NoteThe points and the segments from the example are shown below.
1 1 3 5 8 6
3 1 1 1 5 1 5 8 5 8 5 8 6
3 seconds
512 megabytes
['brute force', 'constructive algorithms', 'geometry', '*1800']
B. Budget Distributiontime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDistributing budgeted money with limited resources and many constraints is a hard problem. A budget plan consists of t topics; i-th topic consists of n_i items. For each topic, the optimal relative money distribution is known. The optimal relative distribution for the topic i is a list of real numbers p_{i,j}, where \sum\limits_{j=1}^{n_i}{p_{i,j}} = 1. Let's denote the amount of money assigned to j-th item of the topic i as c_{i, j}; the total amount of money for the topic is C_i = \sum\limits_{j=1}^{n_i}{c_{i,j}}. A non-optimality of the plan for the topic i is defined as \sum\limits_{j=1}^{n_i}\left|\frac{c_{i, j}}{C_i} - p_{i, j}\right|. Informally, the non-optimality is the total difference between the optimal and the actual ratios of money assigned to all the items in the topic. The total plan non-optimality is the sum of non-optimalities of all t topics. Your task is to minimize the total plan non-optimality.However, the exact amount of money available is not known yet. j-th item of i-th topic already has \hat c_{i,j} dollars assigned to it and they cannot be taken back. Also, there are q possible values of the extra unassigned amounts of money available x_k. For each of them, you need to calculate the minimal possible total non-optimality among all ways to distribute this extra money. You don't need to assign an integer amount of money to an item, any real number is possible, but all the extra money must be distributed among all the items in addition to \hat c_{i,j} already assigned. Formally, for each value of extra money x_k you'll need to find its distribution d_{i,j} such that d_{i, j} \ge 0 and \sum\limits_{i=1}^{t}\sum\limits_{j=1}^{n_i} d_{i,j} = x_k, giving the resulting budget assignments c_{i,j} = \hat c_{i,j} + d_{i,j} that minimize the total plan non-optimality.InputThe first line contains two integers t (1 \le t \le 5 \cdot 10^4) and q (1 \le q \le 3 \cdot 10^5) — the number of topics in the budget and the number of possible amounts of extra money. The next t lines contain descriptions of topics. Each line starts with an integer n_i (2 \le n_i \le 5) — the number of items in i-th topic; it is followed by n_i integers \hat c_{i, j} (0 \le \hat c_{i, j} \le 10^5; for any i, at least one of \hat c_{i,j} > 0) — the amount of money already assigned to j-th item in i-th topic; they are followed by n_i integers p'_{i,j} (1 \le p'_{i,j} \le 1000) — they determine the values of p_{i,j} as p_{i, j} = {p'_{i, j}} \big/ {\sum\limits_{j=1}^{n_i}{p'_{i, j}}} with \sum\limits_{j=1}^{n_i}{p_{i,j}} = 1. The next line contains q integers x_k (0 \le x_k \le 10^{12}) — k-th possible amount of extra money. OutputOutput q real numbers — the minimal possible non-optimality for the corresponding amount of extra money x_k. An absolute or a relative error of the answer must not exceed 10^{-6}. ExamplesInput 1 5 3 1 7 10 700 400 100 0 2 10 50 102 Output 1.0555555555555556 0.8666666666666667 0.5476190476190478 0.12745098039215708 0.0 Input 2 5 3 10 70 100 700 400 100 3 10 30 100 700 400 100 2 10 50 70 110 Output 2.2967032967032974 2.216776340655188 1.8690167362600323 1.7301587301587305 1.5271317829457367
1 5 3 1 7 10 700 400 100 0 2 10 50 102
1.0555555555555556 0.8666666666666667 0.5476190476190478 0.12745098039215708 0.0
3 seconds
512 megabytes
['*3300']
A. Admissible Maptime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA map is a matrix consisting of symbols from the set of 'U', 'L', 'D', and 'R'.A map graph of a map matrix a is a directed graph with n \cdot m vertices numbered as (i, j) (1 \le i \le n; 1 \le j \le m), where n is the number of rows in the matrix, m is the number of columns in the matrix. The graph has n \cdot m directed edges (i, j) \to (i + di_{a_{i, j}}, j + dj_{a_{i, j}}), where (di_U, dj_U) = (-1, 0); (di_L, dj_L) = (0, -1); (di_D, dj_D) = (1, 0); (di_R, dj_R) = (0, 1). A map graph is valid when all edges point to valid vertices in the graph.An admissible map is a map such that its map graph is valid and consists of a set of cycles.A description of a map a is a concatenation of all rows of the map — a string a_{1,1} a_{1,2} \ldots a_{1, m} a_{2, 1} \ldots a_{n, m}.You are given a string s. Your task is to find how many substrings of this string can constitute a description of some admissible map. A substring of a string s_1s_2 \ldots s_l of length l is defined by a pair of indices p and q (1 \le p \le q \le l) and is equal to s_ps_{p+1} \ldots s_q. Two substrings of s are considered different when the pair of their indices (p, q) differs, even if they represent the same resulting string.InputIn the only input line, there is a string s, consisting of at least one and at most 20\,000 symbols 'U', 'L', 'D', or 'R'.OutputOutput one integer — the number of substrings of s that constitute a description of some admissible map.ExamplesInput RDUL Output 2 Input RDRU Output 0 Input RLRLRL Output 6 NoteIn the first example, there are two substrings that can constitute a description of an admissible map — "RDUL" as a matrix of size 2 \times 2 (pic. 1) and "DU" as a matrix of size 2 \times 1 (pic. 2). In the second example, no substring can constitute a description of an admissible map. E. g. if we try to look at the string "RDRU" as a matrix of size 2 \times 2, we can find out that the resulting graph is not a set of cycles (pic. 3).In the third example, three substrings "RL", two substrings "RLRL" and one substring "RLRLRL" can constitute an admissible map, some of them in multiple ways. E. g. here are two illustrations of substring "RLRLRL" as matrices of size 3 \times 2 (pic. 4) and 1 \times 6 (pic. 5).
RDUL
2
3 seconds
512 megabytes
['*3300']
E. MinimizORtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n non-negative integers, numbered from 1 to n.Let's define the cost of the array a as \displaystyle \min_{i \neq j} a_i | a_j, where | denotes the bitwise OR operation.There are q queries. For each query you are given two integers l and r (l < r). For each query you should find the cost of the subarray a_{l}, a_{l + 1}, \ldots, a_{r}.InputEach test case consists of several test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains an integer n (2 \le n \le 10^5) — the length array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i < 2^{30}) — the elements of a.The third line of each test case contains an integer q (1 \le q \le 10^5) — the number of queries.Each of the next q lines contains two integers l_j, r_j (1 \le l_j < r_j \le n) — the description of the j-th query.It is guaranteed that the sum of n and the sum of q over all test cases do not exceed 10^5.OutputFor each test case print q numbers, where the j-th number is the cost of array a_{l_j}, a_{l_j + 1}, \ldots, a_{r_j}.ExampleInput 256 1 3 2 141 22 32 42 540 2 1 107374182341 22 31 33 4Output 7 3 3 1 2 3 1 1073741823 NoteIn the first test case the array a is110_2, 001_2, 011_2, 010_2, 001_2.That's why the answers for the queries are: [1; 2]: a_1 | a_2 = 110_2 | 001_2 = 111_2 = 7; [2; 3]: a_2 | a_3 = 001_2 | 011_2 = 011_2 = 3; [2; 4]: a_2 | a_3 = a_3 | a_4 = a_2 | a_4 = 011_2 = 3; [2; 5]: a_2 | a_5 = 001_2 = 1. In the second test case the array a is00_2, 10_2, 01_2, \underbrace{11\ldots 1_2}_{30} (a_4 = 2^{30} - 1).That's why the answers for the queries are: [1; 2]: a_1 | a_2 = 10_2 = 2; [2; 3]: a_2 | a_3 = 11_2 = 3; [1; 3]: a_1 | a_3 = 01_2 = 1; [3; 4]: a_3 | a_4 = 01_2 | \underbrace{11\ldots 1_2}_{30} = 2^{30} - 1 = 1073741823.
256 1 3 2 141 22 32 42 540 2 1 107374182341 22 31 33 4
7 3 3 1 2 3 1 1073741823
3 seconds
256 megabytes
['bitmasks', 'brute force', 'data structures', 'divide and conquer', 'greedy', 'implementation', 'two pointers', '*2500']
D. GCD Guesstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There is a positive integer 1 \le x \le 10^9 that you have to guess.In one query you can choose two positive integers a \neq b. As an answer to this query you will get \gcd(x + a, x + b), where \gcd(n, m) is the greatest common divisor of the numbers n and m.To guess one hidden number x you are allowed to make no more than 30 queries.InputThe first line of input contains a single integer t (1 \le t \le 1000) denoting the number of test cases.The integer x that you have to guess satisfies the constraints: (1 \le x \le 10^9).InteractionThe hidden number x is fixed before the start of the interaction and does not depend on your queries.To guess each x you can make no more than 30 queries in the following way: "? a b" (1 \le a, b \le 2 \cdot 10^9, a \neq b). For this query you will get \gcd(x + a, x + b).When you know x, print a single line in the following format. "! x" (1 \le x \le 10^9). After that continue to solve the next test case.If you ask more than 30 queries for one x or make an invalid query, the interactor will terminate immediately and your program will receive verdict Wrong Answer.After printing each query do not forget to output end of line and flush the output buffer. Otherwise, you will get the Idleness limit exceeded verdict. To do flush use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; Read documentation for other languages. HacksTo use hacks, use the following format of tests:The first line should contain a single integer t (1 \le t \le 1000) — the number of test cases.The first and only line of each test case should contain a single integer x (1 \le x \le 10^9) denoting the integer x that should be guessed.ExampleInput 2 1 8 1 Output ? 1 2 ? 12 4 ! 4 ? 2000000000 1999999999 ! 1000000000 NoteThe first hidden number is 4, that's why the answers for the queries are:"? 1 2" — \gcd(4 + 1, 4 + 2) = \gcd(5, 6) = 1."? 12 4" — \gcd(4 + 12, 4 + 4) = \gcd(16, 8) = 8.The second hidden number is 10^9, that's why the answer for the query is:"? 2000000000 1999999999" — \gcd(3 \cdot 10^9, 3 \cdot 10^9 - 1) = 1.These queries are made only for understanding the interaction and are not enough for finding the true x.
2 1 8 1
? 1 2 ? 12 4 ! 4 ? 2000000000 1999999999 ! 1000000000
3 seconds
256 megabytes
['bitmasks', 'chinese remainder theorem', 'constructive algorithms', 'games', 'interactive', 'math', 'number theory', '*2000']
C. Tree Infectiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex v (different from root) is the previous to v vertex on the shortest path from the root to the vertex v. Children of the vertex v are all vertices for which v is the parent.You are given a rooted tree with n vertices. The vertex 1 is the root. Initially, all vertices are healthy.Each second you do two operations, the spreading operation and, after that, the injection operation: Spreading: for each vertex v, if at least one child of v is infected, you can spread the disease by infecting at most one other child of v of your choice. Injection: you can choose any healthy vertex and infect it. This process repeats each second until the whole tree is infected. You need to find the minimal number of seconds needed to infect the whole tree.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of the vertices in the given tree.The second line of each test case contains n - 1 integers p_2, p_3, \ldots, p_n (1 \le p_i \le n), where p_i is the ancestor of the i-th vertex in the tree.It is guaranteed that the given graph is a tree.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case you should output a single integer — the minimal number of seconds needed to infect the whole tree.ExampleInput 571 1 1 2 2 455 5 1 42133 161 1 1 1 1Output 4 4 2 3 4 NoteThe image depicts the tree from the first test case during each second.A vertex is black if it is not infected. A vertex is blue if it is infected by injection during the previous second. A vertex is green if it is infected by spreading during the previous second. A vertex is red if it is infected earlier than the previous second. Note that you are able to choose which vertices are infected by spreading and by injections.
571 1 1 2 2 455 5 1 42133 161 1 1 1 1
4 4 2 3 4
1 second
256 megabytes
['binary search', 'greedy', 'sortings', 'trees', '*1600']
B. Array Cloning Techniquetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers. Initially there is only one copy of the given array.You can do operations of two types: Choose any array and clone it. After that there is one more copy of the chosen array. Swap two elements from any two copies (maybe in the same copy) on any positions. You need to find the minimal number of operations needed to obtain a copy where all elements are equal.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9) — the elements of the array a.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case output a single integer — the minimal number of operations needed to create at least one copy where all elements are equal.ExampleInput 61178960 1 3 3 7 02-1000000000 100000000044 3 2 152 5 7 6 371 1 1 1 1 1 1Output 0 6 2 5 7 0 NoteIn the first test case all elements in the array are already equal, that's why the answer is 0.In the second test case it is possible to create a copy of the given array. After that there will be two identical arrays:[ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ] and [ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]After that we can swap elements in a way so all zeroes are in one array:[ \ 0 \ \underline{0} \ \underline{0} \ 3 \ 7 \ 0 \ ] and [ \ \underline{1} \ 1 \ 3 \ 3 \ 7 \ \underline{3} \ ]Now let's create a copy of the first array:[ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ], [ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ] and [ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]Let's swap elements in the first two copies:[ \ 0 \ 0 \ 0 \ \underline{0} \ \underline{0} \ 0 \ ], [ \ \underline{3} \ \underline{7} \ 0 \ 3 \ 7 \ 0 \ ] and [ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ].Finally, we made a copy where all elements are equal and made 6 operations.It can be proven that no fewer operations are enough.
61178960 1 3 3 7 02-1000000000 100000000044 3 2 152 5 7 6 371 1 1 1 1 1 1
0 6 2 5 7 0
1 second
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*900']
A. GCD vs LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. You have to find 4 positive integers a, b, c, d such that a + b + c + d = n, and \gcd(a, b) = \operatorname{lcm}(c, d).If there are several possible answers you can output any of them. It is possible to show that the answer always exists.In this problem \gcd(a, b) denotes the greatest common divisor of a and b, and \operatorname{lcm}(c, d) denotes the least common multiple of c and d.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.Each test case contains a single line with integer n (4 \le n \le 10^9) — the sum of a, b, c, and d.OutputFor each test case output 4 positive integers a, b, c, d such that a + b + c + d = n and \gcd(a, b) = \operatorname{lcm}(c, d).ExampleInput 5478910Output 1 1 1 1 2 2 2 1 2 2 2 2 2 4 2 1 3 5 1 1NoteIn the first test case \gcd(1, 1) = \operatorname{lcm}(1, 1) = 1, 1 + 1 + 1 + 1 = 4.In the second test case \gcd(2, 2) = \operatorname{lcm}(2, 1) = 2, 2 + 2 + 2 + 1 = 7.In the third test case \gcd(2, 2) = \operatorname{lcm}(2, 2) = 2, 2 + 2 + 2 + 2 = 8.In the fourth test case \gcd(2, 4) = \operatorname{lcm}(2, 1) = 2, 2 + 4 + 2 + 1 = 9.In the fifth test case \gcd(3, 5) = \operatorname{lcm}(1, 1) = 1, 3 + 5 + 1 + 1 = 10.
5478910
1 1 1 1 2 2 2 1 2 2 2 2 2 4 2 1 3 5 1 1
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
F. In Every Generation...time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output In every generation there is a Chosen One. She alone will stand against the vampires, the demons, and the forces of darkness. She is the Slayer. — Joss Whedon InputA string s (3 \le |s| \le 7) consisting of lowercase English letters.OutputA single string. If there is no answer, print "none" (without the quotes).ExampleInput tourist Output ooggqjx
tourist
ooggqjx
1 second
256 megabytes
['*special problem', 'strings']
E. Are You Safe?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSeven boys and seven girls from Athens were brought before King Minos. The evil king laughed and said "I hope you enjoy your stay in Crete".With a loud clang, the doors behind them shut, and darkness reigned. The terrified children huddled together. In the distance they heard a bellowing, unholy roar.Bravely, they advanced forward, to their doom.Inputn (1 \le n \le 100) — the dimensions of the labyrinth. Each of the next n lines contains a string of lowercase English letters of length n.ExampleInput 10 atzxcodera mzhappyayc mineodteri trxesonaac mtollexcxc hjikeoutlc eascripsni rgvymnjcxm onzazwswwg geothermal Output YES
10 atzxcodera mzhappyayc mineodteri trxesonaac mtollexcxc hjikeoutlc eascripsni rgvymnjcxm onzazwswwg geothermal
YES
1 second
256 megabytes
['*special problem', 'implementation']
B. Mike's Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou won't find this sequence on OEIS.InputOne integer r (-45 \le r \le 2999).OutputOne integer.ExampleInput 2999 Output 3000
2999
3000
1 second
256 megabytes
['*special problem', 'divide and conquer', 'implementation', 'math']
O. Circular Mazetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a circular maze such as the ones shown in the figures. Determine if it can be solved, i.e., if there is a path which goes from the center to the outside of the maze which does not touch any wall. The maze is described by n walls. Each wall can be either circular or straight. Circular walls are described by a radius r, the distance from the center, and two angles \theta_1, \theta_2 describing the beginning and the end of the wall in the clockwise direction. Notice that swapping the two angles changes the wall. Straight walls are described by an angle \theta, the direction of the wall, and two radii r_1 < r_2 describing the beginning and the end of the wall. Angles are measured in degrees; the angle 0 corresponds to the upward pointing direction; and angles increase clockwise (hence the east direction corresponds to the angle 90).InputEach test contains multiple test cases. The first line contains an integer t (1\le t\le 20) — the number of test cases. The descriptions of the t test cases follow.The first line of each test case contains an integer n (1 \leq n \leq 5000) — the number of walls. Each of the following n lines each contains a character (C for circular, and S for straight) and three integers: either r, \theta_1, \theta_2 (1 \leq r \leq 20 and 0 \leq \theta_1,\theta_2 < 360 with \theta_1 \neq \theta_2) if the wall is circular, or r_1, r_2 and \theta (1 \leq r_1 < r_2 \leq 20 and 0 \leq \theta < 360) if the wall is straight. It is guaranteed that circular walls do not overlap (but two circular walls may intersect at one or two points), and that straight walls do not overlap (but two straight walls may intersect at one point). However, circular and straight walls can intersect arbitrarily.OutputFor each test case, print YES if the maze can be solved and NO otherwise. ExampleInput 2 5 C 1 180 90 C 5 250 230 C 10 150 140 C 20 185 180 S 1 20 180 6 C 1 180 90 C 5 250 230 C 10 150 140 C 20 185 180 S 1 20 180 S 5 10 0 Output YES NO NoteThe two sample test cases correspond to the two mazes in the picture.
2 5 C 1 180 90 C 5 250 230 C 10 150 140 C 20 185 180 S 1 20 180 6 C 1 180 90 C 5 250 230 C 10 150 140 C 20 185 180 S 1 20 180 S 5 10 0
YES NO
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'graphs', 'implementation']
N. Drone Phototime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputToday, like every year at SWERC, the n^2 contestants have gathered outside the venue to take a drone photo. Jennifer, the social media manager for the event, has arranged them into an n\times n square. Being very good at her job, she knows that the contestant standing on the intersection of the i-th row with the j-th column is a_{i,j} years old. Coincidentally, she notices that no two contestants have the same age, and that everyone is between 1 and n^2 years old.Jennifer is planning to have some contestants hold a banner with the ICPC logo parallel to the ground, so that it is clearly visible in the aerial picture. Here are the steps that she is going to follow in order to take the perfect SWERC drone photo. First of all, Jennifer is going to select four contestants standing on the vertices of an axis-aligned rectangle. Then, she will have the two younger contestants hold one of the poles, while the two older contestants will hold the other pole. Finally, she will unfold the banner, using the poles to support its two ends. Obviously, this can only be done if the two poles are parallel and do not cross, as shown in the pictures below. Being very indecisive, Jennifer would like to try out all possible arrangements for the banner, but she is worried that this may cause the contestants to be late for the competition. How many different ways are there to choose the four contestants holding the poles in order to take a perfect photo? Two choices are considered different if at least one contestant is included in one but not the other.InputThe first line contains a single integer n (2\le n \le 1500).The next n lines describe the ages of the contestants. Specifically, the i-th line contains the integers a_{i,1},a_{i,2},\ldots,a_{i,n} (1\le a_{i,j}\le n^2).It is guaranteed that a_{i,j}\neq a_{k,l} if i\neq k or j\neq l.OutputPrint the number of ways for Jennifer to choose the four contestants holding the poles.ExamplesInput 2 1 3 4 2 Output 0 Input 2 3 2 4 1 Output 1 Input 3 9 2 4 1 5 3 7 8 6 Output 6 NoteIn the first sample, there are 4 contestants, arranged as follows. There is only one way to choose four contestants, with one pole held by contestants aged 1 and 2 and the other one by contestants aged 3 and 4. But then, as we can see in the picture, the poles cross. Since there is no valid way to choose four contestants, the answer is 0.In the second sample, the 4 contestants are arranged as follows. Once again, there is only one way to choose four contestants, but this time the poles don't cross. Therefore, the answer is 1.In the third sample, the 9 contestants are arranged as follows. There are 6 ways of choosing four contestants so that the poles don't cross, as shown in the following pictures.
2 1 3 4 2
0
2 seconds
512 megabytes
['combinatorics', 'math', 'sortings']
M. Bottle Arrangementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGabriella has been instructed to organize a renowned wine tasting event which will be attended by m critics. On display, there will be n different varieties of wine, each of which can either be a red wine or a white wine.The wines will come in n bottles arranged in a line on the table, and, for convenience, each critic will sip from a contiguous interval of bottles: that is, he/she will taste exactly the bottles at position a, \, a + 1, \, \dots, \, b for some 1 \le a \le b \le n. The interval depends on the critic, who will select it on the spot according to their preferences. In fact, the i-th critic (1 \le i \le m) has requested that he/she wants to taste exactly r_i red wines and w_i white wines.Gabriella has yet to choose how many bottles of red wine and white wine there will be, and in what order they will appear. Help her find an arrangement (that is, a sequence of n bottles of either red or white wine) that satisfies the requests of all the critics, or state that no such arrangement exists.InputEach test contains multiple test cases. The first line contains an integer t (1\le t\le 100) — the number of test cases. The descriptions of the t test cases follow.The first line of each test case contains two integers n and m (1 \le n \le 100, 1 \le m \le 100) — the number of bottles of wine and the number of critics.Each of the next m lines contains two integers r_i and w_i (0 \le r_i, \, w_i \le 100, r_i + w_i \ge 1) — the number of red and white wines that the i-th critic wants to taste.OutputFor each test case, if at least one solution exists, print a string of length n made up of the characters R and W, where the j-th character (1 \le j \le n) denotes the type of the wine in the j-th bottle of the arrangement (R for red and W for white). If there are multiple solutions, print any.If no solution exists, print the string IMPOSSIBLE.ExampleInput 35 31 03 22 24 32 11 10 33 20 20 3Output RWRRW IMPOSSIBLE WWW NoteIn the first test case, there are n = 5 bottles of wine to be arranged and m = 3 critics. The arrangement RWRRW satisfies the requests of all three critics. Indeed: the first critic can choose the interval [3, \, 3], which contains exactly one bottle of red wine (note that [1, \, 1] and [4, \, 4] are other valid choices); the second critic can choose the interval [1, \, 5], which contains 3 bottles of red wine and 2 bottles of white wine; the third critic can choose the interval [2, \, 5], which contains 2 bottles of red wine and 2 bottles of white wine.
35 31 03 22 24 32 11 10 33 20 20 3
RWRRW IMPOSSIBLE WWW
2 seconds
256 megabytes
['constructive algorithms']
L. Il Derby della Madonninatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe derby between Milan and Inter is happening soon, and you have been chosen as the assistant referee for the match, also known as linesman. Your task is to move along the touch-line, namely the side of the field, always looking very carefully at the match to check for offside positions and other offences.Football is an extremely serious matter in Italy, and thus it is fundamental that you keep very close track of the ball for as much time as possible. This means that you want to maximise the number of kicks which you monitor closely. You are able to monitor closely a kick if, when it happens, you are in the position along the touch-line with minimum distance from the place where the kick happens.Fortunately, expert analysts have been able to accurately predict all the kicks which will occur during the game. That is, you have been given two lists of integers, t_1, \ldots, t_n and a_1, \ldots, a_n, indicating that t_i seconds after the beginning of the match the ball will be kicked and you can monitor closely such kick if you are at the position a_i along the touch-line. At the beginning of the game you start at position 0 and the maximum speed at which you can walk along the touch-line is v units per second (i.e., you can change your position by at most v each second). What is the maximum number of kicks that you can monitor closely?InputThe first line contains two integers n and v (1 \le n \le 2 \cdot 10^5, 1 \le v \le 10^6) — the number of kicks that will take place and your maximum speed.The second line contains n integers t_1, \ldots, t_n (1 \le t_i \le 10^9) — the times of the kicks in the match. The sequence of times is guaranteed to be strictly increasing, i.e., t_1 < t_2 < \cdots < t_n.The third line contains n integers a_1, \ldots, a_n (-10^9 \le a_i \le 10^9) — the positions along the touch-line where you have to be to monitor closely each kick.OutputPrint the maximum number of kicks that you can monitor closely.ExamplesInput 3 2 5 10 15 7 17 29 Output 2 Input 5 1 5 7 8 11 13 3 3 -2 -2 4 Output 3 Input 1 2 3 7 Output 0 NoteIn the first sample, it is possible to move to the right at maximum speed for the first 3.5 seconds and stay at position 7 until the first kick happens, and then immediately move right also at maximum speed to watch the second kick at position 17. There is no way to monitor closely the third kick after the second kick, so at most 2 kicks can be seen.
3 2 5 10 15 7 17 29
2
2 seconds
256 megabytes
['data structures', 'dp', 'math']
K. Pandemic Restrictionstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long time living abroad, you have decided to move back to Italy and have to find a place to live, but things are not so easy due to the ongoing global pandemic.Your three friends Fabio, Flavio and Francesco live at the points with coordinates (x_1, y_1), (x_2, y_2) and (x_3, y_3), respectively. Due to the mobility restrictions in response to the pandemic, meetings are limited to 3 persons, so you will only be able to meet 2 of your friends at a time. Moreover, in order to contain the spread of the infection, the authorities have imposed the following additional measure: for each meeting, the sum of the lengths travelled by each of the attendees from their residence place to the place of the meeting must not exceed r.What is the minimum value of r (which can be any nonnegative real number) for which there exists a place of residence that allows you to hold the three possible meetings involving you and two of your friends? Note that the chosen place of residence need not have integer coordinates.InputThe first line contains the two integers x_1, y_1 (-10^4 \le x_1, y_1 \le 10^4) — the coordinates of the house of your friend Fabio.The second line contains the two integers x_2, y_2 (-10^4 \le x_2, y_2 \le 10^4) — the coordinates of the house of your friend Flavio.The third line contains the two integers x_3, y_3 (-10^4 \le x_3, y_3 \le 10^4) — the coordinates of the house of your friend Francesco.It is guaranteed that your three friends live in different places (i.e., the three points (x_1, y_1), (x_2, y_2), (x_3, y_3) are guaranteed to be distinct).OutputPrint the minimum value of r which allows you to find a residence place satisfying the above conditions. 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 0 0 5 0 3 3 Output 5.0686143166 Input -1 0 0 0 1 0 Output 2.0000000000 NoteIn the first sample, Fabio, Flavio and Francesco live at the points with coordinates (0,0), (5,0) and (3,3) respectively. The optimal place of residence, represented by a green house in the picture below, is at the point with coordinates (2.3842..., 0.4151...). For instance, it is possible for you to meet Flavio and Francesco at the point depicted below, so that the sum of the lengths travelled by the three attendees is at most (and in fact equal to) r=5.0686.... In the second sample, any point on the segment \{(x,0):\ -1 \leq x \leq 1 \} is an optimal place of residence.
0 0 5 0 3 3
5.0686143166
4 seconds
256 megabytes
['geometry', 'ternary search']
J. Training Camptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are organizing a training camp to teach algorithms to young kids. There are n^2 kids, organized in an n by n grid. Each kid is between 1 and n years old (inclusive) and any two kids who are in the same row or in the same column have different ages.You want to select exactly n kids for a programming competition, with exactly one kid from each row and one kid from each column. Moreover, kids who are not selected must be either older than both kids selected in their row and column, or younger than both kids selected in their row and column (otherwise they will complain). Notice that it is always possible to select n kids satisfying these requirements (for example by selecting n kids who have the same age).During the training camp, you observed that some kids are good at programming, and the others are not. What is the maximum number of kids good at programming that you can select while satisfying all the requirements?InputThe first line contains n (1 \leq n \leq 128) — the size of the grid.The following n lines describe the ages of the kids. Specifically, the i-th line contains n integers a_{i,1}, \, a_{i,2}, \, \dots, \, a_{i, n} (1 \le a_{i,j} \le n) — where a_{i,j} is the age of the kid in the i-th row and j-th column. It is guaranteed that two kids on the same row or column have different ages, i.e., a_{i,j} \ne a_{i,j'} for any 1\le i\le n, 1\le j < j'\le n, and a_{i,j} \ne a_{i',j} for any 1\le i < i'\le n, 1\le j\le n.The following n lines describe the programming skills of the kids. Specifically, the i-th line contains n integers c_{i,1}, \, c_{i,2}, \, \dots, \, c_{i, n} (c_{i,j} \in \{0, \, 1\}) — where c_{i,j}=1 if the kid in the i-th row and j-th column is good at programming and c_{i,j}=0 otherwise.OutputPrint the maximum number of kids good at programming that you can select while satisfying all the requirements.ExamplesInput 3 1 2 3 3 1 2 2 3 1 1 0 0 0 0 1 0 0 0 Output 1 Input 4 1 2 3 4 2 1 4 3 3 4 1 2 4 3 2 1 1 1 1 0 0 0 1 0 1 1 0 1 0 0 0 1 Output 2 NoteIn the first sample, it is not possible to select the two kids good at programming (in row 1 and column 1, and in row 2 and column 3), because then you would have to select the kid in row 3 and column 2, and in that case two kids would complain (the one in row 1 and column 2, and the one in row 3 and column 1).A valid selection which contains 1 kid good at programming is achieved by choosing the 3 kids who are 1 year old.In the second sample, there are 10 valid choices of the n kids that satisfy the requirements, and each of them selects exactly 2 kids good at programming.
3 1 2 3 3 1 2 2 3 1 1 0 0 0 0 1 0 0 0
1
2 seconds
256 megabytes
['flows', 'graphs']
I. Ice Cream Shoptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a beach there are n huts in a perfect line, hut 1 being at the left and hut i+1 being 100 meters to the right of hut i, for all 1 \le i \le n - 1. In hut i there are p_i people.There are m ice cream sellers, also aligned in a perfect line with all the huts. The i-th ice cream seller has their shop x_i meters to the right of the first hut. All ice cream shops are at distinct locations, but they may be at the same location as a hut.You want to open a new ice cream shop and you wonder what the best location for your shop is. You can place your ice cream shop anywhere on the beach (not necessarily at an integer distance from the first hut) as long as it is aligned with the huts and the other ice cream shops, even if there is already another ice cream shop or a hut at that location. You know that people would come to your shop only if it is strictly closer to their hut than any other ice cream shop.If every person living in the huts wants to buy exactly one ice cream, what is the maximum number of ice creams that you can sell if you place the shop optimally?InputThe first line contains two integers n and m (2 \le n \le 200\,000, 1 \le m \le 200\,000) — the number of huts and the number of ice cream sellers.The second line contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le 10^9) — the number of people in each hut.The third line contains m integers x_1, x_2, \ldots, x_m (0 \le x_i \le 10^9, x_i \ne x_j for i \ne j) — the location of each ice cream shop.OutputPrint the maximum number of ice creams that can be sold by choosing optimally the location of the new shop.ExamplesInput 3 1 2 5 6 169 Output 7 Input 4 2 1 2 7 8 35 157 Output 15 Input 4 1 272203905 348354708 848256926 939404176 20 Output 2136015810 Input 3 2 1 1 1 300 99 Output 2 NoteIn the first sample, you can place the shop (coloured orange in the picture below) 150 meters to the right of the first hut (for example) so that it is the closest shop to the first two huts, which have 2 and 5 people, for a total of 7 sold ice creams. In the second sample, you can place the shop 170 meters to the right of the first hut (for example) so that it is the closest shop to the last two huts, which have 7 and 8 people, for a total of 15 sold ice creams.
3 1 2 5 6 169
7
2 seconds
256 megabytes
['brute force', 'implementation', 'sortings']
H. Boundarytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBethany would like to tile her bathroom. The bathroom has width w centimeters and length l centimeters. If Bethany simply used the basic tiles of size 1 \times 1 centimeters, she would use w \cdot l of them. However, she has something different in mind. On the interior of the floor she wants to use the 1 \times 1 tiles. She needs exactly (w-2) \cdot (l-2) of these. On the floor boundary she wants to use tiles of size 1 \times a for some positive integer a. The tiles can also be rotated by 90 degrees. For which values of a can Bethany tile the bathroom floor as described? Note that a can also be 1. InputEach test contains multiple test cases. The first line contains an integer t (1\le t\le 100) — the number of test cases. The descriptions of the t test cases follow.Each test case consist of a single line, which contains two integers w, l (3 \leq w, l \leq 10^{9}) — the dimensions of the bathroom.OutputFor each test case, print an integer k (0\le k) — the number of valid values of a for the given test case — followed by k integers a_1, a_2,\dots, a_k (1\le a_i) — the valid values of a. The values a_1, a_2, \dots, a_k have to be sorted from smallest to largest.It is guaranteed that under the problem constraints, the output contains at most 200\,000 integers. ExampleInput 33 512 12314159265 358979323Output 3 1 2 3 3 1 2 11 2 1 2 NoteIn the first test case, the bathroom is 3 centimeters wide and 5 centimeters long. There are three values of a such that Bethany can tile the floor as described in the statement, namely a=1, a=2 and a=3. The three tilings are represented in the following pictures.
33 512 12314159265 358979323
3 1 2 3 3 1 2 11 2 1 2
2 seconds
256 megabytes
['brute force', 'math']
G. Gastronomic Eventtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSWERC organizers want to hold a gastronomic event.The location of the event is a building with n rooms connected by n-1 corridors (each corridor connects two rooms) so that it is possible to go from any room to any other room.In each room you have to set up the tasting of a typical Italian dish. You can choose from n typical Italian dishes rated from 1 to n depending on how good they are (n is the best possible rating). The n dishes have distinct ratings.You want to assign the n dishes to the n rooms so that the number of pleasing tours is maximal. A pleasing tour is a nonempty sequence of rooms so that: Each room in the sequence is connected to the next one in the sequence by a corridor. The ratings of the dishes in the rooms (in the order given by the sequence) are increasing. If you assign the n dishes optimally, what is the maximum number of pleasing tours?InputThe first line contains an integer n (2\le n\le 1\,000\,000) — the number of rooms.The second line contains n-1 integers p_2, p_3, \cdots , p_n (1 \leq p_i < i). Each p_i indicates that there is a corridor between room i and room p_i. It is guaranteed that the building has the property that it is possible to go from any room to any other room.OutputPrint the maximum number of pleasing tours.ExamplesInput 5 1 2 2 2 Output 13 Input 10 1 2 3 4 3 2 7 8 7 Output 47 NoteIn the first sample, it is optimal to place the dish with rating 1 in room 1, the dish with rating 2 in room 3, the dish with rating 3 in room 2, the dish with rating 4 in room 5 and the dish with rating 5 in room 4. All the 13 possible pleasing tours are: (1), (2), (3), (4), (5), (1,2), (3,2), (2,4), (2,5), (1,2,4), (1,2,5), (3,2,4), (3,2,5).There are also other ways to assign the dishes to the rooms so that there are 13 pleasing tours.
5 1 2 2 2
13
2 seconds
512 megabytes
['dp', 'greedy', 'trees']
F. Antennastime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n equidistant antennas on a line, numbered from 1 to n. Each antenna has a power rating, the power of the i-th antenna is p_i. The i-th and the j-th antenna can communicate directly if and only if their distance is at most the minimum of their powers, i.e., |i-j| \leq \min(p_i, p_j). Sending a message directly between two such antennas takes 1 second.What is the minimum amount of time necessary to send a message from antenna a to antenna b, possibly using other antennas as relays?InputEach test contains multiple test cases. The first line contains an integer t (1\le t\le 100\,000) — the number of test cases. The descriptions of the t test cases follow.The first line of each test case contains three integers n, a, b (1 \leq a, b \leq n \leq 200\,000) — the number of antennas, and the origin and target antenna. The second line contains n integers p_1, p_2, \dots, p_n (1 \leq p_i \leq n) — the powers of the antennas.The sum of the values of n over all test cases does not exceed 200\,000. OutputFor each test case, print the number of seconds needed to trasmit a message from a to b. It can be shown that under the problem constraints, it is always possible to send such a message.ExampleInput 310 2 94 1 1 1 5 1 1 1 1 51 1 113 1 33 3 1Output 4 0 2 NoteIn the first test case, we must send a message from antenna 2 to antenna 9. A sequence of communications requiring 4 seconds, which is the minimum possible amount of time, is the following: In 1 second we send the message from antenna 2 to antenna 1. This is possible since |2-1|\le \min(1, 4) = \min(p_2, p_1). In 1 second we send the message from antenna 1 to antenna 5. This is possible since |1-5|\le \min(4, 5) = \min(p_1, p_5). In 1 second we send the message from antenna 5 to antenna 10. This is possible since |5-10|\le \min(5, 5) = \min(p_5, p_{10}). In 1 second we send the message from antenna 10 to antenna 9. This is possible since |10-9|\le \min(5, 1) = \min(p_{10}, p_9).
310 2 94 1 1 1 5 1 1 1 1 51 1 113 1 33 3 1
4 0 2
4 seconds
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'graphs', 'implementation', 'implementation', 'shortest paths', 'shortest paths']
E. Round Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people, numbered from 1 to n, sitting at a round table. Person i+1 is sitting to the right of person i (with person 1 sitting to the right of person n).You have come up with a better seating arrangement, which is given as a permutation p_1, p_2, \dots, p_n. More specifically, you want to change the seats of the people so that at the end person p_{i+1} is sitting to the right of person p_i (with person p_1 sitting to the right of person p_n). Notice that for each seating arrangement there are n permutations that describe it (which can be obtained by rotations).In order to achieve that, you can swap two people sitting at adjacent places; but there is a catch: for all 1 \le x \le n-1 you cannot swap person x and person x+1 (notice that you can swap person n and person 1). What is the minimum number of swaps necessary? It can be proven that any arrangement can be achieved.InputEach test contains multiple test cases. The first line contains an integer t (1\le t\le 10\,000) — the number of test cases. The descriptions of the t test cases follow.The first line of each test case contains a single integer n (3 \le n \le 200\,000) — the number of people sitting at the table. The second line contains n distinct integers p_1, p_2, \dots, p_n (1 \le p_i \le n, p_i \ne p_j for i \ne j) — the desired final order of the people around the table.The sum of the values of n over all test cases does not exceed 200\,000.OutputFor each test case, print the minimum number of swaps necessary to achieve the desired order.ExampleInput 342 3 1 455 4 3 2 174 1 6 5 3 7 2Output 1 10 22 NoteIn the first test case, we can swap person 4 and person 1 (who are adjacent) in the initial configuration and get the order [4, 2, 3, 1] which is equivalent to the desired one. Hence in this case a single swap is sufficient.
342 3 1 455 4 3 2 174 1 6 5 3 7 2
1 10 22
2 seconds
256 megabytes
['math']
D. Evolution of Weaselstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA wild basilisk just appeared at your doorstep. You are not entirely sure what a basilisk is and you wonder whether it evolved from your favorite animal, the weasel. How can you find out whether basilisks evolved from weasels? Certainly, a good first step is to sequence both of their DNAs. Then you can try to check whether there is a sequence of possible mutations from the DNA of the weasel to the DNA of the basilisk. Your friend Ron is a talented alchemist and has studied DNA sequences in many of his experiments. He has found out that DNA strings consist of the letters A, B and C and that single mutations can only remove or add substrings at any position in the string (a substring is a contiguous sequence of characters). The substrings that can be removed or added by a mutation are AA, BB, CC, ABAB or BCBC. During a sequence of mutations a DNA string may even become empty.Ron has agreed to sequence the DNA of the weasel and the basilisk for you, but finding out whether there is a sequence of possible mutations that leads from one to the other is too difficult for him, so you have to do it on your own. InputEach test contains multiple test cases. The first line contains an integer t (1\le t\le 100) — the number of test cases. The descriptions of the t test cases follow.The first line of each test case contains a string u (1\le |u|\le 200) — the DNA of the weasel.The second line of each test case contains a string v (1\le |v|\le 200) — the DNA of the basilisk. The values |u|, |v| denote the lengths of the strings u and v. It is guaranteed that both strings u and v consist of the letters A, B and C.OutputFor each test case, print YES if there is a sequence of mutations to get from u to v and NO otherwise. ExampleInput 8ABBCCAAABBBBCCCCAAABABBCBCABCCBAOutput NO NO NO YES YES YES YES NO
8ABBCCAAABBBBCCCCAAABABBCBCABCCBA
NO NO NO YES YES YES YES NO
2 seconds
256 megabytes
['greedy', 'implementation', 'strings']
C. European Triptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe map of Europe can be represented by a set of n cities, numbered from 1 through n, which are connected by m bidirectional roads, each of which connects two distinct cities. A trip of length k is a sequence of k+1 cities v_1, v_2, \ldots, v_{k+1} such that there is a road connecting each consecutive pair v_i, v_{i+1} of cities, for all 1 \le i \le k. A special trip is a trip that does not use the same road twice in a row, i.e., a sequence of k+1 cities v_1, v_2, \ldots, v_{k+1} such that it forms a trip and v_i \neq v_{i + 2}, for all 1 \le i \le k - 1.Given an integer k, compute the number of distinct special trips of length k which begin and end in the same city. Since the answer might be large, give the answer modulo 998\,244\,353.InputThe first line contains three integers n, m and k (3 \le n \le 100, 1 \le m \le n(n - 1) / 2, 1 \le k \le 10^4) — the number of cities, the number of roads and the length of trips to consider.Each of the following m lines contains a pair of distinct integers a and b (1 \le a, b \le n) — each pair represents a road connecting cities a and b. It is guaranteed that the roads are distinct (i.e., each pair of cities is connected by at most one road).OutputPrint the number of special trips of length k which begin and end in the same city, modulo 998\,244\,353.ExamplesInput 4 5 2 4 1 2 3 3 1 4 3 2 4 Output 0 Input 4 5 3 1 3 4 2 4 1 2 1 3 4 Output 12 Input 8 20 12 4 3 6 7 5 7 8 2 8 3 3 1 4 7 8 5 5 4 3 5 7 1 5 1 7 8 3 2 4 2 5 2 1 4 4 8 3 6 4 6 Output 35551130 NoteIn the first sample, we are looking for special trips of length 2, but since we cannot use the same road twice once we step away from a city we cannot go back, so the answer is 0.In the second sample, we have the following 12 special trips of length 3 which begin and end in the same city: (1, 2, 4, 1), (1, 3, 4, 1), (1, 4, 2, 1), (1, 4, 3, 1), (2, 1, 4, 2), (2, 4, 1, 2), (3, 1, 4, 3), (3, 4, 1, 3), (4, 1, 3, 4), (4, 3, 1, 4), (4, 1, 2, 4), and (4, 2, 1, 4).
4 5 2 4 1 2 3 3 1 4 3 2 4
0
2 seconds
256 megabytes
['dp', 'graphs', 'math', 'matrices']
B. Toystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVittorio has three favorite toys: a teddy bear, an owl, and a raccoon. Each of them has a name. Vittorio takes several sheets of paper and writes a letter on each side of every sheet so that it is possible to spell any of the three names by arranging some of the sheets in a row (sheets can be reordered and flipped as needed). The three names do not have to be spelled at the same time, it is sufficient that it is possible to spell each of them using all the available sheets (and the same sheet can be used to spell different names).Find the minimum number of sheets required. In addition, produce a list of sheets with minimum cardinality which can be used to spell the three names (if there are multiple answers, print any).InputThe first line contains a string t consisting of uppercase letters of the English alphabet (1\le |t| \le 1000) — the name of the teddy bear.The second line contains a string o consisting of uppercase letters of the English alphabet (1\le |o| \le 1000) — the name of the owl.The third line contains a string r consisting of uppercase letters of the English alphabet (1\le |r| \le 1000) — the name of the raccoon.The values |t|, |o|, |r| denote the length of the three names t, o, r.OutputThe first line of the output contains a single integer m — the minimum number of sheets required.Then m lines follow: the j-th of these lines contains a string of two uppercase letters of the English alphabet — the letters appearing on the two sides of the j-th sheet.Note that you can print the sheets and the two letters of each sheet in any order.ExamplesInput AA GA MA Output 2 AG AM Input TEDDY HEDWIG RACCOON Output 8 AT CH CY DG DO ER IN OW Input BDC CAA CE Output 4 AD AE BB CC NoteIn the first sample, the solution uses two sheets: the first sheet has A on one side and G on the other side; the second sheet has A on one side and M on the other side.The name AA can be spelled using the A side of both sheets. The name GA can be spelled using the G side of the first sheet and the A side of the second sheet. Finally, the name MA can be spelled using the M side of the second sheet and the A side of the first sheet.
AA GA MA
2 AG AM
2 seconds
256 megabytes
['greedy', 'strings']
A. Organizing SWERCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGianni, SWERC's chief judge, received a huge amount of high quality problems from the judges and now he has to choose a problem set for SWERC.He received n problems and he assigned a beauty score and a difficulty to each of them. The i-th problem has beauty score equal to b_i and difficulty equal to d_i. The beauty and the difficulty are integers between 1 and 10. If there are no problems with a certain difficulty (the possible difficulties are 1,2,\dots,10) then Gianni will ask for more problems to the judges.Otherwise, for each difficulty between 1 and 10, he will put in the problem set one of the most beautiful problems with such difficulty (so the problem set will contain exactly 10 problems with distinct difficulties). You shall compute the total beauty of the problem set, that is the sum of the beauty scores of the problems chosen by Gianni.InputEach test contains multiple test cases. The first line contains an integer t (1\le t\le 100) — the number of test cases. The descriptions of the t test cases follow.The first line of each test case contains the integer n (1\le n\le 100) — how many problems Gianni received from the judges.The next n lines contain two integers each. The i-th of such lines contains b_i and d_i (1\le b_i, d_i\le 10) — the beauty score and the difficulty of the i-th problem.OutputFor each test case, print the total beauty of the problem set chosen by Gianni. If Gianni cannot create a problem set (because there are no problems with a certain difficulty) print the string MOREPROBLEMS (all letters are uppercase, there are no spaces).ExampleInput 238 49 36 7123 1010 110 210 310 43 1010 510 610 710 810 91 10Output MOREPROBLEMS 93 NoteIn the first test case, Gianni has received only 3 problems, with difficulties 3, 4, 7 which are not sufficient to create a problem set (for example because there is not a problem with difficulty 1).In the second test case, Gianni will create a problem set by taking the problems 2, 3, 4, 5, 7, 8, 9, 10, 11 (which have beauty equal to 10 and all difficulties from 1 to 9) and one of the problems 1 and 6 (which have both beauty 3 and difficulty 10). The total beauty of the resulting problem set is 10\cdot 9 + 3 = 93.
238 49 36 7123 1010 110 210 310 43 1010 510 610 710 810 91 10
MOREPROBLEMS 93
2 seconds
256 megabytes
['brute force', 'implementation']
F. Teleporterstime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n+1 teleporters on a straight line, located in points 0, a_1, a_2, a_3, ..., a_n. It's possible to teleport from point x to point y if there are teleporters in both of those points, and it costs (x-y)^2 energy.You want to install some additional teleporters so that it is possible to get from the point 0 to the point a_n (possibly through some other teleporters) spending no more than m energy in total. Each teleporter you install must be located in an integer point.What is the minimum number of teleporters you have to install?InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_1 < a_2 < a_3 < \dots < a_n \le 10^9).The third line contains one integer m (a_n \le m \le 10^{18}).OutputPrint one integer — the minimum number of teleporters you have to install so that it is possible to get from 0 to a_n spending at most m energy. It can be shown that it's always possible under the constraints from the input format.ExamplesInput 2 1 5 7 Output 2 Input 2 1 5 6 Output 3 Input 1 5 5 Output 4 Input 1 1000000000 1000000043 Output 999999978
2 1 5 7
2
7 seconds
512 megabytes
['binary search', 'greedy', '*2600']
E. Narrow Componentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix a, consisting of 3 rows and n columns. Each cell of the matrix is either free or taken.A free cell y is reachable from a free cell x if at least one of these conditions hold: x and y share a side; there exists a free cell z such that z is reachable from x and y is reachable from z. A connected component is a set of free cells of the matrix such that all cells in it are reachable from one another, but adding any other free cell to the set violates this rule.You are asked q queries about the matrix. Each query is the following: l r — count the number of connected components of the matrix, consisting of columns from l to r of the matrix a, inclusive. Print the answers to all queries.InputThe first line contains an integer n (1 \le n \le 5 \cdot 10^5) — the number of columns of matrix a.The i-th of the next three lines contains a description of the i-th row of the matrix a — a string, consisting of n characters. Each character is either 1 (denoting a free cell) or 0 (denoting a taken cell).The next line contains an integer q (1 \le q \le 3 \cdot 10^5) — the number of queries.The j-th of the next q lines contains two integers l_j and r_j (1 \le l_j \le r_j \le n) — the description of the j-th query.OutputPrint q integers — the j-th value should be equal to the number of the connected components of the matrix, consisting of columns from l_j to r_j of the matrix a, inclusive.ExampleInput 12 100101011101 110110010110 010001011101 8 1 12 1 1 1 2 9 9 8 11 9 12 11 12 4 6 Output 7 1 1 2 1 3 3 3
12 100101011101 110110010110 010001011101 8 1 12 1 1 1 2 9 9 8 11 9 12 11 12 4 6
7 1 1 2 1 3 3 3
2 seconds
256 megabytes
['brute force', 'data structures', 'dp', 'dsu', 'math', 'trees', '*2500']
D. Progressions Coveringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays: an array a consisting of n zeros and an array b consisting of n integers.You can apply the following operation to the array a an arbitrary number of times: choose some subsegment of a of length k and add the arithmetic progression 1, 2, \ldots, k to this subsegment — i. e. add 1 to the first element of the subsegment, 2 to the second element, and so on. The chosen subsegment should be inside the borders of the array a (i.e., if the left border of the chosen subsegment is l, then the condition 1 \le l \le l + k - 1 \le n should be satisfied). Note that the progression added is always 1, 2, \ldots, k but not the k, k - 1, \ldots, 1 or anything else (i.e., the leftmost element of the subsegment always increases by 1, the second element always increases by 2 and so on).Your task is to find the minimum possible number of operations required to satisfy the condition a_i \ge b_i for each i from 1 to n. Note that the condition a_i \ge b_i should be satisfied for all elements at once.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 3 \cdot 10^5) — the number of elements in both arrays and the length of the subsegment, respectively.The second line of the input contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le 10^{12}), where b_i is the i-th element of the array b.OutputPrint one integer — the minimum possible number of operations required to satisfy the condition a_i \ge b_i for each i from 1 to n.ExamplesInput 3 3 5 4 6 Output 5 Input 6 3 1 2 3 2 2 3 Output 3 Input 6 3 1 2 4 1 2 3 Output 3 Input 7 3 50 17 81 25 42 39 96 Output 92 NoteConsider the first example. In this test, we don't really have any choice, so we need to add at least five progressions to make the first element equals 5. The array a becomes [5, 10, 15].Consider the second example. In this test, let's add one progression on the segment [1; 3] and two progressions on the segment [4; 6]. Then, the array a becomes [1, 2, 3, 2, 4, 6].
3 3 5 4 6
5
2 seconds
256 megabytes
['data structures', 'greedy', '*1900']
C. Water the Treestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n trees in a park, numbered from 1 to n. The initial height of the i-th tree is h_i.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day 1. During the j-th day you can: Choose a tree and water it. If the day is odd (e.g. 1, 3, 5, 7, \dots), then the height of the tree increases by 1. If the day is even (e.g. 2, 4, 6, 8, \dots), then the height of the tree increases by 2. Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.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.The first line of the test case contains one integer n (1 \le n \le 3 \cdot 10^5) — the number of trees.The second line of the test case contains n integers h_1, h_2, \ldots, h_n (1 \le h_i \le 10^9), where h_i is the height of the i-th tree.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5 (\sum n \le 3 \cdot 10^5).OutputFor each test case, print one integer — the minimum number of days required to water the trees, so they grow to the same height.ExampleInput 3 3 1 2 4 5 4 4 3 5 5 7 2 5 4 8 3 7 4 Output 4 3 16 NoteConsider the first test case of the example. The initial state of the trees is [1, 2, 4]. During the first day, let's water the first tree, so the sequence of heights becomes [2, 2, 4]; during the second day, let's water the second tree, so the sequence of heights becomes [2, 4, 4]; let's skip the third day; during the fourth day, let's water the first tree, so the sequence of heights becomes [4, 4, 4]. Thus, the answer is 4.
3 3 1 2 4 5 4 4 3 5 5 7 2 5 4 8 3 7 4
4 3 16
3 seconds
256 megabytes
['binary search', 'greedy', 'math', '*1700']
B. Getting Zerotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you have an integer v. In one operation, you can: either set v = (v + 1) \bmod 32768 or set v = (2 \cdot v) \bmod 32768. You are given n integers a_1, a_2, \dots, a_n. What is the minimum number of operations you need to make each a_i equal to 0?InputThe first line contains the single integer n (1 \le n \le 32768) — the number of integers.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i < 32768).OutputPrint n integers. The i-th integer should be equal to the minimum number of operations required to make a_i equal to 0.ExampleInput 4 19 32764 10240 49 Output 14 4 4 15 NoteLet's consider each a_i: a_1 = 19. You can, firstly, increase it by one to get 20 and then multiply it by two 13 times. You'll get 0 in 1 + 13 = 14 steps. a_2 = 32764. You can increase it by one 4 times: 32764 \rightarrow 32765 \rightarrow 32766 \rightarrow 32767 \rightarrow 0. a_3 = 10240. You can multiply it by two 4 times: 10240 \rightarrow 20480 \rightarrow 8192 \rightarrow 16384 \rightarrow 0. a_4 = 49. You can multiply it by two 15 times.
4 19 32764 10240 49
14 4 4 15
2 seconds
256 megabytes
['bitmasks', 'brute force', 'dfs and similar', 'dp', 'graphs', 'greedy', 'shortest paths', '*1300']
A. Array Balancingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays of length n: a_1, a_2, \dots, a_n and b_1, b_2, \dots, b_n.You can perform the following operation any number of times: Choose integer index i (1 \le i \le n); Swap a_i and b_i. What is the minimum possible sum |a_1 - a_2| + |a_2 - a_3| + \dots + |a_{n-1} - a_n| + |b_1 - b_2| + |b_2 - b_3| + \dots + |b_{n-1} - b_n| (in other words, \sum\limits_{i=1}^{n - 1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}) you can achieve after performing several (possibly, zero) operations?InputThe first line contains a single integer t (1 \le t \le 4000) — the number of test cases. Then, t test cases follow.The first line of each test case contains the single integer n (2 \le n \le 25) — the length of arrays a and b.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the array a.The third line of each test case contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^9) — the array b.OutputFor each test case, print one integer — the minimum possible sum \sum\limits_{i=1}^{n-1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}.ExampleInput 3 4 3 3 10 10 10 10 3 3 5 1 2 3 4 5 6 7 8 9 10 6 72 101 108 108 111 44 10 87 111 114 108 100 Output 0 8 218 NoteIn the first test case, we can, for example, swap a_3 with b_3 and a_4 with b_4. We'll get arrays a = [3, 3, 3, 3] and b = [10, 10, 10, 10] with sum 3 \cdot |3 - 3| + 3 \cdot |10 - 10| = 0.In the second test case, arrays already have minimum sum (described above) equal to |1 - 2| + \dots + |4 - 5| + |6 - 7| + \dots + |9 - 10| = 4 + 4 = 8.In the third test case, we can, for example, swap a_5 and b_5.
3 4 3 3 10 10 10 10 3 3 5 1 2 3 4 5 6 7 8 9 10 6 72 101 108 108 111 44 10 87 111 114 108 100
0 8 218
2 seconds
256 megabytes
['greedy', 'math', '*800']
F2. Promising String (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of Problem F. The only difference between the easy version and the hard version is the constraints.We will call a non-empty string balanced if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" and "" are not balanced.We will call a string promising if the string can be made balanced by several (possibly zero) uses of the following operation: replace two adjacent minus signs with one plus sign. In particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.For example, the string "-+---" is promising, because you can replace two adjacent minuses with plus and get a balanced string "-++-", or get another balanced string "-+-+".How many non-empty substrings of the given string s are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string s.Recall that a substring is a sequence of consecutive characters of the string. For example, for string "+-+" its substring are: "+-", "-+", "+", "+-+" (the string is a substring of itself) and some others. But the following strings are not its substring: "--", "++", "-++".InputThe first line of the input contains an integer t (1 \le t \le 10^4) —the number of test cases in the test.Then the descriptions of test cases follow.Each test case of input data consists of two lines. The first line consists of the number n (1 \le n \le 2 \cdot 10^5): the length of s.The second line of the test case contains the string s of length n, consisting only of characters "+" and "-".It is guaranteed that the sum of values n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single number: the number of the promising non-empty substrings of string s. Each non-empty promising substring must be counted in the answer as many times as it occurs in string s.ExampleInput 5 3 +-+ 5 -+--- 4 ---- 7 --+---+ 6 +++--- Output 2 4 2 7 4 NoteThe following are the promising substrings for the first three test cases in the example: s[1 \dots 2]="+-", s[2 \dots 3]="-+"; s[1 \dots 2]="-+", s[2 \dots 3]="+-", s[1 \dots 5]="-+---", s[3 \dots 5]="---"; s[1 \dots 3]="---", s[2 \dots 4]="---".
5 3 +-+ 5 -+--- 4 ---- 7 --+---+ 6 +++---
2 4 2 7 4
2 seconds
256 megabytes
['data structures', 'implementation', 'math', 'strings', '*2100']
F1. Promising String (easy version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of Problem F. The only difference between the easy version and the hard version is the constraints.We will call a non-empty string balanced if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" and "" are not balanced.We will call a string promising if the string can be made balanced by several (possibly zero) uses of the following operation: replace two adjacent minus signs with one plus sign. In particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.For example, the string "-+---" is promising, because you can replace two adjacent minuses with plus and get a balanced string "-++-", or get another balanced string "-+-+".How many non-empty substrings of the given string s are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string s.Recall that a substring is a sequence of consecutive characters of the string. For example, for string "+-+" its substring are: "+-", "-+", "+", "+-+" (the string is a substring of itself) and some others. But the following strings are not its substring: "--", "++", "-++".InputThe first line of the input contains an integer t (1 \le t \le 500) —the number of test cases in the test.Then the descriptions of test cases follow.Each test case of input data consists of two lines. The first line consists of the number n (1 \le n \le 3000): the length of s.The second line of the test case contains the string s of length n, consisting only of characters "+" and "-".It is guaranteed that the sum of values n over all test cases does not exceed 3000.OutputFor each test case, print a single number: the number of the promising non-empty substrings of string s. Each non-empty promising substring must be counted in the answer as many times as it occurs in string s.ExampleInput 5 3 +-+ 5 -+--- 4 ---- 7 --+---+ 6 +++--- Output 2 4 2 7 4 NoteThe following are the promising substrings for the first three test cases in the example: s[1 \dots 2]="+-", s[2 \dots 3]="-+"; s[1 \dots 2]="-+", s[2 \dots 3]="+-", s[1 \dots 5]="-+---", s[3 \dots 5]="---"; s[1 \dots 3]="---", s[2 \dots 4]="---".
5 3 +-+ 5 -+--- 4 ---- 7 --+---+ 6 +++---
2 4 2 7 4
3 seconds
256 megabytes
['brute force', 'implementation', 'math', 'strings', '*1700']
E. Matrix and Shiftstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary matrix A of size n \times n. Rows are numbered from top to bottom from 1 to n, columns are numbered from left to right from 1 to n. The element located at the intersection of row i and column j is called A_{ij}. Consider a set of 4 operations: Cyclically shift all rows up. The row with index i will be written in place of the row i-1 (2 \le i \le n), the row with index 1 will be written in place of the row n. Cyclically shift all rows down. The row with index i will be written in place of the row i+1 (1 \le i \le n - 1), the row with index n will be written in place of the row 1. Cyclically shift all columns to the left. The column with index j will be written in place of the column j-1 (2 \le j \le n), the column with index 1 will be written in place of the column n. Cyclically shift all columns to the right. The column with index j will be written in place of the column j+1 (1 \le j \le n - 1), the column with index n will be written in place of the column 1. The 3 \times 3 matrix is shown on the left before the 3-rd operation is applied to it, on the right — after. You can perform an arbitrary (possibly zero) number of operations on the matrix; the operations can be performed in any order.After that, you can perform an arbitrary (possibly zero) number of new xor-operations: Select any element A_{ij} and assign it with new value A_{ij} \oplus 1. In other words, the value of (A_{ij} + 1) \bmod 2 will have to be written into element A_{ij}. Each application of this xor-operation costs one burl. Note that the 4 shift operations — are free. These 4 operations can only be performed before xor-operations are performed.Output the minimum number of burles you would have to pay to make the A matrix unitary. A unitary matrix is a matrix with ones on the main diagonal and the rest of its elements are zeros (that is, A_{ij} = 1 if i = j and A_{ij} = 0 otherwise).InputThe first line of the input contains an integer t (1 \le t \le 10^4) —the number of test cases in the test.The descriptions of the test cases follow. Before each test case, an empty line is written in the input.The first line of each test case contains a single number n (1 \le n \le 2000)This is followed by n lines, each containing exactly n characters and consisting only of zeros and ones. These lines describe the values in the elements of the matrix.It is guaranteed that the sum of n^2 values over all test cases does not exceed 4 \cdot 10^6.OutputFor each test case, output the minimum number of burles you would have to pay to make the A matrix unitary. In other words, print the minimum number of xor-operations it will take after applying cyclic shifts to the matrix for the A matrix to become unitary.ExampleInput 4 3 010 011 100 5 00010 00001 10000 01000 00100 2 10 10 4 1111 1011 1111 1111 Output 1 0 2 11 NoteIn the first test case, you can do the following: first, shift all the rows down cyclically, then the main diagonal of the matrix will contain only "1". Then it will be necessary to apply xor-operation to the only "1" that is not on the main diagonal.In the second test case, you can make a unitary matrix by applying the operation 2 — cyclic shift of rows upward twice to the matrix.
4 3 010 011 100 5 00010 00001 10000 01000 00100 2 10 10 4 1111 1011 1111 1111
1 0 2 11
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'implementation', '*1600']
D. Maximum Product Strikes Backtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. For each i (1 \le i \le n) the following inequality is true: -2 \le a_i \le 2.You can remove any number (possibly 0) of elements from the beginning of the array and any number (possibly 0) of elements from the end of the array. You are allowed to delete the whole array.You need to answer the question: how many elements should be removed from the beginning of the array, and how many elements should be removed from the end of the array, so that the result will be an array whose product (multiplication) of elements is maximal. If there is more than one way to get an array with the maximum product of elements on it, you are allowed to output any of them. The product of elements of an empty array (array of length 0) should be assumed to be 1.InputThe first line of input data contains an integer t (1 \le t \le 10^4) —the number of test cases in the test.Then the descriptions of the input test cases follow.The first line of each test case description contains an integer n (1 \le n \le 2 \cdot 10^5) —the length of array a.The next line contains n integers a_1, a_2, \dots, a_n (|a_i| \le 2) — elements of array a.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output two non-negative numbers x and y (0 \le x + y \le n) — such that the product (multiplication) of the array numbers, after removing x elements from the beginning and y elements from the end, is maximal.If there is more than one way to get the maximal product, it is allowed to output any of them. Consider the product of numbers on empty array to be 1.ExampleInput 5 4 1 2 -1 2 3 1 1 -2 5 2 0 -2 2 -1 3 -2 -1 -1 3 -1 -2 -2 Output 0 2 3 0 2 0 0 1 1 0 NoteIn the first case, the maximal value of the product is 2. Thus, we can either delete the first three elements (obtain array [2]), or the last two and one first element (also obtain array [2]), or the last two elements (obtain array [1, 2]). Thus, in the first case, the answers fit: "3 0", or "1 2", or "0 2".In the second case, the maximum value of the product is 1. Then we can remove all elements from the array because the value of the product on the empty array will be 1. So the answer is "3 0", but there are other possible answers.In the third case, we can remove the first two elements of the array. Then we get the array: [-2, 2, -1]. The product of the elements of the resulting array is (-2) \cdot 2 \cdot (-1) = 4. This value is the maximum possible value that can be obtained. Thus, for this case the answer is: "2 0".
5 4 1 2 -1 2 3 1 1 -2 5 2 0 -2 2 -1 3 -2 -1 -1 3 -1 -2 -2
0 2 3 0 2 0 0 1 1 0
2 seconds
256 megabytes
['brute force', 'implementation', 'math', 'two pointers', '*1600']
C. Get an Even Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string a=a_1a_2\dots a_n is called even if it consists of a concatenation (joining) of strings of length 2 consisting of the same characters. In other words, a string a is even if two conditions are satisfied at the same time: its length n is even; for all odd i (1 \le i \le n - 1), a_i = a_{i+1} is satisfied. For example, the following strings are even: "" (empty string), "tt", "aabb", "oooo", and "ttrrrroouuuuuuuukk". The following strings are not even: "aaa", "abab" and "abba".Given a string s consisting of lowercase Latin letters. Find the minimum number of characters to remove from the string s to make it even. The deleted characters do not have to be consecutive.InputThe first line of input data contains an integer t (1 \le t \le 10^4) —the number of test cases in the test.The descriptions of the test cases follow.Each test case consists of one string s (1 \le |s| \le 2 \cdot 10^5), where |s| — the length of the string s. The string consists of lowercase Latin letters.It is guaranteed that the sum of |s| on all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single number — the minimum number of characters that must be removed to make s even.ExampleInput 6 aabbdabdccc zyx aaababbb aabbcc oaoaaaoo bmefbmuyw Output 3 3 2 0 2 7 NoteIn the first test case you can remove the characters with indices 6, 7, and 9 to get an even string "aabbddcc".In the second test case, each character occurs exactly once, so in order to get an even string, you must remove all characters from the string.In the third test case, you can get an even string "aaaabb" by removing, for example, 4-th and 6-th characters, or a string "aabbbb" by removing the 5-th character and any of the first three.
6 aabbdabdccc zyx aaababbb aabbcc oaoaaaoo bmefbmuyw
3 3 2 0 2 7
1 second
256 megabytes
['dp', 'greedy', 'strings', '*1300']
B. Vlad and Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNot so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were n types of candies, there are a_i candies of the type i (1 \le i \le n).Vlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there are several such types, he can choose any of them). To get the maximum pleasure from eating, Vlad does not want to eat two candies of the same type in a row.Help him figure out if he can eat all the candies without eating two identical candies in a row.InputThe first line of input data contains an integer t (1 \le t \le 10^4) — the number of input test cases.The following is a description of t test cases of input, two lines for each.The first line of the case contains the single number n (1 \le n \le 2 \cdot 10^5) — the number of types of candies in the package.The second line of the case contains n integers a_i (1 \le a_i \le 10^9) — the number of candies of the type i.It is guaranteed that the sum of n for all cases does not exceed 2 \cdot 10^5.OutputOutput t lines, each of which contains the answer to the corresponding test case of input. As an answer, output "YES" if Vlad can eat candy as planned, and "NO" otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput 6 2 2 3 1 2 5 1 6 2 4 3 4 2 2 2 1 3 1 1000000000 999999999 1 1 Output YES NO NO YES YES YES NoteIn the first example, it is necessary to eat sweets in this order: a candy of the type 2, it is the most frequent, now a = [2, 2]; a candy of the type 1, there are the same number of candies of the type 2, but we just ate one, now a = [1, 2]; a candy of the type 2, it is the most frequent, now a = [1, 1]; a candy of the type 1, now a = [0, 1]; a candy of the type 2, now a = [0, 0] and the candy has run out.In the second example, all the candies are of the same type and it is impossible to eat them without eating two identical ones in a row.In the third example, first of all, a candy of the type 2 will be eaten, after which this kind will remain the only kind that is the most frequent, and you will have to eat a candy of the type 2 again.
6 2 2 3 1 2 5 1 6 2 4 3 4 2 2 2 1 3 1 1000000000 999999999 1 1
YES NO NO YES YES YES
1 second
256 megabytes
['math', '*800']
A. Vasya and Coinstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya decided to go to the grocery store. He found in his wallet a coins of 1 burle and b coins of 2 burles. He does not yet know the total cost of all goods, so help him find out s (s > 0): the minimum positive integer amount of money he cannot pay without change or pay at all using only his coins.For example, if a=1 and b=1 (he has one 1-burle coin and one 2-burle coin), then: he can pay 1 burle without change, paying with one 1-burle coin, he can pay 2 burle without change, paying with one 2-burle coin, he can pay 3 burle without change by paying with one 1-burle coin and one 2-burle coin, he cannot pay 4 burle without change (moreover, he cannot pay this amount at all). So for a=1 and b=1 the answer is s=4.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the test.The description of each test case consists of one line containing two integers a_i and b_i (0 \le a_i, b_i \le 10^8) — the number of 1-burle coins and 2-burles coins Vasya has respectively.OutputFor each test case, on a separate line print one integer s (s > 0): the minimum positive integer amount of money that Vasya cannot pay without change or pay at all.ExampleInput 5 1 1 4 0 0 2 0 0 2314 2374 Output 4 5 1 1 7063 Note The first test case of the example is clarified into the main part of the statement. In the second test case, Vasya has only 1 burle coins, and he can collect either any amount from 1 to 4, but 5 can't. In the second test case, Vasya has only 2 burle coins, and he cannot pay 1 burle without change. In the fourth test case you don't have any coins, and he can't even pay 1 burle.
5 1 1 4 0 0 2 0 0 2314 2374
4 5 1 1 7063
1 second
256 megabytes
['greedy', 'math', '*800']
F. Tree and Permutation Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a tree of n vertices and a permutation p of size n. A token is present on vertex x of the tree.Alice and Bob are playing a game. Alice is in control of the permutation p, and Bob is in control of the token on the tree. In Alice's turn, she must pick two distinct numbers u and v (not positions; u \neq v), such that the token is neither at vertex u nor vertex v on the tree, and swap their positions in the permutation p. In Bob's turn, he must move the token to an adjacent vertex from the one it is currently on.Alice wants to sort the permutation in increasing order. Bob wants to prevent that. Alice wins if the permutation is sorted in increasing order at the beginning or end of her turn. Bob wins if he can make the game go on for an infinite number of moves (which means that Alice is never able to get a sorted permutation). Both players play optimally. Alice makes the first move.Given the tree, the permutation p, and the vertex x on which the token initially is, find the winner of the game.InputThe first line contains a single integer t (1 \le t \le 1000)  — the number of test cases. The description of each test case follows.The first line of each test case has two integers n and x (3 \leq n \leq 2 \cdot 10^5; 1 \leq x \leq n).Each of the next n-1 lines contains two integers a and b (1 \le a, b \le n, a \neq b) indicating an undirected edge between vertex a and vertex b. It is guaranteed that the given edges form a tree.The next line contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n)  — the permutation p.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output one line containing Alice or Bob — the winner of the game. The output is case-sensitive.ExamplesInput 3 6 3 1 3 3 2 4 3 3 6 5 3 2 1 3 6 4 5 3 2 1 2 3 2 1 3 2 3 2 1 2 3 2 1 2 3 Output Alice Bob Alice Input 1 11 4 3 11 5 9 10 3 4 8 2 4 1 8 6 8 8 7 4 5 5 11 7 4 9 8 6 5 11 10 2 3 1 Output Alice NoteHere is the explanation for the first example:In the first test case, there is a way for Alice to win. Here is a possible sequence of moves: Alice swaps 5 and 6, resulting in [2,1,3,5,4,6]. Bob moves the token to vertex 5. Alice swaps 1 and 2, resulting in [1,2,3,5,4,6]. Bob moves the token to vertex 3. Alice swaps 4 and 5, resulting in [1,2,3,4,5,6], and wins. In the second test case, Alice cannot win since Bob can make the game go on forever. Here is the sequence of moves: Alice can only swap 1 and 3, resulting in [3,1,2]. Bob moves the token to vertex 1. Alice can only swap 2 and 3, resulting in [2,1,3]. Bob moves the token to vertex 2. Alice can only swap 1 and 3, resulting in [2,3,1]. Bob moves the token to vertex 3. Alice can only swap 1 and 2, resulting in [1,3,2]. Bob moves the token to vertex 2. And then the sequence repeats forever.In the third test case, Alice wins immediately since the permutation is already sorted.
3 6 3 1 3 3 2 4 3 3 6 5 3 2 1 3 6 4 5 3 2 1 2 3 2 1 3 2 3 2 1 2 3 2 1 2 3
Alice Bob Alice
1 second
256 megabytes
['dfs and similar', 'games', 'graphs', 'trees', '*3000']
E. AND-MEX Walktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an undirected, connected graph with n vertices and m weighted edges. A walk from vertex u to vertex v is defined as a sequence of vertices p_1,p_2,\ldots,p_k (which are not necessarily distinct) starting with u and ending with v, such that p_i and p_{i+1} are connected by an edge for 1 \leq i < k.We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have [w_1,w_2,\ldots,w_{k-1}] where w_i is the weight of the edge between p_i and p_{i+1}. Then the length of the walk is given by \mathrm{MEX}(\{w_1,\,w_1\& w_2,\,\ldots,\,w_1\& w_2\& \ldots\& w_{k-1}\}), where \& denotes the bitwise AND operation.Now you must process q queries of the form u v. For each query, find the minimum possible length of a walk from u to v.The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance: The MEX of \{2,1\} is 0, because 0 does not belong to the set. The MEX of \{3,1,0\} is 2, because 0 and 1 belong to the set, but 2 does not. The MEX of \{0,3,1,2\} is 4 because 0, 1, 2 and 3 belong to the set, but 4 does not. InputThe first line contains two integers n and m (2 \leq n \leq 10^5; n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}).Each of the next m lines contains three integers a, b, and w (1 \leq a, b \leq n, a \neq b; 0 \leq w < 2^{30}) indicating an undirected edge between vertex a and vertex b with weight w. The input will not contain self-loops or duplicate edges, and the provided graph will be connected.The next line contains a single integer q (1 \leq q \leq 10^5).Each of the next q lines contains two integers u and v (1 \leq u, v \leq n, u \neq v), the description of each query.OutputFor each query, print one line containing a single integer — the answer to the query.ExamplesInput 6 7 1 2 1 2 3 3 3 1 5 4 5 2 5 6 4 6 4 6 3 4 1 3 1 5 1 2 5 3 Output 2 0 1 Input 9 8 1 2 5 2 3 11 3 4 10 3 5 10 5 6 2 5 7 1 7 8 5 7 9 5 10 5 7 2 5 7 1 6 4 5 2 7 6 4 1 6 2 4 7 2 8 Output 0 0 2 0 0 2 1 0 1 1 NoteThe following is an explanation of the first example. The graph in the first example. Here is one possible walk for the first query:1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.The array of weights is w=[5,3,1,5,1,2]. Now if we take the bitwise AND of every prefix of this array, we get the set \{5,1,0\}. The MEX of this set is 2. We cannot get a walk with a smaller length (as defined in the statement).
6 7 1 2 1 2 3 3 3 1 5 4 5 2 5 6 4 6 4 6 3 4 1 3 1 5 1 2 5 3
2 0 1
3 seconds
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', '*2200']
D. Reverse Sort Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you had an array A of n elements, each of which is 0 or 1.Let us define a function f(k,A) which returns another array B, the result of sorting the first k elements of A in non-decreasing order. For example, f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]. Note that the first 4 elements were sorted.Now consider the arrays B_1, B_2,\ldots, B_n generated by f(1,A), f(2,A),\ldots,f(n,A). Let C be the array obtained by taking the element-wise sum of B_1, B_2,\ldots, B_n.For example, let A=[0,1,0,1]. Then we have B_1=[0,1,0,1], B_2=[0,1,0,1], B_3=[0,0,1,1], B_4=[0,0,1,1]. Then C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4].You are given C. Determine a binary array A that would give C when processed as above. It is guaranteed that an array A exists for given C in the input. InputThe first line contains a single integer t (1 \leq t \leq 1000)  — the number of test cases.Each test case has two lines. The first line contains a single integer n (1 \leq n \leq 2 \cdot 10^5).The second line contains n integers c_1, c_2, \ldots, c_n (0 \leq c_i \leq n). It is guaranteed that a valid array A exists for the given C.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single line containing n integers a_1, a_2, \ldots, a_n (a_i is 0 or 1). If there are multiple answers, you may output any of them.ExampleInput 5 4 2 4 2 4 7 0 3 4 2 3 2 7 3 0 0 0 4 0 0 0 4 3 1 2 3 Output 1 1 0 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 1 0 1 NoteHere's the explanation for the first test case. Given that A=[1,1,0,1], we can construct each B_i: B_1=[\color{blue}{1},1,0,1]; B_2=[\color{blue}{1},\color{blue}{1},0,1]; B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]; B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}] And then, we can sum up each column above to get C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4].
5 4 2 4 2 4 7 0 3 4 2 3 2 7 3 0 0 0 4 0 0 0 4 3 1 2 3
1 1 0 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 1 0 1
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'implementation', 'math', 'two pointers', '*1900']
C. Line Empiretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at 0. There are n unconquered kingdoms at positions 0<x_1<x_2<\ldots<x_n. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be c_1) to any other conquered kingdom (let its position be c_2) at a cost of a\cdot |c_1-c_2|. From the current capital (let its current position be c_1) you can conquer an unconquered kingdom (let its position be c_2) at a cost of b\cdot |c_1-c_2|. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at 0 or one of x_1,x_2,\ldots,x_n. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.InputThe first line contains a single integer t (1 \le t \le 1000)  — the number of test cases. The description of each test case follows.The first line of each test case contains 3 integers n, a, and b (1 \leq n \leq 2 \cdot 10^5; 1 \leq a,b \leq 10^5).The second line of each test case contains n integers x_1, x_2, \ldots, x_n (1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8).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 cost to conquer all kingdoms.ExampleInput 4 5 2 7 3 5 12 13 21 5 6 3 1 5 6 21 30 2 9 3 10 15 11 27182 31415 16 18 33 98 874 989 4848 20458 34365 38117 72030 Output 173 171 75 3298918744 NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position 1 with cost 3\cdot(1-0)=3. Move the capital to the kingdom at position 1 with cost 6\cdot(1-0)=6. Conquer the kingdom at position 5 with cost 3\cdot(5-1)=12. Move the capital to the kingdom at position 5 with cost 6\cdot(5-1)=24. Conquer the kingdom at position 6 with cost 3\cdot(6-5)=3. Conquer the kingdom at position 21 with cost 3\cdot(21-5)=48. Conquer the kingdom at position 30 with cost 3\cdot(30-5)=75. The total cost is 3+6+12+24+3+48+75=171. You cannot get a lower cost than this.
4 5 2 7 3 5 12 13 21 5 6 3 1 5 6 21 30 2 9 3 10 15 11 27182 31415 16 18 33 98 874 989 4848 20458 34365 38117 72030
173 171 75 3298918744
1 second
256 megabytes
['binary search', 'brute force', 'dp', 'greedy', 'implementation', 'math', '*1500']
B. Bit Flippingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string of length n. You have exactly k moves. In one move, you must select a single bit. The state of all bits except that bit will get flipped (0 becomes 1, 1 becomes 0). You need to output the lexicographically largest string that you can get after using all k moves. Also, output the number of times you will select each bit. If there are multiple ways to do this, you may output any of them.A binary string a is lexicographically larger than a binary string b of the same length, if and only if the following holds: in the first position where a and b differ, the string a contains a 1, and the string b contains a 0. InputThe first line contains a single integer t (1 \le t \le 1000)  — the number of test cases.Each test case has two lines. The first line has two integers n and k (1 \leq n \leq 2 \cdot 10^5; 0 \leq k \leq 10^9).The second line has a binary string of length n, each character is either 0 or 1.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output two lines.The first line should contain the lexicographically largest string you can obtain.The second line should contain n integers f_1, f_2, \ldots, f_n, where f_i is the number of times the i-th bit is selected. The sum of all the integers must be equal to k.ExampleInput 6 6 3 100001 6 4 100011 6 0 000000 6 1 111001 6 11 101100 6 12 001110 Output 111110 1 0 0 2 0 0 111110 0 1 1 1 0 1 000000 0 0 0 0 0 0 100110 1 0 0 0 0 0 111111 1 2 1 3 0 4 111110 1 1 4 2 0 4NoteHere is the explanation for the first testcase. Each step shows how the binary string changes in a move. Choose bit 1: \color{red}{\underline{1}00001} \rightarrow \color{red}{\underline{1}}\color{blue}{11110}. Choose bit 4: \color{red}{111\underline{1}10} \rightarrow \color{blue}{000}\color{red}{\underline{1}}\color{blue}{01}. Choose bit 4: \color{red}{000\underline{1}01} \rightarrow \color{blue}{111}\color{red}{\underline{1}}\color{blue}{10}. The final string is 111110 and this is the lexicographically largest string we can get.
6 6 3 100001 6 4 100011 6 0 000000 6 1 111001 6 11 101100 6 12 001110
111110 1 0 0 2 0 0 111110 0 1 1 1 0 1 000000 0 0 0 0 0 0 100110 1 0 0 0 0 0 111111 1 2 1 3 0 4 111110 1 1 4 2 0 4
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'greedy', 'strings', '*1300']
A. Red Versus Bluetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTeam Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of n matches.In the end, it turned out Team Red won r times and Team Blue won b times. Team Blue was less skilled than Team Red, so b was strictly less than r.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length n where the i-th character denotes who won the i-th match  — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won 3 times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.InputThe first line contains a single integer t (1 \le t \le 1000)  — the number of test cases.Each test case has a single line containing three integers n, r, and b (3 \leq n \leq 100; 1 \leq b < r \leq n, r+b=n).OutputFor each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.ExamplesInput 3 7 4 3 6 5 1 19 13 6 Output RBRBRBR RRRBRR RRBRRBRRBRRBRRBRRBR Input 6 3 2 1 10 6 4 11 6 5 10 9 1 10 8 2 11 9 2 Output RBR RRBRBRBRBR RBRBRBRBRBR RRRRRBRRRR RRRBRRRBRR RRRBRRRBRRR NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is 1. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is 2, given by RR at the beginning. We cannot minimize the answer any further.
3 7 4 3 6 5 1 19 13 6
RBRBRBR RRRBRR RRBRRBRRBRRBRRBRRBR
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*1000']
F. Juju and Binary Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe cuteness of a binary string is the number of \texttt{1}s divided by the length of the string. For example, the cuteness of \texttt{01101} is \frac{3}{5}.Juju has a binary string s of length n. She wants to choose some non-intersecting subsegments of s such that their concatenation has length m and it has the same cuteness as the string s. More specifically, she wants to find two arrays l and r of equal length k such that 1 \leq l_1 \leq r_1 < l_2 \leq r_2 < \ldots < l_k \leq r_k \leq n, and also: \sum\limits_{i=1}^k (r_i - l_i + 1) = m; The cuteness of s[l_1,r_1]+s[l_2,r_2]+\ldots+s[l_k,r_k] is equal to the cuteness of s, where s[x, y] denotes the subsegment s_x s_{x+1} \ldots s_y, and + denotes string concatenation. Juju does not like splitting the string into many parts, so she also wants to minimize the value of k. Find the minimum value of k such that there exist l and r that satisfy the constraints above or determine that it is impossible to find such l and r for any k.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains two integers n and m (1 \leq m \leq n \leq 2 \cdot 10^5).The second line of each test case contains a binary string s of length n.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, if there is no valid pair of l and r, print -1. Otherwise, print k + 1 lines.In the first line, print a number k (1 \leq k \leq m) — the minimum number of subsegments required.Then print k lines, the i-th should contain l_i and r_i (1 \leq l_i \leq r_i \leq n) — the range of the i-th subsegment. Note that you should output the subsegments such that the inequality l_1 \leq r_1 < l_2 \leq r_2 < \ldots < l_k \leq r_k is true.ExampleInput 4 4 2 0011 8 6 11000011 4 3 0101 5 5 11111 Output 1 2 3 2 2 3 5 8 -1 1 1 5 NoteIn the first example, the cuteness of \texttt{0011} is the same as the cuteness of \texttt{01}.In the second example, the cuteness of \texttt{11000011} is \frac{1}{2} and there is no subsegment of size 6 with the same cuteness. So we must use 2 disjoint subsegments \texttt{10} and \texttt{0011}.In the third example, there are 8 ways to split the string such that \sum\limits_{i=1}^k (r_i - l_i + 1) = 3 but none of them has the same cuteness as \texttt{0101}.In the last example, we don't have to split the string.
4 4 2 0011 8 6 11000011 4 3 0101 5 5 11111
1 2 3 2 2 3 5 8 -1 1 1 5
1 second
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'math', '*2700']
E. Gojou and Matrix Gametime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMarin feels exhausted after a long day of cosplay, so Gojou invites her to play a game!Marin and Gojou take turns to place one of their tokens on an n \times n grid with Marin starting first. There are some restrictions and allowances on where to place tokens: Apart from the first move, the token placed by a player must be more than Manhattan distance k away from the previous token placed on the matrix. In other words, if a player places a token at (x_1, y_1), then the token placed by the other player in the next move must be in a cell (x_2, y_2) satisfying |x_2 - x_1| + |y_2 - y_1| > k. Apart from the previous restriction, a token can be placed anywhere on the matrix, including cells where tokens were previously placed by any player. Whenever a player places a token on cell (x, y), that player gets v_{x,\ y} points. All values of v on the grid are distinct. You still get points from a cell even if tokens were already placed onto the cell. The game finishes when each player makes 10^{100} moves.Marin and Gojou will play n^2 games. For each cell of the grid, there will be exactly one game where Marin places a token on that cell on her first move. Please answer for each game, if Marin and Gojou play optimally (after Marin's first move), who will have more points at the end? Or will the game end in a draw (both players have the same points at the end)?InputThe first line contains two integers n, k (3 \le n \le 2000, 1 \leq k \leq n - 2). Note that under these constraints it is always possible to make a move.The following n lines contains n integers each. The j-th integer in the i-th line is v_{i,j} (1 \le v_{i,j} \le n^2). All elements in v are distinct.OutputYou should print n lines. In the i-th line, print n characters, where the j-th character is the result of the game in which Marin places her first token in the cell (i, j). Print 'M' if Marin wins, 'G' if Gojou wins, and 'D' if the game ends in a draw. Do not print spaces between the characters in one line.ExampleInput 3 1 1 2 4 6 8 3 9 5 7 Output GGG MGG MGG
3 1 1 2 4 6 8 3 9 5 7
GGG MGG MGG
4 seconds
256 megabytes
['data structures', 'dp', 'games', 'hashing', 'implementation', 'math', 'number theory', 'sortings', '*2500']
D2. 388535 (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference in the constraints between both versions are colored below in red. You can make hacks only if all versions of the problem are solved.Marin and Gojou are playing hide-and-seek with an array.Gojou initially perform the following steps: First, Gojou chooses 2 integers l and r such that l \leq r. Then, Gojou will make an array a of length r-l+1 which is a permutation of the array [l,l+1,\ldots,r]. Finally, Gojou chooses a secret integer x and sets a_i to a_i \oplus x for all i (where \oplus denotes the bitwise XOR operation). Marin is then given the values of l,r and the final array a. She needs to find the secret integer x to win. Can you help her?Note that there may be multiple possible x that Gojou could have chosen. Marin can find any possible x that could have resulted in the final value of a.InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases.In the first line of each test case contains two integers l and r (\color{red}{\boldsymbol{0} \boldsymbol{\le} \boldsymbol{l}} \le r < 2^{17}).The second line contains r - l + 1 space-seperated integers of a_1,a_2,\ldots,a_{r-l+1} (0 \le a_i < 2^{17}). It is guaranteed that array a is valid.It is guaranteed that the sum of r - l + 1 over all test cases does not exceed 2^{17}.OutputFor each test case print an integer x. If there are multiple answers, print any.ExampleInput 3 4 7 3 2 1 0 4 7 4 7 6 5 1 3 0 2 1 Output 4 0 3 NoteIn the first test case, the original array is [7, 6, 5, 4]. In the second test case, the original array is [4, 7, 6, 5].In the third test case, the original array is [3, 1, 2].
3 4 7 3 2 1 0 4 7 4 7 6 5 1 3 0 2 1
4 0 3
1 second
256 megabytes
['bitmasks', 'brute force', 'data structures', 'math', '*2300']
D1. 388535 (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference in the constraints between both versions is colored below in red. You can make hacks only if all versions of the problem are solved.Marin and Gojou are playing hide-and-seek with an array.Gojou initially performs the following steps: First, Gojou chooses 2 integers l and r such that l \leq r. Then, Gojou makes an array a of length r-l+1 which is a permutation of the array [l,l+1,\ldots,r]. Finally, Gojou chooses a secret integer x and sets a_i to a_i \oplus x for all i (where \oplus denotes the bitwise XOR operation). Marin is then given the values of l,r and the final array a. She needs to find the secret integer x to win. Can you help her?Note that there may be multiple possible x that Gojou could have chosen. Marin can find any possible x that could have resulted in the final value of a.InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases.In the first line of each test case contains two integers l and r ( \color{red}{\boldsymbol{0} \boldsymbol{=} \boldsymbol{l}} \le r < 2^{17}).The second line contains r - l + 1 integers of a_1,a_2,\ldots,a_{r-l+1} (0 \le a_i < 2^{17}). It is guaranteed that a can be generated using the steps performed by Gojou.It is guaranteed that the sum of r - l + 1 over all test cases does not exceed 2^{17}.OutputFor each test case print an integer x. If there are multiple answers, print any.ExampleInput 3 0 3 3 2 1 0 0 3 4 7 6 5 0 2 1 2 3 Output 0 4 3 NoteIn the first test case, the original array is [3, 2, 1, 0]. In the second test case, the original array is [0, 3, 2, 1].In the third test case, the original array is [2, 1, 0].
3 0 3 3 2 1 0 0 3 4 7 6 5 0 2 1 2 3
0 4 3
1 second
256 megabytes
['bitmasks', 'math', '*1600']
C. Shinju and the Lost Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputShinju loves permutations very much! Today, she has borrowed a permutation p from Juju to play with.The i-th cyclic shift of a permutation p is a transformation on the permutation such that p = [p_1, p_2, \ldots, p_n] will now become p = [p_{n-i+1}, \ldots, p_n, p_1,p_2, \ldots, p_{n-i}].Let's define the power of permutation p as the number of distinct elements in the prefix maximums array b of the permutation. The prefix maximums array b is the array of length n such that b_i = \max(p_1, p_2, \ldots, p_i). For example, the power of [1, 2, 5, 4, 6, 3] is 4 since b=[1,2,5,5,6,6] and there are 4 distinct elements in b.Unfortunately, Shinju has lost the permutation p! The only information she remembers is an array c, where c_i is the power of the (i-1)-th cyclic shift of the permutation p. She's also not confident that she remembers it correctly, so she wants to know if her memory is good enough.Given the array c, determine if there exists a permutation p that is consistent with c. You do not have to construct the permutation p.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).InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 5 \cdot 10^3) — the number of test cases.The first line of each test case contains an integer n (1 \le n \le 10^5).The second line of each test case contains n integers c_1,c_2,\ldots,c_n (1 \leq c_i \leq n). It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print "YES" if there is a permutation p exists that satisfies the array c, and "NO" otherwise.You can output "YES" and "NO" in any case (for example, strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive response).ExampleInput 6 1 1 2 1 2 2 2 2 6 1 2 4 6 3 5 6 2 3 1 2 3 4 3 3 2 1 Output YES YES NO NO YES NO NoteIn the first test case, the permutation [1] satisfies the array c.In the second test case, the permutation [2,1] satisfies the array c.In the fifth test case, the permutation [5, 1, 2, 4, 6, 3] satisfies the array c. Let's see why this is true. The zeroth cyclic shift of p is [5, 1, 2, 4, 6, 3]. Its power is 2 since b = [5, 5, 5, 5, 6, 6] and there are 2 distinct elements — 5 and 6. The first cyclic shift of p is [3, 5, 1, 2, 4, 6]. Its power is 3 since b=[3,5,5,5,5,6]. The second cyclic shift of p is [6, 3, 5, 1, 2, 4]. Its power is 1 since b=[6,6,6,6,6,6]. The third cyclic shift of p is [4, 6, 3, 5, 1, 2]. Its power is 2 since b=[4,6,6,6,6,6]. The fourth cyclic shift of p is [2, 4, 6, 3, 5, 1]. Its power is 3 since b = [2, 4, 6, 6, 6, 6]. The fifth cyclic shift of p is [1, 2, 4, 6, 3, 5]. Its power is 4 since b = [1, 2, 4, 6, 6, 6]. Therefore, c = [2, 3, 1, 2, 3, 4].In the third, fourth, and sixth testcases, we can show that there is no permutation that satisfies array c.
6 1 1 2 1 2 2 2 2 6 1 2 4 6 3 5 6 2 3 1 2 3 4 3 3 2 1
YES YES NO NO YES NO
1 second
256 megabytes
['constructive algorithms', 'math', '*1700']
B. Marin and Anti-coprime Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMarin wants you to count number of permutations that are beautiful. A beautiful permutation of length n is a permutation that has the following property: \gcd (1 \cdot p_1, \, 2 \cdot p_2, \, \dots, \, n \cdot p_n) > 1, where \gcd is the greatest common divisor.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).InputThe first line contains one integer t (1 \le t \le 10^3) — the number of test cases.Each test case consists of one line containing one integer n (1 \le n \le 10^3).OutputFor each test case, print one integer — number of beautiful permutations. Because the answer can be very big, please print the answer modulo 998\,244\,353.ExampleInput 7 1 2 3 4 5 6 1000 Output 0 1 0 4 0 36 665702330 NoteIn first test case, we only have one permutation which is [1] but it is not beautiful because \gcd(1 \cdot 1) = 1.In second test case, we only have one beautiful permutation which is [2, 1] because \gcd(1 \cdot 2, 2 \cdot 1) = 2.
7 1 2 3 4 5 6 1000
0 1 0 4 0 36 665702330
1 second
256 megabytes
['combinatorics', 'math', 'number theory', '*800']
A. Marin and Photoshoottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday, Marin is at a cosplay exhibition and is preparing for a group photoshoot!For the group picture, the cosplayers form a horizontal line. A group picture is considered beautiful if for every contiguous segment of at least 2 cosplayers, the number of males does not exceed the number of females (obviously).Currently, the line has n cosplayers which can be described by a binary string s. The i-th cosplayer is male if s_i = 0 and female if s_i = 1. To ensure that the line is beautiful, you can invite some additional cosplayers (possibly zero) to join the line at any position. You can't remove any cosplayer from the line.Marin wants to know the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful. She can't do this on her own, so she's asking you for help. Can you help her?InputThe first line contains a single integer t (1 \leq t \leq 10^3) — the number of test cases. The first line of each test case contains a positive integer n (1 \leq n \leq 100) — the number of cosplayers in the initial line.The second line of each test case contains a binary string s of length n — describing the cosplayers already in line. Each character of the string is either 0 describing a male, or 1 describing a female.Note that there is no limit on the sum of n.OutputFor each test case, print the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful.ExampleInput 9 3 000 3 001 3 010 3 011 3 100 3 101 3 110 3 111 19 1010110000100000101 Output 4 2 1 0 2 0 0 0 17 NoteIn the first test case, for each pair of adjacent cosplayers, you can invite two female cosplayers to stand in between them. Then, 000 \rightarrow 0110110.In the third test case, you can invite one female cosplayer to stand next to the second cosplayer. Then, 010 \rightarrow 0110.
9 3 000 3 001 3 010 3 011 3 100 3 101 3 110 3 111 19 1010110000100000101
4 2 1 0 2 0 0 0 17
1 second
256 megabytes
['constructive algorithms', 'implementation', 'math', '*800']
F. Words on Treetime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices, and q triples (x_i, y_i, s_i), where x_i and y_i are integers from 1 to n, and s_i is a string with length equal to the number of vertices on the simple path from x_i to y_i.You want to write a lowercase Latin letter on each vertex in such a way that, for each of q given triples, at least one of the following conditions holds: if you write out the letters on the vertices on the simple path from x_i to y_i in the order they appear on this path, you get the string s_i; if you write out the letters on the vertices on the simple path from y_i to x_i in the order they appear on this path, you get the string s_i. Find any possible way to write a letter on each vertex to meet these constraints, or report that it is impossible.InputThe first line contains two integers n and q (2 \le n \le 4 \cdot 10^5; 1 \le q \le 4 \cdot 10^5) — the number of vertices in the tree and the number of triples, respectively.Then n - 1 lines follow; the i-th of them contains two integers u_i and v_i (1 \le u_i, v_i \le n; u_i \ne v_i) — the endpoints of the i-th edge. These edges form a tree.Then q lines follow; the j-th of them contains two integers x_j and y_j, and a string s_j consisting of lowercase Latin letters. The length of s_j is equal to the number of vertices on the simple path between x_j and y_j.Additional constraint on the input: \sum \limits_{j=1}^{q} |s_j| \le 4 \cdot 10^5.OutputIf there is no way to meet the conditions on all triples, print NO. Otherwise, print YES in the first line, and a string of n lowercase Latin letters in the second line; the i-th character of the string should be the letter you write on the i-th vertex. If there are multiple answers, print any of them.ExamplesInput 3 2 2 3 2 1 2 1 ab 2 3 bc Output YES abcInput 3 2 2 3 2 1 2 1 ab 2 3 cd Output NO Input 10 10 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 2 ab 1 3 ab 1 4 ab 1 5 ab 1 6 ab 1 7 ab 1 8 ab 1 9 ab 1 10 ab 10 2 aba Output YES baaaaaaaaaInput 10 10 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 2 ab 1 3 ab 1 4 aa 1 5 ab 1 6 ab 1 7 ab 1 8 ab 1 9 ab 1 10 ab 10 2 aba Output NO
3 2 2 3 2 1 2 1 ab 2 3 bc
YES abc
9 seconds
1024 megabytes
['2-sat', 'dfs and similar', 'dsu', 'graphs', 'trees', '*2600']
E. Star MSTtime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn this problem, we will consider complete undirected graphs consisting of n vertices with weighted edges. The weight of each edge is an integer from 1 to k.An undirected graph is considered beautiful if the sum of weights of all edges incident to vertex 1 is equal to the weight of MST in the graph. MST is the minimum spanning tree — a tree consisting of n-1 edges of the graph, which connects all n vertices and has the minimum sum of weights among all such trees; the weight of MST is the sum of weights of all edges in it.Calculate the number of complete beautiful graphs having exactly n vertices and the weights of edges from 1 to k. Since the answer might be large, print it modulo 998244353.InputThe only line contains two integers n and k (2 \le n \le 250; 1 \le k \le 250).OutputPrint one integer — the number of complete beautiful graphs having exactly n vertices and the weights of edges from 1 to k. Since the answer might be large, print it modulo 998244353.ExamplesInput 3 2 Output 5 Input 4 4 Output 571 Input 6 9 Output 310640163 Input 42 13 Output 136246935
3 2
5
6 seconds
512 megabytes
['combinatorics', 'dp', 'graph matchings', 'math', '*2200']
D. For Gamers. By Gamers.time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing a strategy game. In the game, he recruits a squad to fight monsters. Before each battle, Monocarp has C coins to spend on his squad.Before each battle starts, his squad is empty. Monocarp chooses one type of units and recruits no more units of that type than he can recruit with C coins.There are n types of units. Every unit type has three parameters: c_i — the cost of recruiting one unit of the i-th type; d_i — the damage that one unit of the i-th type deals in a second; h_i — the amount of health of one unit of the i-th type. Monocarp has to face m monsters. Every monster has two parameters: D_j — the damage that the j-th monster deals in a second; H_j — the amount of health the j-th monster has. Monocarp has to fight only the j-th monster during the j-th battle. He wants all his recruited units to stay alive. Both Monocarp's squad and the monster attack continuously (not once per second) and at the same time. Thus, Monocarp wins the battle if and only if his squad kills the monster strictly faster than the monster kills one of his units. The time is compared with no rounding.For each monster, Monocarp wants to know the minimum amount of coins he has to spend to kill that monster. If this amount is greater than C, then report that it's impossible to kill that monster.InputThe first line contains two integers n and C (1 \le n \le 3 \cdot 10^5; 1 \le C \le 10^6) — the number of types of units and the amount of coins Monocarp has before each battle.The i-th of the next n lines contains three integers c_i, d_i and h_i (1 \le c_i \le C; 1 \le d_i, h_i \le 10^6).The next line contains a single integer m (1 \le m \le 3 \cdot 10^5) — the number of monsters that Monocarp has to face.The j-th of the next m lines contains two integers D_j and H_j (1 \le D_j \le 10^6; 1 \le H_j \le 10^{12}).OutputPrint m integers. For each monster, print the minimum amount of coins Monocarp has to spend to kill that monster. If this amount is greater than C, then print -1.ExamplesInput 3 10 3 4 6 5 5 5 10 3 4 3 8 3 5 4 10 15 Output 5 3 -1 Input 5 15 14 10 3 9 2 2 10 4 3 7 3 5 4 3 1 6 11 2 1 1 4 7 2 1 1 14 3 3 Output 14 4 14 4 7 7 Input 5 13 13 1 9 6 4 5 12 18 4 9 13 2 5 4 5 2 16 3 6 2 Output 12 5 NoteConsider the first monster of the first example.Monocarp can't recruit one unit of the first type, because it will take both him and the monster 0.75 seconds to kill each other. He can recruit two units for the cost of 6 coins and kill the monster in 0.375 second.Monocarp can recruit one unit of the second type, because he kills the monster in 0.6 seconds, and the monster kills him in 0.625 seconds. The unit is faster. Thus, 5 coins is enough.Monocarp will need at least three units of the third type to kill the first monster, that will cost 30 coins.Monocarp will spend the least coins if he chooses the second type of units and recruits one unit of that type.
3 10 3 4 6 5 5 5 10 3 4 3 8 3 5 4 10 15
5 3 -1
4 seconds
256 megabytes
['binary search', 'brute force', 'greedy', 'math', 'sortings', '*2000']
C. Bracket Sequence Deletiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a bracket sequence consisting of n characters '(' and/or )'. You perform several operations with it.During one operation, you choose the shortest prefix of this string (some amount of first characters of the string) that is good and remove it from the string.The prefix is considered good if one of the following two conditions is satisfied: this prefix is a regular bracket sequence; this prefix is a palindrome of length at least two. A bracket sequence is called regular if it is possible to obtain a correct arithmetic expression by inserting characters '+' and '1' into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not.The bracket sequence is called palindrome if it reads the same back and forth. For example, the bracket sequences )), (( and )(() are palindromes, while bracket sequences (), )( and ))( are not palindromes.You stop performing the operations when it's not possible to find a good prefix. Your task is to find the number of operations you will perform on the given string and the number of remaining characters in the string.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. The next 2t lines describe test cases.The first line of the test case contains one integer n (1 \le n \le 5 \cdot 10^5) — the length of the bracket sequence.The second line of the test case contains n characters '(' and/or ')' — the bracket sequence itself.It is guaranteed that the sum of n over all test cases do not exceed 5 \cdot 10^5 (\sum n \le 5 \cdot 10^5).OutputFor each test case, print two integers c and r — the number of operations you will perform on the given bracket sequence and the number of characters that remain in the string after performing all operations.ExampleInput 5 2 () 3 ()) 4 (((( 5 )((() 6 )((()( Output 1 0 1 1 2 0 1 0 1 1
5 2 () 3 ()) 4 (((( 5 )((() 6 )((()(
1 0 1 1 2 0 1 0 1 1
2 seconds
256 megabytes
['greedy', 'implementation', '*1200']
B. XY Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given four integers n, B, x and y. You should build a sequence a_0, a_1, a_2, \dots, a_n where a_0 = 0 and for each i \ge 1 you can choose: either a_i = a_{i - 1} + x or a_i = a_{i - 1} - y. Your goal is to build such a sequence a that a_i \le B for all i and \sum\limits_{i=0}^{n}{a_i} is maximum possible.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Next t cases follow.The first and only line of each test case contains four integers n, B, x and y (1 \le n \le 2 \cdot 10^5; 1 \le B, x, y \le 10^9).It's guaranteed that the total sum of n doesn't exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the maximum possible \sum\limits_{i=0}^{n}{a_i}.ExampleInput 3 5 100 1 30 7 1000000000 1000000000 1000000000 4 1 7 3 Output 15 4000000000 -10 NoteIn the first test case, the optimal sequence a is [0, 1, 2, 3, 4, 5].In the second test case, the optimal sequence a is [0, 10^9, 0, 10^9, 0, 10^9, 0, 10^9].In the third test case, the optimal sequence a is [0, -3, -6, 1, -2].
3 5 100 1 30 7 1000000000 1000000000 1000000000 4 1 7 3
15 4000000000 -10
2 seconds
256 megabytes
['greedy', '*800']
A. Integer Movestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere's a chip in the point (0, 0) of the coordinate plane. In one operation, you can move the chip from some point (x_1, y_1) to some point (x_2, y_2) if the Euclidean distance between these two points is an integer (i.e. \sqrt{(x_1-x_2)^2+(y_1-y_2)^2} is integer).Your task is to determine the minimum number of operations required to move the chip from the point (0, 0) to the point (x, y).InputThe first line contains a single integer t (1 \le t \le 3000) — number of test cases.The single line of each test case contains two integers x and y (0 \le x, y \le 50) — the coordinates of the destination point.OutputFor each test case, print one integer — the minimum number of operations required to move the chip from the point (0, 0) to the point (x, y).ExampleInput 3 8 6 0 0 9 15 Output 1 0 2 NoteIn the first example, one operation (0, 0) \rightarrow (8, 6) is enough. \sqrt{(0-8)^2+(0-6)^2}=\sqrt{64+36}=\sqrt{100}=10 is an integer.In the second example, the chip is already at the destination point.In the third example, the chip can be moved as follows: (0, 0) \rightarrow (5, 12) \rightarrow (9, 15). \sqrt{(0-5)^2+(0-12)^2}=\sqrt{25+144}=\sqrt{169}=13 and \sqrt{(5-9)^2+(12-15)^2}=\sqrt{16+9}=\sqrt{25}=5 are integers.
3 8 6 0 0 9 15
1 0 2
2 seconds
256 megabytes
['brute force', 'math', '*800']
I. Neighbour Orderingtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an undirected graph G, we say that a neighbour ordering is an ordered list of all the neighbours of a vertex for each of the vertices of G. Consider a given neighbour ordering of G and three vertices u, v and w, such that v is a neighbor of u and w. We write u <_{v} w if u comes after w in v's neighbor list.A neighbour ordering is said to be good if, for each simple cycle v_1, v_2, \ldots, v_c of the graph, one of the following is satisfied: v_1 <_{v_2} v_3, v_2 <_{v_3} v_4, \ldots, v_{c-2} <_{v_{c-1}} v_c, v_{c-1} <_{v_c} v_1, v_c <_{v_1} v_2. v_1 >_{v_2} v_3, v_2 >_{v_3} v_4, \ldots, v_{c-2} >_{v_{c-1}} v_c, v_{c-1} >_{v_c} v_1, v_c >_{v_1} v_2. Given a graph G, determine whether there exists a good neighbour ordering for it and construct one if it does.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and m (2 \leq n \leq 3 \cdot 10^5, 1 \leq m \leq 3 \cdot 10^5), the number of vertices and the number of edges of the graph.The next m lines each contain two integers u, v (0 \leq u, v < n), denoting that there is an edge connecting vertices u and v. It is guaranteed that the graph is connected and there are no loops or multiple edges between the same vertices.The sum of n and the sum of m for all test cases are at most 3 \cdot 10^5.OutputFor each test case, output one line with YES if there is a good neighbour ordering, otherwise output one line with NO. You can print each letter in any case (upper or lower).If the answer is YES, additionally output n lines describing a good neighbour ordering. In the i-th line, output the neighbours of vertex i in order. If there are multiple good neigbour orderings, print any.ExampleInput 3 5 6 0 1 0 2 1 2 2 3 3 4 4 1 2 1 0 1 6 10 0 1 2 0 0 3 0 4 1 2 1 4 2 3 2 5 3 5 4 5 Output YES 1 2 4 2 0 0 1 3 2 4 3 1 YES 1 0 NO
3 5 6 0 1 0 2 1 2 2 3 3 4 4 1 2 1 0 1 6 10 0 1 2 0 0 3 0 4 1 2 1 4 2 3 2 5 3 5 4 5
YES 1 2 4 2 0 0 1 3 2 4 3 1 YES 1 0 NO
5 seconds
256 megabytes
['constructive algorithms', 'graphs', '*3500']
H. Equal LCM Subsetstime limit per test10 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two sets of positive integers A and B. You have to find two non-empty subsets S_A \subseteq A, S_B \subseteq B so that the least common multiple (LCM) of the elements of S_A is equal to the least common multiple (LCM) of the elements of S_B.InputThe input consists of multiple test cases. The first line of the input contains one integer t (1 \leq t \leq 200), the number of test cases.For each test case, there is one line containing two integers n, m (1 \leq n, m \leq 1000), the sizes of the sets A and B, respectively.The next line contains n distinct integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 4 \cdot 10^{36}), the elements of A.The next line contains m distinct integers b_1, b_2, \ldots, b_m (1 \leq b_i \leq 4 \cdot 10^{36}), the elements of B.The sum of n for all test cases and the sum of m for all test cases is at most 1000.OutputFor each test case, if there do not exist two subsets with equal least common multiple, output one line with NO.Otherwise, output one line with YES, followed by a line with two integers |S_A|, |S_B| (1 \leq |S_A| \leq n, 1 \leq |S_B| \leq m), the sizes of the subsets S_A and S_BThe next line should contain |S_A| integers x_1, x_2, \ldots, x_{|S_A|}, the elements of S_A, followed by a line with |S_B| integers y_1, y_2, \ldots, y_{|S_B|}, the elements of S_B. If there are multiple possible pairs of subsets, you can print any.ExampleInput 4 3 4 5 6 7 2 8 9 10 4 4 5 6 7 8 2 3 4 9 1 3 1 1 2 3 5 6 3 4 9 7 8 2 15 11 14 20 12 Output NO YES 1 2 6 2 3 YES 1 1 1 1 YES 3 2 3 7 4 12 14
4 3 4 5 6 7 2 8 9 10 4 4 5 6 7 8 2 3 4 9 1 3 1 1 2 3 5 6 3 4 9 7 8 2 15 11 14 20 12
NO YES 1 2 6 2 3 YES 1 1 1 1 YES 3 2 3 7 4 12 14
10 seconds
512 megabytes
['data structures', 'math', 'number theory', '*3200']
G. Cycle Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe say that a sequence of n integers a_1, a_2, \ldots, a_n is a palindrome if for all 1 \leq i \leq n, a_i = a_{n-i+1}. You are given a sequence of n integers a_1, a_2, \ldots, a_n and you have to find, if it exists, a cycle permutation \sigma so that the sequence a_{\sigma(1)}, a_{\sigma(2)}, \ldots, a_{\sigma(n)} is a palindrome. A permutation of 1, 2, \ldots, n is a bijective function from \{1, 2, \ldots, n\} to \{1, 2, \ldots, n\}. We say that a permutation \sigma is a cycle permutation if 1, \sigma(1), \sigma^2(1), \ldots, \sigma^{n-1}(1) are pairwise different numbers. Here \sigma^m(1) denotes \underbrace{\sigma(\sigma(\ldots \sigma}_{m \text{ times}}(1) \ldots)).InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 3 \cdot 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains an integer n (2 \leq n \leq 2 \cdot 10^5) — the size of the sequence.The second line of each test case contains n integers a_1, \ldots, a_n (1 \leq a_i \leq n).The sum of n for all test cases is at most 2 \cdot 10^5.OutputFor each test case, output one line with YES if a cycle permutation exists, otherwise output one line with NO.If the answer is YES, output one additional line with n integers \sigma(1), \sigma(2), \ldots, \sigma(n), the permutation. If there is more than one permutation, you may print any.ExampleInput 3 4 1 2 2 1 3 1 2 1 7 1 3 3 3 1 2 2 Output YES 3 1 4 2 NO YES 5 3 7 2 6 4 1
3 4 1 2 2 1 3 1 2 1 7 1 3 3 3 1 2 2
YES 3 1 4 2 NO YES 5 3 7 2 6 4 1
1 second
256 megabytes
['constructive algorithms', 'graphs', 'math', '*3200']
F. Parametric MSTtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a_1, a_2, \ldots, a_n. For any real number t, consider the complete weighted graph on n vertices K_n(t) with weight of the edge between vertices i and j equal to w_{ij}(t) = a_i \cdot a_j + t \cdot (a_i + a_j). Let f(t) be the cost of the minimum spanning tree of K_n(t). Determine whether f(t) is bounded above and, if so, output the maximum value it attains.InputThe input consists of multiple test cases. The first line contains a single integer T (1 \leq T \leq 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains an integer n (2 \leq n \leq 2 \cdot 10^5) — the number of vertices of the graph.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-10^6 \leq a_i \leq 10^6).The sum of n for all test cases is at most 2 \cdot 10^5.OutputFor each test case, print a single line with the maximum value of f(t) (it can be shown that it is an integer), or INF if f(t) is not bounded above. ExampleInput 5 2 1 0 2 -1 1 3 1 -1 -2 3 3 -1 -2 4 1 2 3 -4 Output INF -1 INF -6 -18
5 2 1 0 2 -1 1 3 1 -1 -2 3 3 -1 -2 4 1 2 3 -4
INF -1 INF -6 -18
1 second
256 megabytes
['binary search', 'constructive algorithms', 'graphs', 'greedy', 'math', 'sortings', '*2600']
E. Equal Tree Sumstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected unrooted tree, i.e. a connected undirected graph without cycles.You must assign a nonzero integer weight to each vertex so that the following is satisfied: if any vertex of the tree is removed, then each of the remaining connected components has the same sum of weights in its vertices.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains an integer n (3 \leq n \leq 10^5) — the number of vertices of the tree.The next n-1 lines of each case contain each two integers u, v (1 \leq u,v \leq n) denoting that there is an edge between vertices u and v. It is guaranteed that the given edges form a tree.The sum of n for all test cases is at most 10^5.OutputFor each test case, you must output one line with n space separated integers a_1, a_2, \ldots, a_n, where a_i is the weight assigned to vertex i. The weights must satisfy -10^5 \leq a_i \leq 10^5 and a_i \neq 0.It can be shown that there always exists a solution satisfying these constraints. If there are multiple possible solutions, output any of them.ExampleInput 2 5 1 2 1 3 3 4 3 5 3 1 2 1 3 Output -3 5 1 2 2 1 1 1 NoteIn the first case, when removing vertex 1 all remaining connected components have sum 5 and when removing vertex 3 all remaining connected components have sum 2. When removing other vertices, there is only one remaining connected component so all remaining connected components have the same sum.
2 5 1 2 1 3 3 4 3 5 3 1 2 1 3
-3 5 1 2 2 1 1 1
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'math', 'trees', '*2200']
D. K-goodtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe say that a positive integer n is k-good for some positive integer k if n can be expressed as a sum of k positive integers which give k distinct remainders when divided by k.Given a positive integer n, find some k \geq 2 so that n is k-good or tell that such a k does not exist.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases.Each test case consists of one line with an integer n (2 \leq n \leq 10^{18}).OutputFor each test case, print a line with a value of k such that n is k-good (k \geq 2), or -1 if n is not k-good for any k. If there are multiple valid values of k, you can print any of them.ExampleInput 5 2 4 6 15 20 Output -1 -1 3 3 5 Note6 is a 3-good number since it can be expressed as a sum of 3 numbers which give different remainders when divided by 3: 6 = 1 + 2 + 3.15 is also a 3-good number since 15 = 1 + 5 + 9 and 1, 5, 9 give different remainders when divided by 3.20 is a 5-good number since 20 = 2 + 3 + 4 + 5 + 6 and 2,3,4,5,6 give different remainders when divided by 5.
5 2 4 6 15 20
-1 -1 3 3 5
3 seconds
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1900']
C. Make Equal With Modtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n non-negative integers a_1, a_2, \ldots, a_n. You can make the following operation: choose an integer x \geq 2 and replace each number of the array by the remainder when dividing that number by x, that is, for all 1 \leq i \leq n set a_i to a_i \bmod x.Determine if it is possible to make all the elements of the array equal by applying the operation zero or more times.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9) where a_i is the i-th element of the array.The sum of n for all test cases is at most 2 \cdot 10^5.OutputFor each test case, print a line with YES if you can make all elements of the list equal by applying the operation. Otherwise, print NO.You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).ExampleInput 4 4 2 5 6 8 3 1 1 1 5 4 1 7 0 8 4 5 9 17 5 Output YES YES NO YES NoteIn the first test case, one can apply the operation with x = 3 to obtain the array [2, 2, 0, 2], and then apply the operation with x = 2 to obtain [0, 0, 0, 0].In the second test case, all numbers are already equal.In the fourth test case, applying the operation with x = 4 results in the array [1, 1, 1, 1].
4 4 2 5 6 8 3 1 1 1 5 4 1 7 0 8 4 5 9 17 5
YES YES NO YES
2 seconds
256 megabytes
['constructive algorithms', 'math', 'number theory', 'sortings', '*1200']
B. Subtract Operationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a list of n integers. You can perform the following operation: you choose an element x from the list, erase x from the list, and subtract the value of x from all the remaining elements. Thus, in one operation, the length of the list is decreased by exactly 1.Given an integer k (k>0), find if there is some sequence of n-1 operations such that, after applying the operations, the only remaining element of the list is equal to k.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and k (2 \leq n \leq 2\cdot 10^5, 1 \leq k \leq 10^9), the number of integers in the list, and the target value, respectively.The second line of each test case contains the n integers of the list a_1, a_2, \ldots, a_n (-10^9 \leq a_i \leq 10^9).It is guaranteed that the sum of n over all test cases is not greater that 2 \cdot 10^5.OutputFor each test case, print YES if you can achieve k with a sequence of n-1 operations. Otherwise, print NO.You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).ExampleInput 4 4 5 4 2 2 7 5 4 1 9 1 3 4 2 17 17 0 2 17 18 18 Output YES NO YES NO NoteIn the first example we have the list \{4, 2, 2, 7\}, and we have the target k = 5. One way to achieve it is the following: first we choose the third element, obtaining the list \{2, 0, 5\}. Next we choose the first element, obtaining the list \{-2, 3\}. Finally, we choose the first element, obtaining the list \{5\}.
4 4 5 4 2 2 7 5 4 1 9 1 3 4 2 17 17 0 2 17 18 18
YES NO YES NO
1 second
256 megabytes
['data structures', 'greedy', 'math', 'two pointers', '*1100']
A. Good Pairstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \ldots, a_n of positive integers. A good pair is a pair of indices (i, j) with 1 \leq i, j \leq n such that, for all 1 \leq k \leq n, the following equality holds: |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, where |x| denotes the absolute value of x.Find a good pair. Note that i can be equal to j.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases. Description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) where a_i is the i-th element of the array.The sum of n for all test cases is at most 2 \cdot 10^5.OutputFor each test case, print a single line with two space-separated indices i and j which form a good pair of the array. The case i=j is allowed. It can be shown that such a pair always exists. If there are multiple good pairs, print any of them.ExampleInput 3 3 5 2 7 5 1 4 2 2 3 1 2 Output 2 3 1 2 1 1 NoteIn the first case, for i = 2 and j = 3 the equality holds true for all k: k = 1: |a_2 - a_1| + |a_1 - a_3| = |2 - 5| + |5 - 7| = 5 = |2 - 7| = |a_2-a_3|, k = 2: |a_2 - a_2| + |a_2 - a_3| = |2 - 2| + |2 - 7| = 5 = |2 - 7| = |a_2-a_3|, k = 3: |a_2 - a_3| + |a_3 - a_3| = |2 - 7| + |7 - 7| = 5 = |2 - 7| = |a_2-a_3|.
3 3 5 2 7 5 1 4 2 2 3 1 2
2 3 1 2 1 1
1 second
256 megabytes
['math', 'sortings', '*800']
H. Three Minimumstime limit per test8 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputGiven a list of distinct values, we denote with first minimum, second minimum, and third minimum the three smallest values (in increasing order).A permutation p_1, p_2, \dots, p_n is good if the following statement holds for all pairs (l,r) with 1\le l < l+2 \le r\le n. If \{p_l, p_r\} are (not necessarily in this order) the first and second minimum of p_l, p_{l+1}, \dots, p_r then the third minimum of p_l, p_{l+1},\dots, p_r is either p_{l+1} or p_{r-1}. You are given an integer n and a string s of length m consisting of characters "<" and ">".Count the number of good permutations p_1, p_2,\dots, p_n such that, for all 1\le i\le m, p_i < p_{i+1} if s_i = "<"; p_i > p_{i+1} if s_i = ">". As the result can be very large, you should print it modulo 998\,244\,353.InputThe first line contains two integers n and m (2 \le n \le 2 \cdot 10^5, 1 \leq m \leq \min(100, n-1)).The second line contains a string s of length m, consisting of characters "<" and ">".OutputPrint a single integer: the number of good permutations satisfying the constraints described in the statement, modulo 998\,244\,353.ExamplesInput 5 3 >>> Output 5 Input 5 1 < Output 56 Input 6 5 <<><> Output 23 Input 10 5 ><<>< Output 83154 Input 1008 20 <><<>>><<<<<>>>>>>>> Output 284142857 NoteIn the first test, there are 5 good permutations satisfying the constraints given by the string s: [4, 3, 2, 1, 5], [5, 3, 2, 1, 4], [5, 4, 2, 1, 3], [5, 4, 3, 1, 2], [5, 4, 3, 2, 1]. Each of them is good; satisfies p_1 > p_2; satisfies p_2 > p_3; satisfies p_3 > p_4. In the second test, there are 60 permutations such that p_1 < p_2. Only 56 of them are good: the permutations [1, 4, 3, 5, 2], [1, 5, 3, 4, 2], [2, 4, 3, 5, 1], [2, 5, 3, 4, 1] are not good because the required condition doesn't hold for (l, r) = (1, 5). For example, for the permutation [2, 4, 3, 5, 1], the first minimum and the second minimum are p_5 and p_1, respectively (so they are \{p_l, p_r\} up to reordering); the third minimum is p_3 (neither p_{l+1} nor p_{r-1}). In the third test, there are 23 good permutations satisfying the constraints given by the string s: [1, 2, 4, 3, 6, 5], [1, 2, 5, 3, 6, 4], [1, 2, 6, 3, 5, 4], [1, 3, 4, 2, 6, 5], [1, 3, 5, 2, 6, 4], [1, 3, 6, 2, 5, 4], [1, 4, 5, 2, 6, 3], [1, 4, 6, 2, 5, 3], [1, 5, 6, 2, 4, 3], [2, 3, 4, 1, 6, 5], [2, 3, 5, 1, 6, 4], [2, 3, 6, 1, 5, 4], [2, 4, 5, 1, 6, 3], [2, 4, 6, 1, 5, 3], [2, 5, 6, 1, 4, 3], [3, 4, 5, 1, 6, 2], [3, 4, 5, 2, 6, 1], [3, 4, 6, 1, 5, 2], [3, 4, 6, 2, 5, 1], [3, 5, 6, 1, 4, 2], [3, 5, 6, 2, 4, 1], [4, 5, 6, 1, 3, 2], [4, 5, 6, 2, 3, 1].
5 3 >>>
5
8 seconds
1024 megabytes
['combinatorics', 'constructive algorithms', 'divide and conquer', 'dp', 'fft', 'math', '*3500']
G. Snowy Mountaintime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThere are n locations on a snowy mountain range (numbered from 1 to n), connected by n-1 trails in the shape of a tree. Each trail has length 1. Some of the locations are base lodges. The height h_i of each location is equal to the distance to the nearest base lodge (a base lodge has height 0).There is a skier at each location, each skier has initial kinetic energy 0. Each skier wants to ski along as many trails as possible. Suppose that the skier is skiing along a trail from location i to j. Skiers are not allowed to ski uphill (i.e., if h_i < h_j). It costs one unit of kinetic energy to ski along flat ground (i.e., if h_i = h_j), and a skier gains one unit of kinetic energy by skiing downhill (i.e., if h_i > h_j). For each location, compute the length of the longest sequence of trails that the skier starting at that location can ski along without their kinetic energy ever becoming negative. Skiers are allowed to visit the same location or trail multiple times.InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^5).The second line contains n integers l_1, l_2, \ldots, l_n (0 \le l_i \le 1). If l_i = 1, location i is a base lodge; if l_i = 0, location i is not a base lodge. It is guaranteed that there is at least 1 base lodge.Each of the next n-1 lines contains two integers u, v (1 \leq u, v \leq n, u \neq v), meaning that there is a trail that connects the locations u and v. It is guaranteed that the given trails form a tree.OutputPrint n integers: the i-th integer is equal to the length of the longest sequence of trails that the skier starting at location i can ski along without their kinetic energy ever becoming negative.ExamplesInput 6 1 1 0 0 0 0 1 3 2 4 3 4 4 5 5 6 Output 0 0 1 1 3 5 Input 9 0 0 0 0 0 0 1 1 1 1 3 2 3 2 5 3 6 4 5 4 7 5 8 6 9 Output 5 3 2 1 1 1 0 0 0 Input 14 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 2 2 5 3 4 4 5 3 6 4 8 5 9 7 8 6 11 7 12 8 13 9 14 10 11 Output 8 5 4 3 2 2 1 1 1 0 0 0 0 0 Input 20 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 0 1 17 3 11 12 6 10 18 19 8 14 16 20 5 3 2 11 7 10 2 15 8 3 3 15 9 16 7 13 16 1 19 2 2 16 6 1 4 17 Output 2 2 1 5 3 4 8 1 2 6 4 6 10 0 0 0 3 0 1 0 NoteIn the first test, h = [0, 0, 1, 1, 2, 3]. The skier starting from 6 can ski along at most 5 trails, in the path 6 \rightarrow 5 \rightarrow 4 \rightarrow 3 \rightarrow 4 \rightarrow 2 (notice that a skier can ski multiple times along the same trail and can visit more than once the same location): at the location 6, the kinetic energy is 0; at the location 5, the kinetic energy increases by 1 (because h_5 < h_6), so it becomes 1; at the location 4, the kinetic energy increases by 1 (because h_4 < h_5), so it becomes 2; at the location 3, the kinetic energy decreases by 1 (because h_3 = h_4), so it becomes 1; at the location 4, the kinetic energy decreases by 1 (because h_4 = h_3), so it becomes 0; at the location 2, the kinetic energy increases by 1 (because h_2 < h_4), so it becomes 1. There isn't any sequence of trails of length greater than 5 such that the kinetic energy is always non-negative.Moreover, the optimal path for the skier starting from 1 is 1 (no trails); the optimal path for the skier starting from 2 is 2 (no trails); the optimal path for the skier starting from 3 is 3 \rightarrow 1; the optimal path for the skier starting from 4 is 4 \rightarrow 2; the optimal path for the skier starting from 5 is 5 \rightarrow 4 \rightarrow 3 \rightarrow 1. In the second test, h = [3, 2, 2, 1, 1, 1, 0, 0, 0]. The skier starting from 1 can ski along at most 5 trails, in the path 1 \rightarrow 3 \rightarrow 2 \rightarrow 5 \rightarrow 4 \rightarrow 7. at the location 1, the kinetic energy is 0; at the location 3, the kinetic energy increases by 1 (because h_3 < h_1), so it becomes 1; at the location 2, the kinetic energy decreases by 1 (because h_2 = h_3), so it becomes 0; at the location 5, the kinetic energy increases by 1 (because h_5 < h_2), so it becomes 1; at the location 4, the kinetic energy decreases by 1 (because h_4 = h_5), so it becomes 0; at the location 7, the kinetic energy increases by 1 (because h_7 < h_4), so it becomes 1. There isn't any sequence of trails of length greater than 5 such that the kinetic energy is always non-negative.In the third test, for the skier starting from vertex 1, the optimal path is 1 \rightarrow 2 \rightarrow 5 \rightarrow 4 \rightarrow 3 \rightarrow 6 \rightarrow 11 \rightarrow 10 \rightarrow 11.Here are pictures of the first, second, and third test, with the base lodges shown in red:
6 1 1 0 0 0 0 1 3 2 4 3 4 4 5 5 6
0 0 1 1 3 5
5 seconds
1024 megabytes
['data structures', 'dfs and similar', 'graphs', 'greedy', 'shortest paths', 'trees', '*2900']
F. Minimal String Xorationtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an integer n and a string s consisting of 2^n lowercase letters of the English alphabet. The characters of the string s are s_0s_1s_2\cdots s_{2^n-1}.A string t of length 2^n (whose characters are denoted by t_0t_1t_2\cdots t_{2^n-1}) is a xoration of s if there exists an integer j (0\le j \leq 2^n-1) such that, for each 0 \leq i \leq 2^n-1, t_i = s_{i \oplus j} (where \oplus denotes the operation bitwise XOR).Find the lexicographically minimal xoration of s.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 18).The second line contains a string s consisting of 2^n lowercase letters of the English alphabet.OutputPrint a single line containing the lexicographically minimal xoration of s.ExamplesInput 2 acba Output abca Input 3 bcbaaabb Output aabbbcba Input 4 bdbcbccdbdbaaccd Output abdbdccacbdbdccb Input 5 ccfcffccccccffcfcfccfffffcccccff Output cccccffffcccccffccfcffcccccfffff Input 1 zz Output zz NoteIn the first test, the lexicographically minimal xoration t of s ="acba" is "abca". It's a xoration because, for j = 3, t_0 = s_{0 \oplus j} = s_3 = "a"; t_1 = s_{1 \oplus j} = s_2 = "b"; t_2 = s_{2 \oplus j} = s_1 = "c"; t_3 = s_{3 \oplus j} = s_0 = "a". There isn't any xoration of s lexicographically smaller than "abca".In the second test, the minimal string xoration corresponds to choosing j = 4 in the definition of xoration.In the third test, the minimal string xoration corresponds to choosing j = 11 in the definition of xoration.In the fourth test, the minimal string xoration corresponds to choosing j = 10 in the definition of xoration.In the fifth test, the minimal string xoration corresponds to choosing either j = 0 or j = 1 in the definition of xoration.
2 acba
abca
3 seconds
512 megabytes
['bitmasks', 'data structures', 'divide and conquer', 'greedy', 'hashing', 'sortings', 'strings', '*2800']
E. Arithmetic Operationstime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a_1, a_2, \ldots, a_n.You can do the following operation any number of times (possibly zero): Choose any index i and set a_i to any integer (positive, negative or 0). What is the minimum number of operations needed to turn a into an arithmetic progression? The array a is an arithmetic progression if a_{i+1}-a_i=a_i-a_{i-1} for any 2 \leq i \leq n-1.InputThe first line contains a single integer n (1 \le n \le 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^5).OutputPrint a single integer: the minimum number of operations needed to turn a into an arithmetic progression.ExamplesInput 9 3 2 7 8 6 9 5 4 1 Output 6 Input 14 19 2 15 8 9 14 17 13 4 14 4 11 15 7 Output 10 Input 10 100000 1 60000 2 20000 4 8 16 32 64 Output 7 Input 4 10000 20000 10000 1 Output 2 NoteIn the first test, you can get the array a = [11, 10, 9, 8, 7, 6, 5, 4, 3] by performing 6 operations: Set a_3 to 9: the array becomes [3, 2, 9, 8, 6, 9, 5, 4, 1]; Set a_2 to 10: the array becomes [3, 10, 9, 8, 6, 9, 5, 4, 1]; Set a_6 to 6: the array becomes [3, 10, 9, 8, 6, 6, 5, 4, 1]; Set a_9 to 3: the array becomes [3, 10, 9, 8, 6, 6, 5, 4, 3]; Set a_5 to 7: the array becomes [3, 10, 9, 8, 7, 6, 5, 4, 3]; Set a_1 to 11: the array becomes [11, 10, 9, 8, 7, 6, 5, 4, 3]. a is an arithmetic progression: in fact, a_{i+1}-a_i=a_i-a_{i-1}=-1 for any 2 \leq i \leq n-1.There is no sequence of less than 6 operations that makes a an arithmetic progression.In the second test, you can get the array a = [-1, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38] by performing 10 operations.In the third test, you can get the array a = [100000, 80000, 60000, 40000, 20000, 0, -20000, -40000, -60000, -80000] by performing 7 operations.
9 3 2 7 8 6 9 5 4 1
6
5 seconds
1024 megabytes
['brute force', 'data structures', 'graphs', 'math', '*2300']
D. Potion Brewing Classtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice's potion making professor gave the following assignment to his students: brew a potion using n ingredients, such that the proportion of ingredient i in the final potion is r_i > 0 (and r_1 + r_2 + \cdots + r_n = 1).He forgot the recipe, and now all he remembers is a set of n-1 facts of the form, "ingredients i and j should have a ratio of x to y" (i.e., if a_i and a_j are the amounts of ingredient i and j in the potion respectively, then it must hold a_i/a_j = x/y), where x and y are positive integers. However, it is guaranteed that the set of facts he remembers is sufficient to uniquely determine the original values r_i.He decided that he will allow the students to pass the class as long as they submit a potion which satisfies all of the n-1 requirements (there may be many such satisfactory potions), and contains a positive integer amount of each ingredient.Find the minimum total amount of ingredients needed to make a potion which passes the class. As the result can be very large, you should print the answer modulo 998\,244\,353.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5).Each of the next n-1 lines contains four integers i, j, x, y (1 \le i, j \le n, i\not=j, 1\le x, y \le n) — ingredients i and j should have a ratio of x to y. It is guaranteed that the set of facts is sufficient to uniquely determine the original values r_i.It is also guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the minimum total amount of ingredients needed to make a potion which passes the class, modulo 998\,244\,353.ExampleInput 3 4 3 2 3 4 1 2 4 3 1 4 2 4 8 5 4 2 3 6 4 5 4 1 3 5 2 6 8 2 1 3 5 3 4 3 2 2 5 6 7 4 3 17 8 7 4 16 9 17 4 5 5 14 13 12 11 1 17 14 6 13 8 9 2 11 3 11 4 17 7 2 17 16 8 6 15 5 1 14 16 7 1 10 12 17 13 10 11 16 7 2 10 11 6 4 13 17 14 6 3 11 15 8 15 6 12 8 Output 69 359 573672453 NoteIn the first test case, the minimum total amount of ingredients is 69. In fact, the amounts of ingredients 1, 2, 3, 4 of a valid potion are 16, 12, 9, 32, respectively. The potion is valid because Ingredients 3 and 2 have a ratio of 9 : 12 = 3 : 4; Ingredients 1 and 2 have a ratio of 16 : 12 = 4 : 3; Ingredients 1 and 4 have a ratio of 16 : 32 = 2 : 4. In the second test case, the amounts of ingredients 1, 2, 3, 4, 5, 6, 7, 8 in the potion that minimizes the total amount of ingredients are 60, 60, 24, 48, 32, 60, 45, 30.
3 4 3 2 3 4 1 2 4 3 1 4 2 4 8 5 4 2 3 6 4 5 4 1 3 5 2 6 8 2 1 3 5 3 4 3 2 2 5 6 7 4 3 17 8 7 4 16 9 17 4 5 5 14 13 12 11 1 17 14 6 13 8 9 2 11 3 11 4 17 7 2 17 16 8 6 15 5 1 14 16 7 1 10 12 17 13 10 11 16 7 2 10 11 6 4 13 17 14 6 3 11 15 8 15 6 12 8
69 359 573672453
3 seconds
256 megabytes
['dfs and similar', 'math', 'number theory', 'trees', '*2100']
C. Alice and the Caketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has a cake, and she is going to cut it. She will perform the following operation n-1 times: choose a piece of the cake (initially, the cake is all one piece) with weight w\ge 2 and cut it into two smaller pieces of weight \lfloor\frac{w}{2}\rfloor and \lceil\frac{w}{2}\rceil (\lfloor x \rfloor and \lceil x \rceil denote floor and ceiling functions, respectively).After cutting the cake in n pieces, she will line up these n pieces on a table in an arbitrary order. Let a_i be the weight of the i-th piece in the line.You are given the array a. Determine whether there exists an initial weight and sequence of operations which results in a.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single line: print YES if the array a could have resulted from Alice's operations, otherwise print NO.You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).ExampleInput 14 1 327 2 869 541 2 985214736 985214737 3 2 3 1 3 2 3 3 6 1 1 1 1 1 1 6 100 100 100 100 100 100 8 100 100 100 100 100 100 100 100 8 2 16 1 8 64 1 4 32 10 1 2 4 7 1 1 1 1 7 2 10 7 1 1 1 3 1 3 3 2 3 10 1 4 4 1 1 1 3 3 3 1 10 2 3 2 2 1 2 2 2 2 2 4 999999999 999999999 999999999 999999999 Output YES NO YES YES NO YES NO YES YES YES YES NO NO YES NoteIn the first test case, it's possible to get the array a by performing 0 operations on a cake with weight 327.In the second test case, it's not possible to get the array a.In the third test case, it's possible to get the array a by performing 1 operation on a cake with weight 1\,970\,429\,473: Cut it in half, so that the weights are [985\,214\,736, 985\,214\,737]. Note that the starting weight can be greater than 10^9.In the fourth test case, it's possible to get the array a by performing 2 operations on a cake with weight 6: Cut it in half, so that the weights are [3,3]. Cut one of the two pieces with weight 3, so that the new weights are [1, 2, 3] which is equivalent to [2, 3, 1] up to reordering.
14 1 327 2 869 541 2 985214736 985214737 3 2 3 1 3 2 3 3 6 1 1 1 1 1 1 6 100 100 100 100 100 100 8 100 100 100 100 100 100 100 100 8 2 16 1 8 64 1 4 32 10 1 2 4 7 1 1 1 1 7 2 10 7 1 1 1 3 1 3 3 2 3 10 1 4 4 1 1 1 3 3 3 1 10 2 3 2 2 1 2 2 2 2 2 4 999999999 999999999 999999999 999999999
YES NO YES YES NO YES NO YES YES YES YES NO NO YES
2 seconds
256 megabytes
['data structures', 'greedy', 'implementation', 'sortings', '*1400']
B. Prefix Removalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of lowercase letters of the English alphabet. You must perform the following algorithm on s: Let x be the length of the longest prefix of s which occurs somewhere else in s as a contiguous substring (the other occurrence may also intersect the prefix). If x = 0, break. Otherwise, remove the first x characters of s, and repeat. A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".For instance, if we perform the algorithm on s = "abcabdc", Initially, "ab" is the longest prefix that also appears somewhere else as a substring in s, so s = "cabdc" after 1 operation. Then, "c" is the longest prefix that also appears somewhere else as a substring in s, so s = "abdc" after 2 operations. Now x=0 (because there are no non-empty prefixes of "abdc" that also appear somewhere else as a substring in s), so the algorithm terminates. Find the final state of the string after performing the algorithm.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.This is followed by t lines, each containing a description of one test case. Each line contains a string s. The given strings consist only of lowercase letters of the English alphabet and have lengths between 1 and 2 \cdot 10^5 inclusive.It is guaranteed that the sum of the lengths of s over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single line containing the string s after executing the algorithm. It can be shown that such string is non-empty.ExampleInput 6 abcabdc a bbbbbbbbbb codeforces cffcfccffccfcffcfccfcffccffcfccf zyzyzwxxyyxxyyzzyzzxxwzxwywxwzxxyzzw Output abdc a b deforces cf xyzzw NoteThe first test case is explained in the statement.In the second test case, no operations can be performed on s.In the third test case, Initially, s = "bbbbbbbbbb". After 1 operation, s = "b". In the fourth test case, Initially, s = "codeforces". After 1 operation, s = "odeforces". After 2 operations, s = "deforces".
6 abcabdc a bbbbbbbbbb codeforces cffcfccffccfcffcfccfcffccffcfccf zyzyzwxxyyxxyyzzyzzxxwzxwywxwzxxyzzw
abdc a b deforces cf xyzzw
2 seconds
256 megabytes
['strings', '*800']
A. Maximum Cake Tastinesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n pieces of cake on a line. The i-th piece of cake has weight a_i (1 \leq i \leq n).The tastiness of the cake is the maximum total weight of two adjacent pieces of cake (i. e., \max(a_1+a_2,\, a_2+a_3,\, \ldots,\, a_{n-1} + a_{n})).You want to maximize the tastiness of the cake. You are allowed to do the following operation at most once (doing more operations would ruin the cake): Choose a contiguous subsegment a[l, r] of pieces of cake (1 \leq l \leq r \leq n), and reverse it. The subsegment a[l, r] of the array a is the sequence a_l, a_{l+1}, \dots, a_r.If you reverse it, the array will become a_1, a_2, \dots, a_{l-2}, a_{l-1}, \underline{a_r}, \underline{a_{r-1}}, \underline{\dots}, \underline{a_{l+1}}, \underline{a_l}, a_{r+1}, a_{r+2}, \dots, a_{n-1}, a_n.For example, if the weights are initially [5, 2, 1, 4, 7, 3], you can reverse the subsegment a[2, 5], getting [5, \underline{7}, \underline{4}, \underline{1}, \underline{2}, 3]. The tastiness of the cake is now 5 + 7 = 12 (while before the operation the tastiness was 4+7=11).Find the maximum tastiness of the cake after doing the operation at most once.InputThe first line contains a single integer t (1 \le t \le 50) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 1000) — the number of pieces of cake.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — a_i is the weight of the i-th piece of cake.OutputFor each test case, print a single integer: the maximum tastiness of the cake after doing the operation at most once.ExampleInput 5 6 5 2 1 4 7 3 3 32 78 78 3 69 54 91 8 999021 999021 999021 999021 999652 999021 999021 999021 2 1000000000 1000000000 Output 12 156 160 1998673 2000000000 NoteIn the first test case, after reversing the subsegment a[2, 5], you get a cake with weights [5, \underline{7}, \underline{4}, \underline{1}, \underline{2}, 3]. The tastiness of the cake is now \max(5+7, 7+4, 4+1, 1+2, 2+3) = 12. This is the maximum possible tastiness of the cake one can obtain by performing the operation at most once.In the second test case, it's optimal not to do any operation. The tastiness is 78+78 = 156.In the third test case, after reversing the subsegment a[1, 2], you get a cake with weights [\underline{54}, \underline{69}, 91]. The tastiness of the cake is now \max(54+69, 69+91) = 160. There is no way to make the tastiness of the cake greater than 160 by performing at most one operation.
5 6 5 2 1 4 7 3 3 32 78 78 3 69 54 91 8 999021 999021 999021 999021 999652 999021 999021 999021 2 1000000000 1000000000
12 156 160 1998673 2000000000
2 seconds
256 megabytes
['brute force', 'greedy', 'implementation', 'sortings', '*800']
F. Tower Defensetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp is playing a tower defense game. A level in the game can be represented as an OX axis, where each lattice point from 1 to n contains a tower in it.The tower in the i-th point has c_i mana capacity and r_i mana regeneration rate. In the beginning, before the 0-th second, each tower has full mana. If, at the end of some second, the i-th tower has x mana, then it becomes \mathit{min}(x + r_i, c_i) mana for the next second.There are q monsters spawning on a level. The j-th monster spawns at point 1 at the beginning of t_j-th second, and it has h_j health. Every monster is moving 1 point per second in the direction of increasing coordinate.When a monster passes the tower, the tower deals \mathit{min}(H, M) damage to it, where H is the current health of the monster and M is the current mana amount of the tower. This amount gets subtracted from both monster's health and tower's mana.Unfortunately, sometimes some monsters can pass all n towers and remain alive. Monocarp wants to know what will be the total health of the monsters after they pass all towers.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of towers.The i-th of the next n lines contains two integers c_i and r_i (1 \le r_i \le c_i \le 10^9) — the mana capacity and the mana regeneration rate of the i-th tower.The next line contains a single integer q (1 \le q \le 2 \cdot 10^5) — the number of monsters.The j-th of the next q lines contains two integers t_j and h_j (0 \le t_j \le 2 \cdot 10^5; 1 \le h_j \le 10^{12}) — the time the j-th monster spawns and its health.The monsters are listed in the increasing order of their spawn time, so t_j < t_{j+1} for all 1 \le j \le q-1.OutputPrint a single integer — the total health of all monsters after they pass all towers.ExamplesInput 3 5 1 7 4 4 2 4 0 14 1 10 3 16 10 16 Output 4 Input 5 2 1 4 1 5 4 7 5 8 3 9 1 21 2 18 3 14 4 24 5 8 6 25 7 19 8 24 9 24 Output 40
3 5 1 7 4 4 2 4 0 14 1 10 3 16 10 16
4
4 seconds
512 megabytes
['binary search', 'brute force', 'data structures', '*3000']
E. Sum of Matchingstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's denote the size of the maximum matching in a graph G as \mathit{MM}(G).You are given a bipartite graph. The vertices of the first part are numbered from 1 to n, the vertices of the second part are numbered from n+1 to 2n. Each vertex's degree is 2.For a tuple of four integers (l, r, L, R), where 1 \le l \le r \le n and n+1 \le L \le R \le 2n, let's define G'(l, r, L, R) as the graph which consists of all vertices of the given graph that are included in the segment [l, r] or in the segment [L, R], and all edges of the given graph such that each of their endpoints belongs to one of these segments. In other words, to obtain G'(l, r, L, R) from the original graph, you have to remove all vertices i such that i \notin [l, r] and i \notin [L, R], and all edges incident to these vertices.Calculate the sum of \mathit{MM}(G(l, r, L, R)) over all tuples of integers (l, r, L, R) having 1 \le l \le r \le n and n+1 \le L \le R \le 2n.InputThe first line contains one integer n (2 \le n \le 1500) — the number of vertices in each part.Then 2n lines follow, each denoting an edge of the graph. The i-th line contains two integers x_i and y_i (1 \le x_i \le n; n + 1 \le y_i \le 2n) — the endpoints of the i-th edge.There are no multiple edges in the given graph, and each vertex has exactly two incident edges.OutputPrint one integer — the sum of \mathit{MM}(G(l, r, L, R)) over all tuples of integers (l, r, L, R) having 1 \le l \le r \le n and n+1 \le L \le R \le 2n.ExampleInput 5 4 6 4 9 2 6 3 9 1 8 5 10 2 7 3 7 1 10 5 8 Output 314
5 4 6 4 9 2 6 3 9 1 8 5 10 2 7 3 7 1 10 5 8
314
4 seconds
512 megabytes
['brute force', 'combinatorics', 'constructive algorithms', 'dfs and similar', 'graph matchings', 'greedy', 'math', '*2600']
D. Nearest Excluded Pointstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n distinct points on a plane. The coordinates of the i-th point are (x_i, y_i).For each point i, find the nearest (in terms of Manhattan distance) point with integer coordinates that is not among the given n points. If there are multiple such points — you can choose any of them.The Manhattan distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of points in the set.The next n lines describe points. The i-th of them contains two integers x_i and y_i (1 \le x_i, y_i \le 2 \cdot 10^5) — coordinates of the i-th point.It is guaranteed that all points in the input are distinct.OutputPrint n lines. In the i-th line, print the point with integer coordinates that is not among the given n points and is the nearest (in terms of Manhattan distance) to the i-th point from the input.Output coordinates should be in range [-10^6; 10^6]. It can be shown that any optimal answer meets these constraints.If there are several answers, you can print any of them.ExamplesInput 6 2 2 1 2 2 1 3 2 2 3 5 5 Output 1 1 1 1 2 0 3 1 2 4 5 4 Input 8 4 4 2 4 2 2 2 3 1 4 4 2 1 3 3 3 Output 4 3 2 5 2 1 2 5 1 5 4 1 1 2 3 2
6 2 2 1 2 2 1 3 2 2 3 5 5
1 1 1 1 2 0 3 1 2 4 5 4
4 seconds
256 megabytes
['binary search', 'data structures', 'dfs and similar', 'graphs', 'shortest paths', '*1900']
C. Fault-tolerant Networktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a classroom with two rows of computers. There are n computers in each row and each computer has its own grade. Computers in the first row has grades a_1, a_2, \dots, a_n and in the second row — b_1, b_2, \dots, b_n.Initially, all pairs of neighboring computers in each row are connected by wire (pairs (i, i + 1) for all 1 \le i < n), so two rows form two independent computer networks.Your task is to combine them in one common network by connecting one or more pairs of computers from different rows. Connecting the i-th computer from the first row and the j-th computer from the second row costs |a_i - b_j|.You can connect one computer to several other computers, but you need to provide at least a basic fault tolerance: you need to connect computers in such a way that the network stays connected, despite one of its computer failing. In other words, if one computer is broken (no matter which one), the network won't split in two or more parts.That is the minimum total cost to make a fault-tolerant network?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Next t cases follow.The first line of each test case contains the single integer n (3 \le n \le 2 \cdot 10^5) — the number of computers in each row.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the grades of computers in the first row.The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^9) — the grades of computers in the second row.It's guaranteed that the total sum of n doesn't exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the minimum total cost to make a fault-tolerant network.ExampleInput 231 10 120 4 2541 1 1 11000000000 1000000000 1000000000 1000000000Output 31 1999999998 NoteIn the first test case, it's optimal to connect four pairs of computers: computer 1 from the first row with computer 2 from the second row: cost |1 - 4| = 3; computer 3 from the first row with computer 2 from the second row: cost |1 - 4| = 3; computer 2 from the first row with computer 1 from the second row: cost |10 - 20| = 10; computer 2 from the first row with computer 3 from the second row: cost |10 - 25| = 15; In total, 3 + 3 + 10 + 15 = 31.In the second test case, it's optimal to connect 1 from the first row with 1 from the second row, and 4 from the first row with 4 from the second row.
231 10 120 4 2541 1 1 11000000000 1000000000 1000000000 1000000000
31 1999999998
2 seconds
256 megabytes
['brute force', 'data structures', 'implementation', '*1500']
B. Prove Him Wrongtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, your friend discovered one special operation on an integer array a: Choose two indices i and j (i \neq j); Set a_i = a_j = |a_i - a_j|. After playing with this operation for a while, he came to the next conclusion: For every array a of n integers, where 1 \le a_i \le 10^9, you can find a pair of indices (i, j) such that the total sum of a will decrease after performing the operation. This statement sounds fishy to you, so you want to find a counterexample for a given integer n. Can you find such counterexample and prove him wrong?In other words, find an array a consisting of n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) such that for all pairs of indices (i, j) performing the operation won't decrease the total sum (it will increase or not change the sum).InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.The first and only line of each test case contains a single integer n (2 \le n \le 1000) — the length of array a.OutputFor each test case, if there is no counterexample array a of size n, print NO.Otherwise, print YES followed by the array a itself (1 \le a_i \le 10^9). If there are multiple counterexamples, print any.ExampleInput 3 2 512 3 Output YES 1 337 NO YES 31 4 159 NoteIn the first test case, the only possible pairs of indices are (1, 2) and (2, 1).If you perform the operation on indices (1, 2) (or (2, 1)), you'll get a_1 = a_2 = |1 - 337| = 336, or array [336, 336]. In both cases, the total sum increases, so this array a is a counterexample.
3 2 512 3
YES 1 337 NO YES 31 4 159
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*800']
A. Playofftime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a playoff tournament where 2^n athletes compete. The athletes are numbered from 1 to 2^n.The tournament is held in n stages. In each stage, the athletes are split into pairs in such a way that each athlete belongs exactly to one pair. In each pair, the athletes compete against each other, and exactly one of them wins. The winner of each pair advances to the next stage, the athlete who was defeated gets eliminated from the tournament.The pairs are formed as follows: in the first stage, athlete 1 competes against athlete 2; 3 competes against 4; 5 competes against 6, and so on; in the second stage, the winner of the match "1–2" competes against the winner of the match "3–4"; the winner of the match "5–6" competes against the winner of the match "7–8", and so on; the next stages are held according to the same rules. When athletes x and y compete, the winner is decided as follows: if x+y is odd, the athlete with the lower index wins (i. e. if x < y, then x wins, otherwise y wins); if x+y is even, the athlete with the higher index wins. The following picture describes the way the tournament with n = 3 goes. Your task is the following one: given the integer n, determine the index of the athlete who wins the tournament.InputThe first line contains one integer t (1 \le t \le 30) — the number of test cases.Each test case consists of one line containing one integer n (1 \le n \le 30).OutputFor each test case, print one integer — the index of the winner of the tournament.ExampleInput 2 3 1 Output 7 1 NoteThe case n = 3 is shown in the picture from the statement.If n = 1, then there's only one match between athletes 1 and 2. Since 1 + 2 = 3 is an odd number, the athlete with the lower index wins. So, the athlete 1 is the winner.
2 3 1
7 1
2 seconds
512 megabytes
['implementation', '*800']
G. Counting Shortcutstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an undirected connected graph with n vertices and m edges. The graph contains no loops (edges from a vertex to itself) and multiple edges (i.e. no more than one edge between each pair of vertices). The vertices of the graph are numbered from 1 to n. Find the number of paths from a vertex s to t whose length differs from the shortest path from s to t by no more than 1. It is necessary to consider all suitable paths, even if they pass through the same vertex or edge more than once (i.e. they are not simple). Graph consisting of 6 of vertices and 8 of edges For example, let n = 6, m = 8, s = 6 and t = 1, and let the graph look like the figure above. Then the length of the shortest path from s to t is 1. Consider all paths whose length is at most 1 + 1 = 2. 6 \rightarrow 1. The length of the path is 1. 6 \rightarrow 4 \rightarrow 1. Path length is 2. 6 \rightarrow 2 \rightarrow 1. Path length is 2. 6 \rightarrow 5 \rightarrow 1. Path length is 2. There is a total of 4 of matching paths.InputThe first line of test contains the number t (1 \le t \le 10^4) —the number of test cases in the test.Before each test case, there is a blank line. The first line of test case contains two numbers n, m (2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5) —the number of vertices and edges in the graph. The second line contains two numbers s and t (1 \le s, t \le n, s \neq t) —the numbers of the start and end vertices of the path.The following m lines contain descriptions of edges: the ith line contains two integers u_i, v_i (1 \le u_i,v_i \le n) — the numbers of vertices that connect the ith edge. It is guaranteed that the graph is connected and does not contain loops and multiple edges.It is guaranteed that the sum of values n on all test cases of input data does not exceed 2 \cdot 10^5. Similarly, it is guaranteed that the sum of values m on all test cases of input data does not exceed 2 \cdot 10^5.OutputFor each test case, output a single number — the number of paths from s to t such that their length differs from the length of the shortest path by no more than 1.Since this number may be too large, output it modulo 10^9 + 7.ExampleInput 4 4 4 1 4 1 2 3 4 2 3 2 4 6 8 6 1 1 4 1 6 1 5 1 2 5 6 4 6 6 3 2 6 5 6 1 3 3 5 5 4 3 1 4 2 2 1 1 4 8 18 5 1 2 1 3 1 4 2 5 2 6 5 7 3 8 4 6 4 8 7 1 4 4 7 1 6 6 7 3 8 8 5 4 5 4 3 8 2 Output 2 4 1 11
4 4 4 1 4 1 2 3 4 2 3 2 4 6 8 6 1 1 4 1 6 1 5 1 2 5 6 4 6 6 3 2 6 5 6 1 3 3 5 5 4 3 1 4 2 2 1 1 4 8 18 5 1 2 1 3 1 4 2 5 2 6 5 7 3 8 4 6 4 8 7 1 4 4 7 1 6 6 7 3 8 8 5 4 5 4 3 8 2
2 4 1 11
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'dp', 'graphs', 'shortest paths', '*2100']
F. Vitaly and Advanced Useless Algorithmstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitaly enrolled in the course Advanced Useless Algorithms. The course consists of n tasks. Vitaly calculated that he has a_i hours to do the task i from the day he enrolled in the course. That is, the deadline before the i-th task is a_i hours. The array a is sorted in ascending order, in other words, the job numbers correspond to the order in which the assignments are turned in.Vitaly does everything conscientiously, so he wants to complete each task by 100 percent, or more. Initially, his completion rate for each task is 0 percent.Vitaly has m training options, each option can be used not more than once. The ith option is characterized by three integers: e_i, t_i and p_i. If Vitaly uses the ith option, then after t_i hours (from the current moment) he will increase the progress of the task e_i by p_i percent. For example, let Vitaly have 3 of tasks to complete. Let the array a have the form: a = [5, 7, 8]. Suppose Vitaly has 5 of options: [e_1=1, t_1=1, p_1=30], [e_2=2, t_2=3, p_2=50], [e_3=2, t_3=3, p_3=100], [e_4=1, t_4=1, p_4=80], [e_5=3, t_5=3, p_5=100]. Then, if Vitaly prepares in the following way, he will be able to complete everything in time: Vitaly chooses the 4-th option. Then in 1 hour, he will complete the 1-st task at 80 percent. He still has 4 hours left before the deadline for the 1-st task. Vitaly chooses the 3-rd option. Then in 3 hours, he will complete the 2-nd task in its entirety. He has another 1 hour left before the deadline for the 1-st task and 4 hours left before the deadline for the 3-rd task. Vitaly chooses the 1-st option. Then after 1 hour, he will complete the 1-st task for 110 percent, which means that he will complete the 1-st task just in time for the deadline. Vitaly chooses the 5-th option. He will complete the 3-rd task for 2 hours, and after another 1 hour, Vitaly will complete the 3-rd task in its entirety. Thus, Vitaly has managed to complete the course completely and on time, using the 4 options.Help Vitaly — print the options for Vitaly to complete the tasks in the correct order. Please note: each option can be used not more than once. If there are several possible answers, it is allowed to output any of them.InputThe first line of input data contains an integer T (1 \le T \le 10^4) —the number of input test cases in the test.The descriptions of the input test case follow.The first line of each test case description contains two integers n and m (1 \le n,m \le 10^5) —the number of jobs and the number of training options, respectively.The next line contains n numbers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the time before the deadline of job i. The array values — are non-decreasing, that is a_1 \le a_2 \le \dots \le a_n.The following m lines contain triples of numbers e_i, t_i, p_i (1 \le e_i \le n, 1 \le t_i \le 10^9, 1 \le p_i \le 100) — if Vitaly chooses this option, then after t_i hours he will increase the progress of the task e_i by p_i percent. The options are numbered from 1 to m in order in the input data.It is guaranteed that the sum of n+m on all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print on the first line the number k, meaning that for k of options, Vitaly will be able to complete each task by 100 percent or more on time. The options should not be repeated. Or print -1 if Vitaly is unable to complete all tasks in time.If there is an answer, on the next line print k of different integers from 1 to m — the numbers of the options in the order you want. If there is more than one answer, it is allowed to print any of them.ExamplesInput 5 3 5 5 7 8 1 1 30 2 3 50 2 3 100 1 1 80 3 3 100 1 5 51 1 36 91 1 8 40 1 42 83 1 3 45 1 13 40 2 9 9 20 2 8 64 2 7 64 1 20 56 2 8 76 2 20 48 1 2 89 1 3 38 2 18 66 1 7 51 3 2 7 18 33 1 5 80 3 4 37 2 5 569452312 703565975 1 928391659 66 1 915310 82 2 87017081 92 1 415310 54 2 567745964 82 Output 4 1 4 3 5 3 2 4 5 4 6 7 1 2 -1 4 2 4 3 5 Input 3 3 9 20 31 40 1 9 64 3 17 100 3 9 59 3 18 57 3 20 49 2 20 82 2 14 95 1 8 75 2 16 67 2 6 20 36 2 2 66 2 20 93 1 3 46 1 10 64 2 8 49 2 18 40 1 1 1000000000 1 1000000000 100 Output -1 4 3 4 1 5 1 1
5 3 5 5 7 8 1 1 30 2 3 50 2 3 100 1 1 80 3 3 100 1 5 51 1 36 91 1 8 40 1 42 83 1 3 45 1 13 40 2 9 9 20 2 8 64 2 7 64 1 20 56 2 8 76 2 20 48 1 2 89 1 3 38 2 18 66 1 7 51 3 2 7 18 33 1 5 80 3 4 37 2 5 569452312 703565975 1 928391659 66 1 915310 82 2 87017081 92 1 415310 54 2 567745964 82
4 1 4 3 5 3 2 4 5 4 6 7 1 2 -1 4 2 4 3 5
2 seconds
256 megabytes
['dp', 'greedy', 'implementation', '*2200']
E. Rescheduling the Examtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow Dmitry has a session, and he has to pass n exams. The session starts on day 1 and lasts d days. The ith exam will take place on the day of a_i (1 \le a_i \le d), all a_i — are different. Sample, where n=3, d=12, a=[3,5,9]. Orange — exam days. Before the first exam Dmitry will rest 2 days, before the second he will rest 1 day and before the third he will rest 3 days. For the session schedule, Dmitry considers a special value \mu — the smallest of the rest times before the exam for all exams. For example, for the image above, \mu=1. In other words, for the schedule, he counts exactly n numbers  — how many days he rests between the exam i-1 and i (for i=0 between the start of the session and the exam i). Then it finds \mu — the minimum among these n numbers.Dmitry believes that he can improve the schedule of the session. He may ask to change the date of one exam (change one arbitrary value of a_i). Help him change the date so that all a_i remain different, and the value of \mu is as large as possible.For example, for the schedule above, it is most advantageous for Dmitry to move the second exam to the very end of the session. The new schedule will take the form: Now the rest periods before exams are equal to [2,2,5]. So, \mu=2. Dmitry can leave the proposed schedule unchanged (if there is no way to move one exam so that it will lead to an improvement in the situation).InputThe first line of input data contains an integer t (1 \le t \le 10^4) — the number of input test cases. The descriptions of test cases follow.An empty line is written in the test before each case.The first line of each test case contains two integers n and d (2 \le n \le 2 \cdot 10^5, 1 \le d \le 10^9) — the number of exams and the length of the session, respectively.The second line of each test case contains n integers a_i (1 \le a_i \le d, a_i < a_{i+1}), where the i-th number means the date of the i-th exam.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the maximum possible value of \mu if Dmitry can move any one exam to an arbitrary day. All values of a_i should remain distinct.ExampleInput 9 3 12 3 5 9 2 5 1 5 2 100 1 2 5 15 3 6 9 12 15 3 1000000000 1 400000000 500000000 2 10 3 4 2 2 1 2 4 15 6 11 12 13 2 20 17 20 Output 2 1 1 2 99999999 3 0 1 9 NoteThe first sample is parsed in statement.One of the optimal schedule changes for the second sample: Initial schedule. New schedule.In the third sample, we need to move the exam from day 1 to any day from 4 to 100.In the fourth sample, any change in the schedule will only reduce \mu, so the schedule should be left as it is.In the fifth sample, we need to move the exam from day 1 to any day from 100000000 to 300000000.One of the optimal schedule changes for the sixth sample: Initial schedule. New schedule.In the seventh sample, every day is exam day, and it is impossible to rearrange the schedule.
9 3 12 3 5 9 2 5 1 5 2 100 1 2 5 15 3 6 9 12 15 3 1000000000 1 400000000 500000000 2 10 3 4 2 2 1 2 4 15 6 11 12 13 2 20 17 20
2 1 1 2 99999999 3 0 1 9
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'implementation', 'math', 'sortings', '*1900']
D. Twist the Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya got an array a of numbers from 1 to n, where a[i]=i.He performed n operations sequentially. In the end, he received a new state of the a array.At the i-th operation, Petya chose the first i elements of the array and cyclically shifted them to the right an arbitrary number of times (elements with indexes i+1 and more remain in their places). One cyclic shift to the right is such a transformation that the array a=[a_1, a_2, \dots, a_n] becomes equal to the array a = [a_i, a_1, a_2, \dots, a_{i-2}, a_{i-1}, a_{i+1}, a_{i+2}, \dots, a_n].For example, if a = [5,4,2,1,3] and i=3 (that is, this is the third operation), then as a result of this operation, he could get any of these three arrays: a = [5,4,2,1,3] (makes 0 cyclic shifts, or any number that is divisible by 3); a = [2,5,4,1,3] (makes 1 cyclic shift, or any number that has a remainder of 1 when divided by 3); a = [4,2,5,1,3] (makes 2 cyclic shifts, or any number that has a remainder of 2 when divided by 3). Let's look at an example. Let n=6, i.e. initially a=[1,2,3,4,5,6]. A possible scenario is described below. i=1: no matter how many cyclic shifts Petya makes, the array a does not change. i=2: let's say Petya decided to make a 1 cyclic shift, then the array will look like a = [\textbf{2}, \textbf{1}, 3, 4, 5, 6]. i=3: let's say Petya decided to make 1 cyclic shift, then the array will look like a = [\textbf{3}, \textbf{2}, \textbf{1}, 4, 5, 6]. i=4: let's say Petya decided to make 2 cyclic shifts, the original array will look like a = [\textbf{1}, \textbf{4}, \textbf{3}, \textbf{2}, 5, 6]. i=5: let's say Petya decided to make 0 cyclic shifts, then the array won't change. i=6: let's say Petya decided to make 4 cyclic shifts, the array will look like a = [\textbf{3}, \textbf{2}, \textbf{5}, \textbf{6}, \textbf{1}, \textbf{4}]. You are given a final array state a after all n operations. Determine if there is a way to perform the operation that produces this result. In this case, if an answer exists, print the numbers of cyclical shifts that occurred during each of the n operations.InputThe first line of the input contains an integer t (1 \le t \le 500) — the number of test cases in the test.The descriptions of the test cases follow.The first line of the description of each test case contains one integer n (2 \le n \le 2\cdot10^3) — the length of the array a.The next line contains the final state of the array a: n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) are written. All a_i are distinct.It is guaranteed that the sum of n values over all test cases does not exceed 2\cdot10^3.OutputFor each test case, print the answer on a separate line.Print -1 if the given final value a cannot be obtained by performing an arbitrary number of cyclic shifts on each operation. Otherwise, print n non-negative integers d_1, d_2, \dots, d_n (d_i \ge 0), where d_i means that during the i-th operation the first i elements of the array were cyclic shifted to the right d_i times.If there are several possible answers, print the one where the total number of shifts is minimal (that is, the sum of d_i values is the smallest). If there are several such answers, print any of them.ExampleInput 3 6 3 2 5 6 1 4 3 3 1 2 8 5 8 1 3 2 6 4 7 Output 0 1 1 2 0 4 0 0 1 0 1 2 0 2 5 6 2 NoteThe first test case matches the example from the statement.The second set of input data is simple. Note that the answer [3, 2, 1] also gives the same permutation, but since the total number of shifts 3+2+1 is greater than 0+0+1, this answer is not correct.
3 6 3 2 5 6 1 4 3 3 1 2 8 5 8 1 3 2 6 4 7
0 1 1 2 0 4 0 0 1 0 1 2 0 2 5 6 2
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'implementation', 'math', '*1300']