problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
F. Squarestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n squares drawn from left to right on the floor. The i-th square has three integers p_i,a_i,b_i, written on it. The sequence p_1,p_2,\dots,p_n forms a permutation.Each round you will start from the leftmost square 1 and jump to the right. If you are now on the i-th square, you can do one of the following two operations: Jump to the i+1-th square and pay the cost a_i. If i=n, then you can end the round and pay the cost a_i. Jump to the j-th square and pay the cost b_i, where j is the leftmost square that satisfies j > i, p_j > p_i. If there is no such j then you can end the round and pay the cost b_i. There are q rounds in the game. To make the game more difficult, you need to maintain a square set S (initially it is empty). You must pass through these squares during the round (other squares can also be passed through). The square set S for the i-th round is obtained by adding or removing a square from the square set for the (i-1)-th round. For each round find the minimum cost you should pay to end it.InputThe first line contains two integers n, q (1\le n,q\le 2 \cdot 10^5)  — the number of squares and the number of rounds.The second line contains n distinct integers p_1,p_2,\dots,p_n (1\le p_i\le n). It is guaranteed that the sequence p_1,p_2,\dots,p_n forms a permutation.The third line contains n integers a_1,a_2,\ldots,a_n (-10^9\le a_i\le 10^9).The fourth line contains n integers b_1,b_2,\dots,b_n (-10^9\le b_i\le 10^9).Then q lines follow, i-th of them contains a single integer x_i (1\le x_i\le n). If x_i was in the set S on the (i-1)-th round you should remove it, otherwise, you should add it.OutputPrint q lines, each of them should contain a single integer  — the minimum cost you should pay to end the corresponding round.ExamplesInput 3 2 2 1 3 10 -5 4 3 -2 3 1 2 Output 6 8 Input 5 4 2 1 5 3 4 6 -5 3 -10 -1 0 3 2 7 2 1 2 3 2 Output -8 -7 -7 -8 NoteLet's consider the character T as the end of a round. Then we can draw two graphs for the first and the second test. In the first round of the first test, the set that you must pass through is \{1\}. The path you can use is 1\to 3\to T and its cost is 6.In the second round of the first test, the set that you must pass through is \{1,2\}. The path you can use is 1\to 2\to 3\to T and its cost is 8.
3 2 2 1 3 10 -5 4 3 -2 3 1 2
6 8
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'dp', 'graphs', 'trees', '*3300']
E. Qingshan and Danieltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputQingshan and Daniel are going to play a card game. But it will be so boring if only two persons play this. So they will make n robots in total to play this game automatically. Robots made by Qingshan belong to the team 1, and robots made by Daniel belong to the team 2. Robot i belongs to team t_i. Before the game starts, a_i cards are given for robot i.The rules for this card game are simple: Before the start, the robots are arranged in a circle in the order or their indices. The robots will discard cards in some order, in each step one robot discards a single card. When the game starts, robot 1 will discard one of its cards. After that, robots will follow the following rules: If robot i discards the card last, the nearest robot whose team is opposite from i's will discard the card next. In another word j will discard a card right after i, if and only if among all j that satisfy t_i\ne t_j, dist(i,j) (definition is below) is minimum. The robot who has no cards should quit the game immediately. This robot won't be considered in the next steps. When no robot can discard the card next, the game ends. We define the distance from robot x to robot y as dist(x,y)=(y-x+n)\bmod n. It is similar to the oriented distance on the circle.For example, when n=5, the distance from 1 to 3 is dist(1,3)=(3-1+5)\bmod 5=2, the distance from 3 to 1 is dist(3,1)=(1-3+5)\bmod 5 =3.Later, Qingshan finds out that it will take so much time to see how robots play. She wants to know the result as quickly as possible. You, as Qingshan's fan, are asked to calculate an array [ans_1,ans_2,\ldots,ans_n] — ans_i is equal to the number of cards, that i-th robot will discard during the game. You need to hurry!To avoid the large size of the input, the team and the number of cards of each robot will be generated in your code with some auxiliary arrays.InputThe first line contains one integer n (1 \le n \le 5\cdot 10^6) — the number of robots playing this game.The second line contains one integer m (1 \le m \le \min(n,200\,000)).Each of the next m line contains four integers p_i, k_i, b_i, w_i (1 \le p_i \le n, 1 \le k_i \le 10^9+7, 0 \le b_i ,w_i< k_i). It's guaranteed that p_m=n and p_{j-1}<p_{j} (2 \le j \le m).Arrays a_j and t_j should be generated by the following pseudo code:seed = 0base = 0function rnd(): ret = seed seed = (seed * base + 233) mod 1000000007 return retp[0] = 0for i = 1 to m: seed = b[i] base = w[i] for j = p[i - 1] + 1 to p[i]: t[j] = (rnd() mod 2) + 1 a[j] = (rnd() mod k[i]) + 1OutputPrint a single integer \left( \prod_{i=1}^{n} ((ans_i \oplus i^2)+1)\right) \bmod 10^9+7, where \oplus denotes the bitwise XOR operation.ExamplesInput 3 3 1 5 2 3 2 7 1 2 3 2 1 1 Output 100 Input 5000000 2 1919810 998244353 114514 19260817 5000000 233333333 623532 7175 Output 800210675 Input 1 1 1 1 0 0 Output 1 NoteIn the first test case a=[5,5,1] and t=[1,2,2].The robot 1 discards the card first.Then robot 2 discards the card next. Robot 3 doesn't discard the card next because dist(1,2)<dist(1,3).Then robot 1 discards the card next. Robot 3 doesn't discard the card next because t_2=t_3.If we write down the index of the robot who discards a card in time order, it will be the sequence [1,2,1,2,1,2,1,2]. So robots 1, 2 and 3 discard 5, 5 and 0 cards, respectively. And the answer is (((5 \oplus 1^2)+1)\times((5 \oplus 2^2)+1)\times((0 \oplus 3^2)+1)) \bmod 10^9+7=(5\times 2 \times 10)\bmod 10^9+7=100.
3 3 1 5 2 3 2 7 1 2 3 2 1 1
100
2 seconds
256 megabytes
['brute force', 'data structures', 'greedy', 'implementation', '*3200']
D. BFS Treestime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time.You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998\,244\,353.InputThe first line contains two integers n, m (1 \le n \le 400, 0 \le m \le 600) — the number of vertices and the number of edges in the graph.The i-th of the next m lines contains two integers a_i, b_i (1 \leq a_i, b_i \leq n, a_i < b_i), representing an edge connecting a_i and b_i.It is guaranteed that all edges are distinct and the graph is connected.OutputPrint n lines, each consisting of n integers.The integer printed in the row i and the column j should be f(i,j) \bmod 998\,244\,353.ExamplesInput 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 NoteThe following picture describes the first example.The tree with red edges is a BFS tree rooted at both 1 and 2.Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way.
4 4 1 2 2 3 3 4 1 4
2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2
2.5 seconds
512 megabytes
['combinatorics', 'dfs and similar', 'graphs', 'math', 'shortest paths', 'trees', '*2600']
C. Garden of the Suntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are many sunflowers in the Garden of the Sun.Garden of the Sun is a rectangular table with n rows and m columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were burned into ashes. In other words, those cells struck by the lightning became empty. Magically, any two empty cells have no common points (neither edges nor corners).Now the owner wants to remove some (possibly zero) sunflowers to reach the following two goals: When you are on an empty cell, you can walk to any other empty cell. In other words, those empty cells are connected. There is exactly one simple path between any two empty cells. In other words, there is no cycle among the empty cells. You can walk from an empty cell to another if they share a common edge.Could you please give the owner a solution that meets all her requirements?Note that you are not allowed to plant sunflowers. You don't need to minimize the number of sunflowers you remove. It can be shown that the answer always exists.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. The description of the test cases follows.The first line contains two integers n, m (1 \le n,m \le 500) — the number of rows and columns. Each of the next n lines contains m characters. Each character is either 'X' or '.', representing an empty cell and a cell that grows a sunflower, respectively.It is guaranteed that the sum of n \cdot m for all test cases does not exceed 250\,000.OutputFor each test case, print n lines. Each should contain m characters, representing one row of the table. Each character should be either 'X' or '.', representing an empty cell and a cell with a sunflower, respectively.If there are multiple answers, you can print any. It can be shown that the answer always exists.ExampleInput 5 3 3 X.X ... X.X 4 4 .... .X.X .... .X.X 5 5 .X... ....X .X... ..... X.X.X 1 10 ....X.X.X. 2 2 .. .. Output XXX ..X XXX XXXX .X.X .X.. .XXX .X... .XXXX .X... .X... XXXXX XXXXXXXXXX .. .. NoteLet's use (x,y) to describe the cell on x-th row and y-th column.In the following pictures white, yellow, and blue cells stand for the cells that grow a sunflower, the cells lightning stroke, and the cells sunflower on which are removed, respectively.In the first test case, one possible solution is to remove sunflowers on (1,2), (2,3) and (3 ,2). Another acceptable solution is to remove sunflowers on (1,2), (2,2) and (3,2). This output is considered wrong because there are 2 simple paths between any pair of cells (there is a cycle). For example, there are 2 simple paths between (1,1) and (3,3). (1,1)\to (1,2)\to (1,3)\to (2,3)\to (3,3) (1,1)\to (2,1)\to (3,1)\to (3,2)\to (3,3) This output is considered wrong because you can't walk from (1,1) to (3,3).
5 3 3 X.X ... X.X 4 4 .... .X.X .... .X.X 5 5 .X... ....X .X... ..... X.X.X 1 10 ....X.X.X. 2 2 .. ..
XXX ..X XXX XXXX .X.X .X.. .XXX .X... .XXXX .X... .X... XXXXX XXXXXXXXXX .. ..
1 second
256 megabytes
['constructive algorithms', 'graphs', '*2300']
B. Let's Go Hikingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper.A permutation p is written from left to right on the paper. First Qingshan chooses an integer index x (1\le x\le n) and tells it to Daniel. After that, Daniel chooses another integer index y (1\le y\le n, y \ne x).The game progresses turn by turn and as usual, Qingshan moves first. The rules follow: If it is Qingshan's turn, Qingshan must change x to such an index x' that 1\le x'\le n, |x'-x|=1, x'\ne y, and p_{x'}<p_x at the same time. If it is Daniel's turn, Daniel must change y to such an index y' that 1\le y'\le n, |y'-y|=1, y'\ne x, and p_{y'}>p_y at the same time. The person who can't make her or his move loses, and the other wins. You, as Qingshan's fan, are asked to calculate the number of possible x to make Qingshan win in the case both players play optimally.InputThe first line contains a single integer n (2\le n\le 10^5) — the length of the permutation.The second line contains n distinct integers p_1,p_2,\dots,p_n (1\le p_i\le n) — the permutation.OutputPrint the number of possible values of x that Qingshan can choose to make her win.ExamplesInput 5 1 2 5 4 3 Output 1 Input 7 1 2 4 6 5 3 7 Output 0 NoteIn the first test case, Qingshan can only choose x=3 to win, so the answer is 1.In the second test case, if Qingshan will choose x=4, Daniel can choose y=1. In the first turn (Qingshan's) Qingshan chooses x'=3 and changes x to 3. In the second turn (Daniel's) Daniel chooses y'=2 and changes y to 2. Qingshan can't choose x'=2 because y=2 at this time. Then Qingshan loses.
5 1 2 5 4 3
1
1 second
256 megabytes
['games', 'greedy', '*1900']
A. Diamond Minertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDiamond Miner is a game that is similar to Gold Miner, but there are n miners instead of 1 in this game.The mining area can be described as a plane. The n miners can be regarded as n points on the y-axis. There are n diamond mines in the mining area. We can regard them as n points on the x-axis. For some reason, no miners or diamond mines can be at the origin (point (0, 0)). Every miner should mine exactly one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point (a,b) uses his hook to mine a diamond mine at the point (c,d), he will spend \sqrt{(a-c)^2+(b-d)^2} energy to mine it (the distance between these points). The miners can't move or help each other.The object of this game is to minimize the sum of the energy that miners spend. Can you find this minimum?InputThe input consists of multiple test cases. The first line contains a single integer t (1\le t\le 10) — 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 10^5) — the number of miners and mines.Each of the next 2n lines contains two space-separated integers x (-10^8 \le x \le 10^8) and y (-10^8 \le y \le 10^8), which represent the point (x,y) to describe a miner's or a diamond mine's position. Either x = 0, meaning there is a miner at the point (0, y), or y = 0, meaning there is a diamond mine at the point (x, 0). There can be multiple miners or diamond mines at the same point.It is guaranteed that no point is at the origin. It is guaranteed that the number of points on the x-axis is equal to n and the number of points on the y-axis is equal to n.It's guaranteed that the sum of n for all test cases does not exceed 10^5.OutputFor each test case, print a single real number — the minimal sum of energy that should be spent.Your answer is considered correct if its absolute or relative error does not exceed 10^{-9}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}.ExampleInput 3 2 0 1 1 0 0 -1 -2 0 4 1 0 3 0 -5 0 6 0 0 3 0 1 0 2 0 4 5 3 0 0 4 0 -3 4 0 2 0 1 0 -3 0 0 -10 0 -2 0 -10 Output 3.650281539872885 18.061819283610362 32.052255376143336 NoteIn the first test case, the miners are at (0,1) and (0,-1), while the diamond mines are at (1,0) and (-2,0). If you arrange the miners to get the diamond mines in the way, shown in the picture, you can get the sum of the energy \sqrt2 + \sqrt5.
3 2 0 1 1 0 0 -1 -2 0 4 1 0 3 0 -5 0 6 0 0 3 0 1 0 2 0 4 5 3 0 0 4 0 -3 4 0 2 0 1 0 -3 0 0 -10 0 -2 0 -10
3.650281539872885 18.061819283610362 32.052255376143336
1 second
256 megabytes
['geometry', 'greedy', 'math', 'sortings', '*1200']
F. Delete The Edgestime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an undirected connected graph consisting of n vertices and m edges. Your goal is to destroy all edges of the given graph.You may choose any vertex as the starting one and begin walking from it along the edges. When you walk along an edge, you destroy it. Obviously, you cannot walk along an edge if it is destroyed.You can perform the mode shift operation at most once during your walk, and this operation can only be performed when you are at some vertex (you cannot perform it while traversing an edge). After the mode shift, the edges you go through are deleted in the following way: the first edge after the mode shift is not destroyed, the second one is destroyed, the third one is not destroyed, the fourth one is destroyed, and so on. You cannot switch back to the original mode, and you don't have to perform this operation if you don't want to.Can you destroy all the edges of the given graph?InputThe first line contains two integers n and m (2 \le n \le 3000; n - 1 \le m \le \min(\frac{n(n-1)}{2}, 3000)) — the numbef of vertices and the number of edges in the graph.Then m lines follow, each containing two integers x_i and y_i (1 \le x_i, y_i \le n; x_i \ne y_i) — the endpoints of the i-th edge. These edges form a connected undirected graph without multiple edges.OutputIf it's impossible to destroy all of the edges, print 0.Otherwise, print the sequence of your actions as follows. First, print k — the number of actions (k \le 2m + 2). Then, print the sequence itself, consisting of k integers. The first integer should be the index of the starting vertex. Then, each of the next integers should be either the index of the next vertex in your traversal, or -1 if you use mode shift. You are allowed to use mode shift at most once.If there are multiple answers, print any of them.ExamplesInput 3 3 1 2 2 3 3 1 Output 4 1 2 3 1 Input 4 3 1 2 2 3 4 2 Output 8 2 -1 1 2 3 2 4 2 Input 5 5 1 2 2 3 3 1 2 4 2 5 Output 9 2 3 1 2 -1 4 2 5 2 Input 5 5 1 2 2 3 3 1 2 4 4 5 Output 8 5 4 2 3 1 -1 2 1 Input 6 5 1 2 2 3 3 4 4 5 3 6 Output 0
3 3 1 2 2 3 3 1
4 1 2 3 1
8 seconds
512 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'graphs', 'implementation', '*2900']
E. A-Z Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty.You should process m queries with it. Each query is one of three types: "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; "? k" — find the sequence of k vertices v_1, v_2, \dots, v_k such that there exist both routes v_1 \to v_2 \to \dots \to v_k and v_k \to v_{k - 1} \to \dots \to v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. InputThe first line contains two integers n and m (2 \le n \le 2 \cdot 10^5; 1 \le m \le 2 \cdot 10^5) — the number of vertices in the graph and the number of queries.The next m lines contain queries — one per line. Each query is one of three types: "+ u v c" (1 \le u, v \le n; u \neq v; c is a lowercase Latin letter); "- u v" (1 \le u, v \le n; u \neq v); "? k" (2 \le k \le 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type.OutputFor each query of the third type, print YES if there exist the sequence v_1, v_2, \dots, v_k described above, or NO otherwise.ExampleInput 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES NoteIn the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3 and 3 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 1.In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters.In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3 \xrightarrow{\text{d}} 2 \xrightarrow{\text{c}} 1.
3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5
YES NO YES
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'graphs', 'hashing', '*2400']
D. Dogeforcestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Dogeforces company has k employees. Each employee, except for lower-level employees, has at least 2 subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates.The full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company.InputThe first line contains a single integer n (2 \le n \le 500) — the number of lower-level employees.This is followed by n lines, where i-th line contains n integers a_{i,1}, a_{i,2}, \dots, a_{i,n} (1 \le a_{i,j} \le 5000) — salary of the common supervisor of employees with numbers i and j. It is guaranteed that a_{i,j} = a_{j,i}. Note that a_{i,i} is equal to the salary of the i-th employee.OutputIn the first line, print a single integer k — the number of employees in the company.In the second line, print k integers c_1, c_2, \dots, c_k, where c_i is the salary of the employee with the number i.In the third line, print a single integer r — the number of the employee who is the head of the company.In the following k-1 lines, print two integers v and u (1 \le v, u \le k) — the number of the employee and his direct supervisor.Note that the lower-level employees have numbers from 1 to n, and for the rest of the employees, you have to assign numbers from n+1 to k. If there are several correct company structures, you can print any of them.ExampleInput 3 2 5 7 5 1 7 7 7 4 Output 5 2 1 4 7 5 4 1 5 2 5 5 4 3 4 NoteOne of the possible structures in the first example:
3 2 5 7 5 1 7 7 7 4
5 2 1 4 7 5 4 1 5 2 5 5 4 3 4
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'dfs and similar', 'divide and conquer', 'dsu', 'greedy', 'sortings', 'trees', '*2300']
C. 1D Sokobantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a game similar to Sokoban on an infinite number line. The game is discrete, so you only consider integer positions on the line.You start on a position 0. There are n boxes, the i-th box is on a position a_i. All positions of the boxes are distinct. There are also m special positions, the j-th position is b_j. All the special positions are also distinct.In one move you can go one position to the left or to the right. If there is a box in the direction of your move, then you push the box to the next position in that direction. If the next position is taken by another box, then that box is also pushed to the next position, and so on. You can't go through the boxes. You can't pull the boxes towards you.You are allowed to perform any number of moves (possibly, zero). Your goal is to place as many boxes on special positions as possible. Note that some boxes can be initially placed on special positions.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then descriptions of t testcases follow.The first line of each testcase contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of boxes and the number of special positions, respectively.The second line of each testcase contains n distinct integers in the increasing order a_1, a_2, \dots, a_n (-10^9 \le a_1 < a_2 < \dots < a_n \le 10^9; a_i \neq 0) — the initial positions of the boxes.The third line of each testcase contains m distinct integers in the increasing order b_1, b_2, \dots, b_m (-10^9 \le b_1 < b_2 < \dots < b_m \le 10^9; b_i \neq 0) — the special positions.The sum of n over all testcases doesn't exceed 2 \cdot 10^5. The sum of m over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase print a single integer — the maximum number of boxes that can be placed on special positions.ExampleInput 5 5 6 -1 1 5 11 15 -4 -3 -2 6 7 15 2 2 -1 1 -1000000000 1000000000 2 2 -1000000000 1000000000 -1 1 3 5 -1 1 2 -2 -1 1 2 5 2 1 1 2 10 Output 4 2 0 3 1 NoteIn the first testcase you can go 5 to the right: the box on position 1 gets pushed to position 6 and the box on position 5 gets pushed to position 7. Then you can go 6 to the left to end up on position -1 and push a box to -2. At the end, the boxes are on positions [-2, 6, 7, 11, 15], respectively. Among them positions [-2, 6, 7, 15] are special, thus, the answer is 4.In the second testcase you can push the box from -1 to -10^9, then the box from 1 to 10^9 and obtain the answer 2.The third testcase showcases that you are not allowed to pull the boxes, thus, you can't bring them closer to special positions.In the fourth testcase all the boxes are already on special positions, so you can do nothing and still obtain the answer 3.In the fifth testcase there are fewer special positions than boxes. You can move either 8 or 9 to the right to have some box on position 10.
5 5 6 -1 1 5 11 15 -4 -3 -2 6 7 15 2 2 -1 1 -1000000000 1000000000 2 2 -1000000000 1000000000 -1 1 3 5 -1 1 2 -2 -1 1 2 5 2 1 1 2 10
4 2 0 3 1
2 seconds
256 megabytes
['binary search', 'dp', 'greedy', 'implementation', 'two pointers', '*1900']
B. Berland Crosswordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland crossword is a puzzle that is solved on a square grid with n rows and n columns. Initially all the cells are white.To solve the puzzle one has to color some cells on the border of the grid black in such a way that: exactly U cells in the top row are black; exactly R cells in the rightmost column are black; exactly D cells in the bottom row are black; exactly L cells in the leftmost column are black. Note that you can color zero cells black and leave every cell white.Your task is to check if there exists a solution to the given puzzle.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then the descriptions of t testcases follow.The only line of each testcase contains 5 integers n, U, R, D, L (2 \le n \le 100; 0 \le U, R, D, L \le n).OutputFor each testcase print "YES" if the solution exists and "NO" otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).ExampleInput 4 5 2 5 3 1 3 0 0 0 0 4 4 1 4 0 2 1 1 1 1 Output YES YES NO YES NoteHere are possible solutions to testcases 1, 2 and 4:
4 5 2 5 3 1 3 0 0 0 0 4 4 1 4 0 2 1 1 1 1
YES YES NO YES
2 seconds
256 megabytes
['bitmasks', 'brute force', 'greedy', 'implementation', '*1400']
A. ABC Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string a, consisting of n characters, n is even. For each i from 1 to n a_i is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You want to find a string b that consists of n characters such that: b is a regular bracket sequence; if for some i and j (1 \le i, j \le n) a_i=a_j, then b_i=b_j. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string b exists.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then the descriptions of t testcases follow.The only line of each testcase contains a string a. a consists only of uppercase letters 'A', 'B' and 'C'. Let n be the length of a. It is guaranteed that n is even and 2 \le n \le 50.OutputFor each testcase print "YES" if there exists such a string b that: b is a regular bracket sequence; if for some i and j (1 \le i, j \le n) a_i=a_j, then b_i=b_j. Otherwise, print "NO".You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).ExampleInput 4 AABBAC CACA BBBBAC ABCA Output YES YES NO NO NoteIn the first testcase one of the possible strings b is "(())()".In the second testcase one of the possible strings b is "()()".
4 AABBAC CACA BBBBAC ABCA
YES YES NO NO
2 seconds
256 megabytes
['bitmasks', 'brute force', 'implementation', '*900']
F. Enchanted Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There exists a matrix a of size n \times m (n rows and m columns), you know only numbers n and m. The rows of the matrix are numbered from 1 to n from top to bottom, and columns of the matrix are numbered from 1 to m from left to right. The cell on the intersection of the x-th row and the y-th column is denoted as (x, y).You are asked to find the number of pairs (r, c) (1 \le r \le n, 1 \le c \le m, r is a divisor of n, c is a divisor of m) such that if we split the matrix into rectangles of size r \times c (of height r rows and of width c columns, each cell belongs to exactly one rectangle), all those rectangles are pairwise equal.You can use queries of the following type: ? h w i_1 j_1 i_2 j_2 (1 \le h \le n, 1 \le w \le m, 1 \le i_1, i_2 \le n, 1 \le j_1, j_2 \le m) — to check if non-overlapping subrectangles of height h rows and of width w columns of matrix a are equal or not. The upper left corner of the first rectangle is (i_1, j_1). The upper left corner of the second rectangle is (i_2, j_2). Subrectangles overlap, if they have at least one mutual cell. If the subrectangles in your query have incorrect coordinates (for example, they go beyond the boundaries of the matrix) or overlap, your solution will be considered incorrect. You can use at most 3 \cdot \left \lfloor{ \log_2{(n+m)} } \right \rfloor queries. All elements of the matrix a are fixed before the start of your program and do not depend on your queries.InputThe first line contains two integers n and m (1 \le n, m \le 1000) — the number of rows and columns, respectively.OutputWhen ready, print a line with an exclamation mark ('!') and then the answer — the number of suitable pairs (r, c). After that your program should terminate.InteractionTo make a query, print a line with the format "? h w i_1 j_1 i_2 j_2 ", where the integers are the height and width and the coordinates of upper left corners of non-overlapping rectangles, about which you want to know if they are equal or not.After each query read a single integer t (t is 0 or 1): if the subrectangles are equal, t=1, otherwise t=0.In case your query is of incorrect format or you asked more than 3 \cdot \left \lfloor{ \log_2{(n+m)} } \right \rfloor queries, you will receive the Wrong Answer verdict.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.It is guaranteed that the matrix a is fixed and won't change during the interaction process.Hacks formatFor hacks use the following format.The first line contains two integers n and m (1 \le n, m \le 1000) — the number of rows and columns in the matrix, respectively.Each of the next n lines contains m integers — the elements of matrix a. All the elements of the matrix must be integers between 1 and n \cdot m, inclusive.ExampleInput 3 4 1 1 1 0Output ? 1 2 1 1 1 3 ? 1 2 2 1 2 3 ? 1 2 3 1 3 3 ? 1 1 1 1 1 2 ! 2NoteIn the example test the matrix a of size 3 \times 4 is equal to: 1 2 1 23 3 3 32 1 2 1
3 4 1 1 1 0
? 1 2 1 1 1 3 ? 1 2 2 1 2 3 ? 1 2 3 1 3 3 ? 1 1 1 1 1 2 ! 2
1 second
256 megabytes
['bitmasks', 'interactive', 'number theory', '*2600']
E. Enormous XORtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers l and r in binary representation. Let g(x, y) be equal to the bitwise XOR of all integers from x to y inclusive (that is x \oplus (x+1) \oplus \dots \oplus (y-1) \oplus y). Let's define f(l, r) as the maximum of all values of g(x, y) satisfying l \le x \le y \le r.Output f(l, r).InputThe first line contains a single integer n (1 \le n \le 10^6) — the length of the binary representation of r.The second line contains the binary representation of l — a string of length n consisting of digits 0 and 1 (0 \le l < 2^n).The third line contains the binary representation of r — a string of length n consisting of digits 0 and 1 (0 \le r < 2^n).It is guaranteed that l \le r. The binary representation of r does not contain any extra leading zeros (if r=0, the binary representation of it consists of a single zero). The binary representation of l is preceded with leading zeros so that its length is equal to n.OutputIn a single line output the value of f(l, r) for the given pair of l and r in binary representation without extra leading zeros.ExamplesInput 7 0010011 1111010 Output 1111111Input 4 1010 1101 Output 1101 NoteIn sample test case l=19, r=122. f(x,y) is maximal and is equal to 127, with x=27, y=100, for example.
7 0010011 1111010
1111111
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'greedy', 'math', 'strings', 'two pointers', '*2600']
D. GCD of an Arraytime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n. You are asked to process q queries of the following format: given integers i and x, multiply a_i by x.After processing each query you need to output the greatest common divisor (GCD) of all elements of the array a.Since the answer can be too large, you are asked to output it modulo 10^9+7.InputThe first line contains two integers — n and q (1 \le n, q \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 2 \cdot 10^5) — the elements of the array a before the changes.The next q lines contain queries in the following format: each line contains two integers i and x (1 \le i \le n, 1 \le x \le 2 \cdot 10^5).OutputPrint q lines: after processing each query output the GCD of all elements modulo 10^9+7 on a separate line.ExampleInput 4 3 1 6 8 12 1 12 2 3 3 3 Output 2 2 6 NoteAfter the first query the array is [12, 6, 8, 12], \operatorname{gcd}(12, 6, 8, 12) = 2.After the second query — [12, 18, 8, 12], \operatorname{gcd}(12, 18, 8, 12) = 2.After the third query — [12, 18, 24, 12], \operatorname{gcd}(12, 18, 24, 12) = 6.Here the \operatorname{gcd} function denotes the greatest common divisor.
4 3 1 6 8 12 1 12 2 3 3 3
2 2 6
2.5 seconds
256 megabytes
['brute force', 'data structures', 'hashing', 'implementation', 'math', 'number theory', 'sortings', 'two pointers', '*2100']
C. K-beautiful Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.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 T (1 \le T \le 10\,000) — the number of test cases.The next 2 \cdot T lines contain the description of test cases. The description of each test case consists of two lines.The first line of the description contains two integers n and k (1 \le k \le n \le 10^5) — the length of string s and number k respectively.The second line contains string s consisting of lowercase English letters.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.ExampleInput 4 4 2 abcd 3 1 abc 4 3 aaaa 9 3 abaabaaaa Output acac abc -1 abaabaaab NoteIn the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.We can show that there is no suitable string in the third test case.In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
4 4 2 abcd 3 1 abc 4 3 aaaa 9 3 abaabaaaa
acac abc -1 abaabaaab
2 seconds
256 megabytes
['binary search', 'brute force', 'constructive algorithms', 'greedy', 'strings', '*2000']
B. Planet Lapitulettitime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).The image of the clocks in the mirror is reflected against a vertical axis. The reflection is not a valid time.The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.You are asked to solve the problem for several test cases.InputThe first line contains a single integer T (1 \le T \le 100) — the number of test cases.The next 2 \cdot T lines contain the description of test cases. The description of each test case consists of two lines.The first line of a test case contains two integers h, m (1 \le h, m \le 100).The second line contains the start time s in the described format HH:MM.OutputFor each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct.ExampleInput 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 NoteIn the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct.
5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04
12:21 00:00 52:28 00:00 00:00
2 seconds
256 megabytes
['brute force', 'implementation', '*1300']
A. Anti-knapsacktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k.A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.InputThe first line contains the number of test cases T (1 \le T \le 100).Each of the next T lines contains two integers n and k (1 \le k \le n \le 1000) — the description of test cases.OutputFor each test case output two lines. In the first line output a single integer m — the number of chosen integers.In the second line output m distinct integers from 1 to n — the chosen numbers.If there are multiple answers, print any. You can print the numbers in any order.ExampleInput 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
3 3 2 5 3 1 1
2 3 1 3 4 5 2 0
1 second
256 megabytes
['constructive algorithms', 'greedy', '*800']
E. Almost Fault-Tolerant Databasetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are storing an integer array of length m in a database. To maintain internal integrity and protect data, the database stores n copies of this array.Unfortunately, the recent incident may have altered the stored information in every copy in the database.It's believed, that the incident altered at most two elements in every copy. You need to recover the original array based on the current state of the database.In case there are multiple ways to restore the array, report any. If there is no array that differs from every copy in no more than two positions, report that as well.InputThe first line contains integers n and m (2 \le n; 1 \le m; n \cdot m \le 250\,000) — the number of copies and the size of the array.Each of the following n lines describes one of the currently stored copies in the database, it consists of m integers s_{i, 1}, s_{i, 2}, \dots, s_{i, m} (1 \le s_{i, j} \le 10^9).OutputIf there is an array consistent with all given copies, print "Yes" and then the array itself. The array must have length m and contain integers between 1 and 10^9 only.Otherwise, print "No".If there are multiple possible arrays, print any of them.ExamplesInput 3 4 1 10 10 100 1 1 1 100 10 100 1 100 Output Yes 1 10 1 100 Input 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 2 2 1 1 1 1 2 2 1 1 1 1 2 2 1 1 1 1 2 2 1 1 1 1 2 2 1 1 1 1 2 2 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 Output Yes 1 1 1 1 1 1 1 Input 2 5 2 2 1 1 1 1 1 2 2 2 Output No NoteIn the first example, the array [1, 10, 1, 100] differs from first and second copies in just one position, and from the third copy in two positions.In the second example, array [1, 1, 1, 1, 1, 1, 1] is the same as the first copy and differs from all other copies in at most two positions.In the third example, there is no array differing in at most two positions from every database's copy.
3 4 1 10 10 100 1 1 1 100 10 100 1 100
Yes 1 10 1 100
2 seconds
512 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'greedy', 'implementation', '*2500']
D. Genius's Gambittime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given three integers a, b, k.Find two binary integers x and y (x \ge y) such that both x and y consist of a zeroes and b ones; x - y (also written in binary form) has exactly k ones. You are not allowed to use leading zeros for x and y. InputThe only line contains three integers a, b, and k (0 \leq a; 1 \leq b; 0 \leq k \leq a + b \leq 2 \cdot 10^5) — the number of zeroes, ones, and the number of ones in the result.OutputIf it's possible to find two suitable integers, print "Yes" followed by x and y in base-2.Otherwise print "No".If there are multiple possible answers, print any of them.ExamplesInput 4 2 3 Output Yes 101000 100001 Input 3 2 1 Output Yes 10100 10010 Input 3 2 5 Output No NoteIn the first example, x = 101000_2 = 2^5 + 2^3 = 40_{10}, y = 100001_2 = 2^5 + 2^0 = 33_{10}, 40_{10} - 33_{10} = 7_{10} = 2^2 + 2^1 + 2^0 = 111_{2}. Hence x-y has 3 ones in base-2.In the second example, x = 10100_2 = 2^4 + 2^2 = 20_{10}, y = 10010_2 = 2^4 + 2^1 = 18, x - y = 20 - 18 = 2_{10} = 10_{2}. This is precisely one 1.In the third example, one may show, that it's impossible to find an answer.
4 2 3
Yes 101000 100001
2 seconds
512 megabytes
['bitmasks', 'constructive algorithms', 'greedy', 'math', '*1900']
C. Maximum widthtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: s of length n and t of length m.A sequence p_1, p_2, \ldots, p_m, where 1 \leq p_1 < p_2 < \ldots < p_m \leq n, is called beautiful, if s_{p_i} = t_i for all i from 1 to m. The width of a sequence is defined as \max\limits_{1 \le i < m} \left(p_{i + 1} - p_i\right).Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings s and t there is at least one beautiful sequence.InputThe first input line contains two integers n and m (2 \leq m \leq n \leq 2 \cdot 10^5) — the lengths of the strings s and t.The following line contains a single string s of length n, consisting of lowercase letters of the Latin alphabet.The last line contains a single string t of length m, consisting of lowercase letters of the Latin alphabet.It is guaranteed that there is at least one beautiful sequence for the given strings.OutputOutput one integer — the maximum width of a beautiful sequence.ExamplesInput 5 3 abbbc abc Output 3 Input 5 2 aaaaa aa Output 4 Input 5 5 abcdf abcdf Output 1 Input 2 2 ab ab Output 1 NoteIn the first example there are two beautiful sequences of width 3: they are \{1, 2, 5\} and \{1, 4, 5\}.In the second example the beautiful sequence with the maximum width is \{1, 5\}.In the third example there is exactly one beautiful sequence — it is \{1, 2, 3, 4, 5\}.In the fourth example there is exactly one beautiful sequence — it is \{1, 2\}.
5 3 abbbc abc
3
2 seconds
512 megabytes
['binary search', 'data structures', 'dp', 'greedy', 'two pointers', '*1500']
B. Card Decktime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a deck of n cards, and you'd like to reorder it to a new one.Each card has a value between 1 and n equal to p_i. All p_i are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. p_1 stands for the bottom card, p_n is the top card. In each step you pick some integer k > 0, take the top k cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as \sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}.Given the original deck, output the deck with maximum possible order you can make using the operation above.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains the single integer n (1 \le n \le 10^5) — the size of deck you have.The second line contains n integers p_1, p_2,\dots, p_n (1 \le p_i \le n; p_i \neq p_j if i \neq j) — values of card in the deck from bottom to top.It's guaranteed that the sum of n over all test cases doesn't exceed 10^5.OutputFor each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top.If there are multiple answers, print any of them.ExampleInput 4 4 1 2 3 4 5 1 5 2 4 3 6 4 2 5 3 6 1 1 1 Output 4 3 2 1 5 2 4 3 1 6 1 5 3 4 2 1 NoteIn the first test case, one of the optimal strategies is the next one: take 1 card from the top of p and move it to p': p becomes [1, 2, 3], p' becomes [4]; take 1 card from the top of p: p becomes [1, 2], p' becomes [4, 3]; take 1 card from the top of p: p becomes [1], p' becomes [4, 3, 2]; take 1 card from the top of p: p becomes empty, p' becomes [4, 3, 2, 1]. In result, p' has order equal to 4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1 = 256 + 48 + 8 + 1 = 313.In the second test case, one of the optimal strategies is: take 4 cards from the top of p and move it to p': p becomes [1], p' becomes [5, 2, 4, 3]; take 1 card from the top of p and move it to p': p becomes empty, p' becomes [5, 2, 4, 3, 1]; In result, p' has order equal to 5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1 = 3125 + 250 + 100 + 15 + 1 = 3491.In the third test case, one of the optimal strategies is: take 2 cards from the top of p and move it to p': p becomes [4, 2, 5, 3], p' becomes [6, 1]; take 2 cards from the top of p and move it to p': p becomes [4, 2], p' becomes [6, 1, 5, 3]; take 2 cards from the top of p and move it to p': p becomes empty, p' becomes [6, 1, 5, 3, 4, 2]. In result, p' has order equal to 6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2 = 46656 + 1296 + 1080 + 108 + 24 + 2 = 49166.
4 4 1 2 3 4 5 1 5 2 4 3 6 4 2 5 3 6 1 1 1
4 3 2 1 5 2 4 3 1 6 1 5 3 4 2 1
1 second
512 megabytes
['data structures', 'greedy', 'math', '*1100']
A. Three swimmerstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThree swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.It takes the first swimmer exactly a minutes to swim across the entire pool and come back, exactly b minutes for the second swimmer and c minutes for the third. Hence, the first swimmer will be on the left side of the pool after 0, a, 2a, 3a, ... minutes after the start time, the second one will be at 0, b, 2b, 3b, ... minutes, and the third one will be on the left side of the pool after 0, c, 2c, 3c, ... minutes.You came to the left side of the pool exactly p minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.InputThe first line of the input contains a single integer t (1 \leq t \leq 1000) — the number of test cases. Next t lines contains test case descriptions, one per line.Each line contains four integers p, a, b and c (1 \leq p, a, b, c \leq 10^{18}), time in minutes after the start, when you came to the pool and times in minutes it take the swimmers to cross the entire pool and come back.OutputFor each test case, output one integer — how long you have to wait (in minutes) before one of the swimmers arrives at the left side of the pool.ExampleInput 4 9 5 4 8 2 6 10 9 10 2 5 10 10 9 9 9 Output 1 4 0 8 NoteIn the first test case, the first swimmer is on the left side in 0, 5, 10, 15, \ldots minutes after the start time, the second swimmer is on the left side in 0, 4, 8, 12, \ldots minutes after the start time, and the third swimmer is on the left side in 0, 8, 16, 24, \ldots minutes after the start time. You arrived at the pool in 9 minutes after the start time and in a minute you will meet the first swimmer on the left side.In the second test case, the first swimmer is on the left side in 0, 6, 12, 18, \ldots minutes after the start time, the second swimmer is on the left side in 0, 10, 20, 30, \ldots minutes after the start time, and the third swimmer is on the left side in 0, 9, 18, 27, \ldots minutes after the start time. You arrived at the pool 2 minutes after the start time and after 4 minutes meet the first swimmer on the left side.In the third test case, you came to the pool 10 minutes after the start time. At the same time, all three swimmers are on the left side. A rare stroke of luck!In the fourth test case, all swimmers are located on the left side in 0, 9, 18, 27, \ldots minutes after the start time. You arrived at the pool 10 minutes after the start time and after 8 minutes meet all three swimmers on the left side.
4 9 5 4 8 2 6 10 9 10 2 5 10 10 9 9 9
1 4 0 8
1 second
512 megabytes
['math', '*800']
I. Ruler Of The Zootime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter realizing that Zookeeper is just a duck, the animals have overthrown Zookeeper. They now have to decide a new ruler among themselves through a fighting tournament of the following format:Initially, animal 0 is king, while everyone else queues up with animal 1 at the front of the queue and animal n-1 at the back. The animal at the front of the queue will challenge the king to a fight, and the animal with greater strength will win the fight. The winner will become king, while the loser joins the back of the queue.An animal who wins 3 times consecutively will be crowned ruler for the whole zoo. The strength of each animal depends on how many consecutive fights he won. Animal i has strength A_i with 0 consecutive win, B_i with 1 consecutive win, and C_i with 2 consecutive wins. Initially, everyone has 0 consecutive win.For all animals, A_i > B_i and C_i > B_i. Also, the values of A_i, B_i, C_i are distinct (all 3n values are pairwise different). In other words, an animal who is not a king has strength A_i. A king usually has a strength of B_i or C_i. The exception is on the first turn, the first king (animal 0) has strength A_i.Who is the new ruler, and after how many fights? Or will it end up that animals fight forever with no one ending up as ruler?InputThe first line contains one integer n (4 \leq n \leq 6000) — number of the animals. i-th of the next n lines contains 3 integers A_i, B_i and C_i (0 \leq A_i, B_i, C_i \leq 10^9).It is guaranteed that A_i > B_i and C_i > B_i, and that all values of A_i, B_i and C_i are distinct.OutputOutput two integers in a single line. The first is the index of the animal that will become ruler, and the second is the number of fights passed until some animal becomes the ruler.If the animals will fight for infinitely long, output -1 -1 instead.ExamplesInput 4 5 1 2 10 8 11 9 0 3 7 4 6 Output -1 -1Input 5 11 7 12 8 6 14 2 1 10 13 0 9 5 3 4 Output 1 7 NoteThe following describes the sequence of events for the second sample. Note that in fight 1, the king (animal 0) has strength A_0. The tournament ends at fight 7 as animal 1 wins fight 5, 6 and 7.
4 5 1 2 10 8 11 9 0 3 7 4 6
-1 -1
3 seconds
256 megabytes
['brute force', 'data structures', '*3500']
H. Yuezheng Ling and Dynamic Treetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYuezheng Ling gives Luo Tianyi a tree which has n nodes, rooted at 1. Luo Tianyi will tell you that the parent of the i-th node is a_i (1 \leq a_i<i for 2 \le i \le n), and she will ask you to perform q queries of 2 types: She'll give you three integers l, r and x (2 \le l \le r \le n, 1 \le x \le 10^5). You need to replace a_i with \max(a_i-x,1) for all i with l \leq i \leq r. She'll give you two integers u, v (1 \le u, v \le n). You need to find the LCA of nodes u and v (their lowest common ancestor).InputThe first line contains two integers n and q (2\leq n,q \leq 10^5) — the number of nodes and the number of queries, respectively.The second line contains n-1 integers a_2, a_3,\dots, a_n (1 \le a_i < i), where a_i is the parent of the node i.Next q lines contain queries. For each query, the first integer of each line is t (t = 1 or 2) — the type of the query. If t = 1, this represents the query of the first type. Then, three integers will follow: l, r, x (2 \le l \le r \le n, 1 \le x \le 10^5), meaning that you have to replace a_i with \max(a_i-x,1) for all i with l \leq i \leq r. If t = 2, this represents the query of the second type. Then, two integers will follow: u and v (1 \le u, v \le n), and you have to find the LCA of u and v. It's guaranteed that there is at least one query of the second type.OutputFor each query of the second type output answer on a new line.ExampleInput 6 4 1 2 3 3 4 2 3 4 1 2 3 1 2 5 6 2 2 3 Output 3 3 1 NoteThe tree in example is shown below. After the query of the first type, the tree changes and is looking as shown below.
6 4 1 2 3 3 4 2 3 4 1 2 3 1 2 5 6 2 2 3
3 3 1
1.5 seconds
256 megabytes
['data structures', 'trees', '*3400']
G. Switch and Fliptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n coins labeled from 1 to n. Initially, coin c_i is on position i and is facing upwards ((c_1, c_2, \dots, c_n) is a permutation of numbers from 1 to n). You can do some operations on these coins. In one operation, you can do the following:Choose 2 distinct indices i and j.Then, swap the coins on positions i and j.Then, flip both coins on positions i and j. (If they are initially faced up, they will be faced down after the operation and vice versa)Construct a sequence of at most n+1 operations such that after performing all these operations the coin i will be on position i at the end, facing up.Note that you do not need to minimize the number of operations.InputThe first line contains an integer n (3 \leq n \leq 2 \cdot 10^5) — the number of coins.The second line contains n integers c_1,c_2,\dots,c_n (1 \le c_i \le n, c_i \neq c_j for i\neq j).OutputIn the first line, output an integer q (0 \leq q \leq n+1) — the number of operations you used.In the following q lines, output two integers i and j (1 \leq i, j \leq n, i \ne j) — the positions you chose for the current operation.ExamplesInput 3 2 1 3 Output 3 1 3 3 2 3 1 Input 5 1 2 3 4 5 Output 0 NoteLet coin i facing upwards be denoted as i and coin i facing downwards be denoted as -i.The series of moves performed in the first sample changes the coins as such: [~~~2,~~~1,~~~3] [-3,~~~1,-2] [-3,~~~2,-1] [~~~1,~~~2,~~~3] In the second sample, the coins are already in their correct positions so there is no need to swap.
3 2 1 3
3 1 3 3 2 3 1
1 second
256 megabytes
['constructive algorithms', 'graphs', 'math', '*2800']
F. Magnetstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Kochiya Sanae is playing with magnets. Realizing that some of those magnets are demagnetized, she is curious to find them out.There are n magnets, which can be of the following 3 types: N S - — these magnets are demagnetized. Note that you don't know the types of these magnets beforehand.You have a machine which can measure the force between the magnets, and you can use it at most n+\lfloor \log_2n\rfloor times.You can put some magnets to the left part of the machine and some to the right part of the machine, and launch the machine. Obviously, you can put one magnet to at most one side (you don't have to put all magnets). You can put the same magnet in different queries.Then the machine will tell the force these magnets produce. Formally, let n_1,s_1 be the number of N and S magnets correspondently on the left and n_2,s_2 — on the right. Then the force between them would be n_1n_2+s_1s_2-n_1s_2-n_2s_1. Please note that the force is a signed value.However, when the absolute value of the force is strictly larger than n, the machine will crash into pieces.You need to find all magnets of type - (all demagnetized ones), without breaking the machine.Note that the interactor is not adaptive. The types of the magnets are fixed before the start of the interaction and do not change with queries.It is guaranteed that there are at least 2 magnets whose type is not -, and at least 1 magnet of type -.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.InteractionFor each test case you should start by reading an integer n (3 \leq n \leq 2000) — the number of the magnets. It is guaranteed that the total sum of all n over all test cases doesn't exceed 2000.After that you can put some magnets into the machine and make a query from the statement.You have to print each query in three lines: In the first line print "? l r" (without quotes) where l and r (1 \leq l,r < n, l+r \leq n) respectively denote the number of the magnets you put to left and right. In the second line print l integers a_1, \dots, a_l (1 \leq a_i \leq n, a_i \neq a_j if i \neq j) — the indices of the magnets you put to left. In the third line print r integers b_1, \dots, b_r (1 \leq b_i \leq n, b_i \neq b_j if i \neq j) — the indices of the magnets you put to right. The same magnet can't be put to both sides in the same query. Formally, you should guarantee that a_i \neq b_j for any i and j. However, you may leave some magnets unused.After printing a query do not forget to output end of line and flush the output. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.After this, you should read an integer F — the force these magnets produce.Note that if your query is invalid(either the query limit exceeds, the machine crashes or the arguments are invalid), the interactor will terminate immediately. In this case terminate your program to receive verdict Wrong Answer instead of arbitrary verdicts.If you are confident about your answer, use the following format to report it: "! k A", where k is the number of magnets you found, and A is an array consisting of k different integers from 1 to n denoting the indices of the magnets of type - that you found. You may print elements of A in arbitrary order. After that, if this is the last test case, you have to terminate your program; otherwise you should immediately continue to deal with the next test case.Note that the interactor is not adaptive. The types of the magnets are fixed before the start of interaction and do not change with queries.HacksTo hack a solution, use the following format:The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases in your hack.Then follow the descriptions of the t test cases, each printed in two lines: The first line contains a single integer n (3 \leq n \leq 2000) — the number of magnets. The second line contains a string S of length n consisting of only N, S and -, denoting the magnets' types. Each of your test case should guarantee that there are at least 2 magnets whose type is not -, and at least 1 magnet of type -. Meanwhile, the total sum of n in all test cases should not exceed 2000.ExampleInput 1 4 0 1 0 0 Output ? 1 1 3 4 ? 1 2 1 2 3 ? 1 1 1 4 ? 1 1 1 3 ! 2 3 4 NoteThe empty lines in the sample are just for you to better understand the interaction process. You're not required to print them.In the sample, the types of the magnets are NN--.At first, you put the third magnet on the left and the fourth one on the right. Both of them have type -, thus no force is produced.Then you put the first magnet on the left and the second and third one on the right. The third magnet has type -, while the other two magnets are of type N, so the force produced is 1.In the following two queries, the force is 0 since there is only a magnet with property - on the right.Then we can determine that the magnets of type - are the third and the fourth one, so we should print ! 2 3 4 and exit.
1 4 0 1 0 0
? 1 1 3 4 ? 1 2 1 2 3 ? 1 1 1 4 ? 1 1 1 3 ! 2 3 4
1 second
256 megabytes
['binary search', 'constructive algorithms', 'interactive', '*2700']
E. Fib-treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet F_k denote the k-th term of Fibonacci sequence, defined as below: F_0 = F_1 = 1 for any integer n \geq 0, F_{n+2} = F_{n+1} + F_nYou are given a tree with n vertices. Recall that a tree is a connected undirected graph without cycles.We call a tree a Fib-tree, if its number of vertices equals F_k for some k, and at least one of the following conditions holds: The tree consists of only 1 vertex; You can divide it into two Fib-trees by removing some edge of the tree. Determine whether the given tree is a Fib-tree or not.InputThe first line of the input contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of vertices in the tree.Then n-1 lines follow, each of which contains two integers u and v (1\leq u,v \leq n, u \neq v), representing an edge between vertices u and v. It's guaranteed that given edges form a tree.OutputPrint "YES" if the given tree is a Fib-tree, or "NO" otherwise.You can print your answer in any case. For example, if the answer is "YES", then the output "Yes" or "yeS" will also be considered as correct answer.ExamplesInput 3 1 2 2 3 Output YES Input 5 1 2 1 3 1 4 1 5 Output NO Input 5 1 3 1 2 4 5 3 4 Output YES NoteIn the first sample, we can cut the edge (1, 2), and the tree will be split into 2 trees of sizes 1 and 2 correspondently. Any tree of size 2 is a Fib-tree, as it can be split into 2 trees of size 1.In the second sample, no matter what edge we cut, the tree will be split into 2 trees of sizes 1 and 4. As 4 isn't F_k for any k, it's not Fib-tree.In the third sample, here is one possible order of cutting the edges so that all the trees in the process are Fib-trees: (1, 3), (1, 2), (4, 5), (3, 4).
3 1 2 2 3
YES
1 second
256 megabytes
['brute force', 'dfs and similar', 'divide and conquer', 'number theory', 'trees', '*2400']
D. Zookeeper and The Infinite Zootime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a new attraction in Singapore Zoo: The Infinite Zoo.The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled 1,2,3,\ldots. There is a directed edge from vertex u to vertex u+v if and only if u\&v=v, where \& denotes the bitwise AND operation. There are no other edges in the graph.Zookeeper has q queries. In the i-th query she will ask you if she can travel from vertex u_i to vertex v_i by going through directed edges.InputThe first line contains an integer q (1 \leq q \leq 10^5) — the number of queries.The i-th of the next q lines will contain two integers u_i, v_i (1 \leq u_i, v_i < 2^{30}) — a query made by Zookeeper.OutputFor the i-th of the q queries, output "YES" in a single line if Zookeeper can travel from vertex u_i to vertex v_i. Otherwise, output "NO".You can print your answer in any case. For example, if the answer is "YES", then the output "Yes" or "yeS" will also be considered as correct answer.ExampleInput 5 1 4 3 6 1 6 6 2 5 5 Output YES YES NO NO YES NoteThe subgraph on vertices 1,2,3,4,5,6 is shown below.
5 1 4 3 6 1 6 6 2 5 5
YES YES NO NO YES
3 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'greedy', 'math', '*1800']
C. Pekora and Trampolinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a trampoline park with n trampolines in a line. The i-th of which has strength S_i.Pekora can jump on trampolines in multiple passes. She starts the pass by jumping on any trampoline of her choice. If at the moment Pekora jumps on trampoline i, the trampoline will launch her to position i + S_i, and S_i will become equal to \max(S_i-1,1). In other words, S_i will decrease by 1, except of the case S_i=1, when S_i will remain equal to 1. If there is no trampoline in position i + S_i, then this pass is over. Otherwise, Pekora will continue the pass by jumping from the trampoline at position i + S_i by the same rule as above.Pekora can't stop jumping during the pass until she lands at the position larger than n (in which there is no trampoline). Poor Pekora!Pekora is a naughty rabbit and wants to ruin the trampoline park by reducing all S_i to 1. What is the minimum number of passes she needs to reduce all S_i to 1?InputThe first line contains a single integer t (1 \le t \le 500) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 5000) — the number of trampolines.The second line of each test case contains n integers S_1, S_2, \dots, S_n (1 \le S_i \le 10^9), where S_i is the strength of the i-th trampoline.It's guaranteed that the sum of n over all test cases doesn't exceed 5000.OutputFor each test case, output a single integer — the minimum number of passes Pekora needs to do to reduce all S_i to 1.ExampleInput 3 7 1 4 2 2 2 2 2 2 2 3 5 1 1 1 1 1 Output 4 3 0 NoteFor the first test case, here is an optimal series of passes Pekora can take. (The bolded numbers are the positions that Pekora jumps into during these passes.) [1,4,\textbf{2},2,\textbf{2},2,\textbf{2}] [1,\textbf{4},1,2,1,\textbf{2},1] [1,\textbf{3},1,2,\textbf{1},\textbf{1},\textbf{1}] [1,\textbf{2},1,\textbf{2},1,\textbf{1},\textbf{1}] For the second test case, the optimal series of passes is show below. [\textbf{2},3] [1,\textbf{3}] [1,\textbf{2}] For the third test case, all S_i are already equal to 1.
3 7 1 4 2 2 2 2 2 2 2 3 5 1 1 1 1 1
4 3 0
2 seconds
256 megabytes
['brute force', 'data structures', 'dp', 'greedy', 'implementation', '*1700']
B. Minimal Costtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a graph of n rows and 10^6 + 2 columns, where rows are numbered from 1 to n and columns from 0 to 10^6 + 1: Let's denote the node in the row i and column j by (i, j).Initially for each i the i-th row has exactly one obstacle — at node (i, a_i). You want to move some obstacles so that you can reach node (n, 10^6+1) from node (1, 0) by moving through edges of this graph (you can't pass through obstacles). Moving one obstacle to an adjacent by edge free node costs u or v coins, as below: If there is an obstacle in the node (i, j), you can use u coins to move it to (i-1, j) or (i+1, j), if such node exists and if there is no obstacle in that node currently. If there is an obstacle in the node (i, j), you can use v coins to move it to (i, j-1) or (i, j+1), if such node exists and if there is no obstacle in that node currently. Note that you can't move obstacles outside the grid. For example, you can't move an obstacle from (1,1) to (0,1). Refer to the picture above for a better understanding. Now you need to calculate the minimal number of coins you need to spend to be able to reach node (n, 10^6+1) from node (1, 0) by moving through edges of this graph without passing through obstacles.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 three integers n, u and v (2 \le n \le 100, 1 \le u, v \le 10^9) — the number of rows in the graph and the numbers of coins needed to move vertically and horizontally respectively.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6) — where a_i represents that the obstacle in the i-th row is in node (i, a_i).It's guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^4.OutputFor each test case, output a single integer — the minimal number of coins you need to spend to be able to reach node (n, 10^6+1) from node (1, 0) by moving through edges of this graph without passing through obstacles.It can be shown that under the constraints of the problem there is always a way to make such a trip possible.ExampleInput 3 2 3 4 2 2 2 3 4 3 2 2 4 3 3 2 Output 7 3 3 NoteIn the first sample, two obstacles are at (1, 2) and (2,2). You can move the obstacle on (2, 2) to (2, 3), then to (1, 3). The total cost is u+v = 7 coins. In the second sample, two obstacles are at (1, 3) and (2,2). You can move the obstacle on (1, 3) to (2, 3). The cost is u = 3 coins.
3 2 3 4 2 2 2 3 4 3 2 2 4 3 3 2
7 3 3
2 seconds
256 megabytes
['brute force', 'math', '*1200']
A. K-th Largest Valuetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: 1 x : Assign to a_x the value 1 - a_x. 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1.InputThe first line contains two integers n and q (1 \le n, q \le 10^5) — the length of the given array and the number of queries.The second line contains n integers a_1, a_2, a_3, \dots, a_n (0 \le a_i \le 1) — elements of the initial array.Each of the following q lines contains two integers. The first integer is t (1 \le t \le 2) — the type of query. If t = 1 the second integer is x (1 \le x \le n) — the position of the modified number. You have to assign to a_x the value 1 - a_x. If t = 2 the second integer is k (1 \le k \le n) — you need to print the k-th largest value of the array.It's guaranteed that there will be at least one query of the second type (satisfying t = 2).OutputFor each query of the second type, print a single integer — the answer to the query.ExampleInput 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 NoteInitially a = [1, 1, 0, 1, 0].The first operation is printing the third largest value, which is 1.The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0].The third operation is printing the third largest value, it is 0.The fourth operation is printing the first largest value, it is 1.The last operation is printing the fifth largest value, it is 0.
5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5
1 0 1 0
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*800']
G. Old Floppy Drive time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm: the drive takes one positive number x as input and puts a pointer to the first element of the a array; after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one; as soon as the sum is at least x, the drive will shut down. Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows: the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1. the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5. the answer to the third query is 2, the amount is 1+(-3)+4=2. InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of each test case consists of two positive integers n, m (1 \le n, m \le 2 \cdot 10^5) — the number of numbers on the disk and the number of asked questions.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 third line of each test case contains m positive integers x_1, x_2, \ldots, x_m (1 \le x \le 10^9).It is guaranteed that the sums of n and m over all test cases do not exceed 2 \cdot 10^5. OutputPrint m numbers on a separate line for each test case. The i-th number is: -1 if the drive will run infinitely; the number of seconds the drive will run, otherwise. ExampleInput 3 3 3 1 -3 4 1 5 2 2 2 -2 0 1 2 2 2 0 1 1 2 Output 0 6 2 -1 -1 1 3
3 3 3 1 -3 4 1 5 2 2 2 -2 0 1 2 2 2 0 1 1 2
0 6 2 -1 -1 1 3
2 seconds
256 megabytes
['binary search', 'data structures', 'math', '*1900']
F. Equalize the Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp was gifted an array a of length n. Polycarp considers an array beautiful if there exists a number C, such that each number in the array occurs either zero or C times. Polycarp wants to remove some elements from the array a to make it beautiful.For example, if n=6 and a = [1, 3, 2, 1, 4, 2], then the following options are possible to make the array a array beautiful: Polycarp removes elements at positions 2 and 5, array a becomes equal to [1, 2, 1, 2]; Polycarp removes elements at positions 1 and 6, array a becomes equal to [3, 2, 1, 4]; Polycarp removes elements at positions 1, 2 and 6, array a becomes equal to [2, 1, 4]; Help Polycarp determine the minimum number of elements to remove from the array a to make it beautiful.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of each test case consists of one integer n (1 \le n \le 2 \cdot 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 (1 \le a_i \le 10^9) — 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 one integer — the minimum number of elements that Polycarp has to remove from the array a to make it beautiful.ExampleInput 3 6 1 3 2 1 4 2 4 100 100 4 100 8 1 2 3 3 3 2 6 6 Output 2 1 2
3 6 1 3 2 1 4 2 4 100 100 4 100 8 1 2 3 3 3 2 6 6
2 1 2
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'math', 'sortings', '*1500']
E. Accidental Victorytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA championship is held in Berland, in which n players participate. The player with the number i has a_i (a_i \ge 1) tokens.The championship consists of n-1 games, which are played according to the following rules: in each game, two random players with non-zero tokens are selected; the player with more tokens is considered the winner of the game (in case of a tie, the winner is chosen randomly); the winning player takes all of the loser's tokens; The last player with non-zero tokens is the winner of the championship.All random decisions that are made during the championship are made equally probable and independently.For example, if n=4, a = [1, 2, 4, 3], then one of the options for the game (there could be other options) is: during the first game, the first and fourth players were selected. The fourth player has more tokens, so he takes the first player's tokens. Now a = [0, 2, 4, 4]; during the second game, the fourth and third players were selected. They have the same number of tokens, but in a random way, the third player is the winner. Now a = [0, 2, 8, 0]; during the third game, the second and third players were selected. The third player has more tokens, so he takes the second player's tokens. Now a = [0, 0, 10, 0]; the third player is declared the winner of the championship. Championship winners will receive personalized prizes. Therefore, the judges want to know in advance which players have a chance of winning, i.e have a non-zero probability of winning the championship. You have been asked to find all such players. InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of each test case consists of one positive integer n (1 \le n \le 2 \cdot 10^5) — the number of players in the championship.The second line of each test case contains n positive integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the number of tokens the players have.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5. OutputFor each test case, print the number of players who have a nonzero probability of winning the championship. On the next line print the numbers of these players in increasing order. Players are numbered starting from one in the order in which they appear in the input. ExampleInput 2 4 1 2 4 3 5 1 1 1 1 1 Output 3 2 3 4 5 1 2 3 4 5
2 4 1 2 4 3 5 1 1 1 1 1
3 2 3 4 5 1 2 3 4 5
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', '*1400']
D. Permutation Transformationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation — is a sequence of length n integers from 1 to n, in which all the numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] — permutations, and [2, 3, 2], [4, 3, 1], [0] — no.Polycarp was recently gifted a permutation a[1 \dots n] of length n. Polycarp likes trees more than permutations, so he wants to transform permutation a into a rooted binary tree. He transforms an array of different integers into a tree as follows: the maximum element of the array becomes the root of the tree; all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child; all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child. For example, if he builds a tree by permutation a=[3, 5, 2, 1, 4], then the root will be the element a_2=5, and the left subtree will be the tree that will be built for the subarray a[1 \dots 1] = [3], and the right one — for the subarray a[3 \dots 5] = [2, 1, 4]. As a result, the following tree will be built: The tree corresponding to the permutation a=[3, 5, 2, 1, 4]. Another example: let the permutation be a=[1, 3, 2, 7, 5, 6, 4]. In this case, the tree looks like this: The tree corresponding to the permutation a=[1, 3, 2, 7, 5, 6, 4]. Let us denote by d_v the depth of the vertex a_v, that is, the number of edges on the path from the root to the vertex numbered a_v. Note that the root depth is zero. Given the permutation a, for each vertex, find the value of d_v.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.The first line of each test case contains an integer n (1 \le n \le 100) — the length of the permutation.This is followed by n numbers a_1, a_2, \ldots, a_n — permutation a.OutputFor each test case, output n values — d_1, d_2, \ldots, d_n.ExampleInput 3 5 3 5 2 1 4 1 1 4 4 3 1 2 Output 1 0 2 3 1 0 0 1 3 2
3 5 3 5 2 1 4 1 1 4 4 3 1 2
1 0 2 3 1 0 0 1 3 2
2 seconds
256 megabytes
['dfs and similar', 'divide and conquer', 'implementation', '*1200']
C. Sum of Cubestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer x. Check whether the number x is representable as the sum of the cubes of two positive integers.Formally, you need to check if there are two integers a and b (1 \le a, b) such that a^3+b^3=x.For example, if x = 35, then the numbers a=2 and b=3 are suitable (2^3+3^3=8+27=35). If x=4, then no pair of numbers a and b is suitable.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.Each test case contains one integer x (1 \le x \le 10^{12}).Please note, that the input for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language.OutputFor each test case, output on a separate line: "YES" if x is representable as the sum of the cubes of two positive integers. "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).ExampleInput 7 1 2 4 34 35 16 703657519796 Output NO YES NO NO YES YES YES NoteThe number 1 is not representable as the sum of two cubes.The number 2 is represented as 1^3+1^3.The number 4 is not representable as the sum of two cubes.The number 34 is not representable as the sum of two cubes.The number 35 is represented as 2^3+3^3.The number 16 is represented as 2^3+2^3.The number 703657519796 is represented as 5779^3+7993^3.
7 1 2 4 34 35 16 703657519796
NO YES NO NO YES YES YES
2 seconds
256 megabytes
['binary search', 'brute force', 'brute force', 'math', '*1100']
B. Balanced Remainderstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a number n (divisible by 3) and an array a[1 \dots n]. In one move, you can increase any of the array elements by one. Formally, you choose the index i (1 \le i \le n) and replace a_i with a_i + 1. You can choose the same index i multiple times for different moves.Let's denote by c_0, c_1 and c_2 the number of numbers from the array a that have remainders 0, 1 and 2 when divided by the number 3, respectively. Let's say that the array a has balanced remainders if c_0, c_1 and c_2 are equal.For example, if n = 6 and a = [0, 2, 5, 5, 4, 8], then the following sequence of moves is possible: initially c_0 = 1, c_1 = 1 and c_2 = 4, these values are not equal to each other. Let's increase a_3, now the array a = [0, 2, 6, 5, 4, 8]; c_0 = 2, c_1 = 1 and c_2 = 3, these values are not equal. Let's increase a_6, now the array a = [0, 2, 6, 5, 4, 9]; c_0 = 3, c_1 = 1 and c_2 = 2, these values are not equal. Let's increase a_1, now the array a = [1, 2, 6, 5, 4, 9]; c_0 = 2, c_1 = 2 and c_2 = 2, these values are equal to each other, which means that the array a has balanced remainders. Find the minimum number of moves needed to make the array a have balanced remainders.InputThe first line contains one integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains one integer n (3 \le n \le 3 \cdot 10^4) — the length of the array a. It is guaranteed that the number n is divisible by 3.The next line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 100).It is guaranteed that the sum of n over all test cases does not exceed 150\,000.OutputFor each test case, output one integer — the minimum number of moves that must be made for the a array to make it have balanced remainders.ExampleInput 4 6 0 2 5 5 4 8 6 2 0 2 1 0 0 9 7 1 3 4 2 10 3 9 6 6 0 1 2 3 4 5 Output 3 1 3 0 NoteThe first test case is explained in the statements.In the second test case, you need to make one move for i=2.The third test case you need to make three moves: the first move: i=9; the second move: i=9; the third move: i=2. In the fourth test case, the values c_0, c_1 and c_2 initially equal to each other, so the array a already has balanced remainders.
4 6 0 2 5 5 4 8 6 2 0 2 1 0 0 9 7 1 3 4 2 10 3 9 6 6 0 1 2 3 4 5
3 1 3 0
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'math', '*1000']
A. Dense Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any i (1 \le i \le n-1), this condition must be satisfied: \frac{\max(a[i], a[i+1])}{\min(a[i], a[i+1])} \le 2For example, the arrays [1, 2, 3, 4, 3], [1, 1, 1] and [5, 10] are dense. And the arrays [5, 11], [1, 4, 2], [6, 6, 1] are not dense.You are given an array a of n integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added.For example, if a=[4,2,10,1], then the answer is 5, and the array itself after inserting elements into it may look like this: a=[4,2,\underline{\textbf{3}},\underline{\textbf{5}},10,\underline{\textbf{6}},\underline{\textbf{4}},\underline{\textbf{2}},1] (there are other ways to build such a).InputThe first line contains one integer t (1 \le t \le 1000). Then t test cases follow.The first line of each test case contains one integer n (2 \le n \le 50) — the length of the array a.The next line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 50).OutputFor each test case, output one integer — the minimum number of numbers that must be added to the array to make it dense.ExampleInput 6 4 4 2 10 1 2 1 3 2 6 1 3 1 4 2 5 1 2 3 4 3 12 4 31 25 50 30 20 34 46 42 16 15 16 Output 5 1 2 1 0 3 NoteThe first test case is explained in the statements.In the second test case, you can insert one element, a=[1,\underline{\textbf{2}},3].In the third test case, you can insert two elements, a=[6,\underline{\textbf{4}},\underline{\textbf{2}},1].In the fourth test case, you can insert one element, a=[1,\underline{\textbf{2}},4,2].In the fifth test case, the array a is already dense.
6 4 4 2 10 1 2 1 3 2 6 1 3 1 4 2 5 1 2 3 4 3 12 4 31 25 50 30 20 34 46 42 16 15 16
5 1 2 1 0 3
2 seconds
256 megabytes
['greedy', 'math', '*800']
J. Flower Shoptime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend is running a flower shop. In order to be prepared for the next holidays (when, as usual, sales skyrocket) she asked you to write her a special program that will help to analyze the stocks she has.There are n different types of flowers she can order and each flower of the type i costs w_i. The last holidays were a great success, she sold all flowers she had, so right now all her stocks are empty.From this point, she starts routine operations of ordering and selling flowers, while trying to analyze what she has at hand. All of this can be represented as m queries of three types: "1 i c" — she bought c flowers of type i; "2 i c" — she disposed of c flowers of type i; "3 l r k" — how many variants of bouquets she can make using only flowers of types l, l + 1, \dots, r with the total cost no more than k. For simplicity, you can think that a bouquet is a multiset of flowers, and two bouquets are different if they are different as multisets. The cost of a bouquet is the sum of all flowers it has. Help your friend and write the program that can process all these queries.InputThe first line contains two integers n and m (1 \le n \le 1000; 1 \le m \le 1000) — the number of flower types and the number of queries.The second line contains n integers w_1, w_2, \dots, w_n (1 \le w_i \le 1000) — the cost of one flower of each type.The next m lines contains queries — one per line. Each query has one of three types: 1 i c (1 \le i \le n; 1 \le c \le 5000); 2 i c (1 \le i \le n; 1 \le c \le 5000). It's guaranteed that there are at least c flowers of type i at this moment; 3 l r k (1 \le l \le r \le n; 1 \le k \le 5000) It's guaranteed that the total cost of all flowers in stock after each query doesn't exceed 5000.OutputFor each query of the third type, print how many variants of bouquets she can make using only flowers of types l, l + 1, \dots, r with the total cost no more than k. Since the answer may be too large, print it modulo 998\,244\,353.ExampleInput 5 12 1 2 3 2 1 1 1 5 1 2 3 1 3 1 3 1 5 10 3 4 5 100 1 4 4 1 5 1 3 2 5 7 3 1 1 3 3 1 5 100 2 1 5 3 1 5 100 Output 40 0 28 3 479 79
5 12 1 2 3 2 1 1 1 5 1 2 3 1 3 1 3 1 5 10 3 4 5 100 1 4 4 1 5 1 3 2 5 7 3 1 1 3 3 1 5 100 2 1 5 3 1 5 100
40 0 28 3 479 79
5 seconds
256 megabytes
['*special problem', 'data structures', 'fft', 'math', '*3100']
I. Demonic Invasiontime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDalaran is a flying city of magic. It consists of n floating islands connected by m bridges (each bridge can be traversed in both directions). Every island is reachable from every other along these bridges. It would be a shame if some magic experiment went horribly wrong and this magnificent city got destroyed, right?Well, just guess what happened. A portal to demons' realm was opened at the island 1. This is the start of day 1 of the catastrophe, and all k mages have gathered at the island 1 (they were trying to close the portal, but found out that it was impossible). At the start of day 2, a gigantic horde of demons will emerge from the portal, capture the island 1 and kill every mage staying at that island. During each day i, if the island v was captured by demons by the start of the day, the horde of demons will travel across all bridges connected directly to v, capture every island they reach, and kill every mage they meet along the way.Each bridge contains exactly one magic stone. Each mage at the start of the day can do one of the following actions: Spend one day travelling along one of the bridges connected to the island where the mage currently is. When passing through a bridge, the mage can pick up the magic stone from it (if there is any; each magic stone can be picked up by at most one mage). If the bridge is passed by the demons during the same day, or by the start of the next day, the island where the mage goes is already captured by the demonic horde (even if they arrive there at the same moment), the mage is killed. Perform a teleportation ritual to get to safety outside Dalaran. This ritual consumes two magic stones (and cannot be performed if the mage has less than two stones). Each magic stone decays in 2 days, so if is picked up in the middle of day i, it decays in the middle of day i + 2. Decayed stones cannot be used in teleportation ritual.Calculate the maximum number of mages that can get to safety.InputThe first line contains three integers n, m and k (2 \le n \le 10^5; n - 1 \le m \le 10^5; 1 \le k \le 10^5) — the number of islands, the number of bridges and the number of mages.Then m lines follow, the i-th line contains two integers x_i and y_i (1 \le x_i, y_i \le n; x_i \ne y_i) denoting a bridge between the islands x_i and y_i.Each pair of islands has at most one bridge connecting them. Every island is reachable from every other island along the bridges.OutputPrint one integer — the maximum number of mages that can get to safety.ExamplesInput 4 4 1 1 2 2 3 3 4 4 1 Output 1 Input 4 4 4 1 2 2 3 3 4 4 1 Output 2 Input 3 2 10 1 2 2 3 Output 1 Input 4 5 1 1 2 2 3 3 4 4 1 3 1 Output 0
4 4 1 1 2 2 3 3 4 4 1
1
8 seconds
512 megabytes
['*special problem', 'flows', '*3100']
H. Build From Suffixestime limit per test10 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an integer n and a sequence a of n-1 integers, each element is either 0 or 1.You are asked to build a string of length n such that: each letter is one of "abcd"; if a_i=1, then the i-th suffix of the string is lexicographically smaller than the (i+1)-th suffix; if a_i=0, then the i-th suffix of the string is lexicographically greater than the (i+1)-th suffix. You will be asked q queries of form: i (1 \le i \le n - 1) — flip the value of a_i (if a_i=0, then set a_i to 1, and vice versa). After each query print the number of different strings that satisfy the given constraints modulo 998\,244\,353.InputThe first line contains two integers n and q (2 \le n \le 10^5; 1 \le q \le 10^5) — the length of the string and the number of queries.The second line contains n-1 integers a_1, a_2, \dots, a_{n-1} (a_i \in \{0, 1\}) — the constraints on suffixes of the string.Each of the next q lines contains a query: an integer i (1 \le i \le n - 1) — flip the value of a_i (if a_i=0, then set a_i to 1, and vice versa).OutputAfter each query print the number of different strings that satisfy the given constraints modulo 998\,244\,353.ExamplesInput 2 2 0 1 1 Output 6 10 Input 3 4 0 0 1 2 1 2 Output 20 10 14 20 Input 10 10 0 0 0 1 1 1 0 1 0 4 1 8 4 2 9 5 6 6 8 Output 1815 3201 2710 2776 2290 1644 2668 1271 2668 2436 NoteThe i-th suffix of a string is a continuous substring that starts from the i-th position and ends in the last position.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. Two strings a and b of length n differ if there exists a position i such that a_i \neq b_i.
2 2 0 1 1
6 10
10 seconds
512 megabytes
['*special problem', 'combinatorics', 'data structures', '*2800']
G. Painting Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers, each integer is from 1 to n, all of them are pairwise distinct. You have to paint them red and blue (each integer should have exactly one color).The cost of painting is the number of pairs (x, y) such that y \bmod x = 0, y is red and x is blue.For each k \in [1, n], calculate the maximum cost of painting if exactly k integers should have a red color.InputThe first line contains one integer n (2 \le n \le 10^5).OutputFor each k \in [1,n] print one integer — the maximum cost of painting, if exactly k integers should be red.ExamplesInput 6 Output 3 5 6 6 5 0 Input 2 Output 1 0 Input 11 Output 3 6 9 11 12 13 14 14 13 10 0
6
3 5 6 6 5 0
2 seconds
256 megabytes
['*special problem', 'data structures', 'greedy', 'number theory', '*2500']
F. Dogecointime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, cryptocurrencies have become increasingly popular. Ann decided that it was about time she started mining the Dogecoin cryptocurrency. Ann's computer is not very powerful, so Ann mines exactly 1 Dogecoin per day. On the Internet, there are forecasts of the cost of 1 dogecoin for the next n days. Every day, Ann can sell any amount of dogecoin that she currently has. Note that if Ann mined Dogecoin on the i-th day, then she can sell it on the same day.Ann has not yet decided when to start mining. She has prepared q possible plans and for each of them wants to know the maximum profit that she can get. Each of the plans is described by two numbers l and r — the first and last days of mining. Note that Ann should not have any Dogecoin left after the r-th day.InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5).The second line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le 10^6), where c_i is the cost of Dogecoin on the i-th day.The third line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of Ann's plans.The following q lines contains two integers l and r (1 \le l \le r \le n) — the first and last days of mining. OutputFor each Ann's plan print one integer — the maximum profit that she can get using this plan.ExampleInput 5 4 1 2 3 2 4 1 5 2 4 3 5 5 5 Output 15 9 8 2
5 4 1 2 3 2 4 1 5 2 4 3 5 5 5
15 9 8 2
2 seconds
256 megabytes
['*special problem', '*special problem', 'binary search', 'data structures', '*2300']
E. Palindromic Doublestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA subsequence is a sequence that can be obtained from another sequence by removing some elements without changing the order of the remaining elements.A palindromic sequence is a sequence that is equal to the reverse of itself.You are given a sequence of n integers a_1, a_2, \dots, a_n. Any integer value appears in a no more than twice.What is the length of the longest palindromic subsequence of sequence a?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then the descriptions of t testcases follow.The first line of each testcase contains a single integer n (1 \le n \le 250\,000) — the number of elements in the sequence.The second line of each testcase contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n).Any integer value appears in a no more than twice. The sum of n over all testcases doesn't exceed 250\,000.OutputFor each testcase print a single integer — the length of the longest palindromic subsequence of sequence a.ExampleInput 5 6 2 1 3 1 5 2 6 1 3 3 4 4 1 1 1 2 1 1 7 4 4 2 5 7 2 3 Output 5 4 1 2 3 NoteHere are the longest palindromic subsequences for the example testcases: 2 1 3 1 5 2 1 3 3 4 4 1 or 1 3 3 4 4 1 1 1 1 4 4 2 5 7 2 3 or 4 4 2 5 7 2 3
5 6 2 1 3 1 5 2 6 1 3 3 4 4 1 1 1 2 1 1 7 4 4 2 5 7 2 3
5 4 1 2 3
2 seconds
256 megabytes
['*special problem', 'data structures', 'dp', '*2200']
D. Problemsolving Marathontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has decided to do a problemsolving marathon. He wants to solve s problems in n days. Let a_i be the number of problems he solves during the i-th day. He wants to find a distribution of problems into days such that: a_i is an integer value for all i from 1 to n; a_i \ge 1 for all i from 1 to n; a_{i + 1} \ge a_i for all i from 1 to n-1; a_{i + 1} \le 2 \cdot a_i for all i from 1 to n-1; a_n is maximized. Note that a_1 can be arbitrarily large.What is the largest value of a_n Polycarp can obtain?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then the descriptions of t testcases follow.The only line of each testcase contains two integers n and s (1 \le n \le s \le 10^{18}) — the number of days and the number of problems Polycarp wants to solve.It's guaranteed that the distribution always exists within the given constraints.OutputFor each testcase print a single integer — the maximum value of a_n.ExampleInput 3 1 15 3 9 2 6 Output 15 4 4 NoteIn the first testcase there is only one distribution: [15].In the second testcase the distribution that maximizes a_n is: [2, 3, 4].In the third testcase the distribution that maximizes a_n is: [2, 4]. [3, 3] is a valid distribution but a_n=3 which is smaller than 4. [1, 5] is not a valid distribution because 5 > 2 \cdot 1.
3 1 15 3 9 2 6
15 4 4
2 seconds
256 megabytes
['*special problem', 'binary search', 'greedy', '*1900']
C. Two Policementime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a street that can be represented as an array of length n.There are two policemen patrolling a street: the first one is standing at the point x of the street and the second one is standing at the point y of the street.During one minute, both policemen can decide what to do (independently): move left (if the current position is greater than 1), move right (if the current position is less than n), or do nothing.The street is considered clear if each point of the street is visited by at least one policeman.Your task is to find the minimum number of minutes the policemen need to visit each point of the street (again, each point should be visited by at least one of them).You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains three integers n, x and y (2 \le n \le 10^6; 1 \le x, y \le n; x \ne y) — the length of the street, the position of the first policeman and the position of the second policeman, respectively.It is guaranteed that the sum of n does not exceed 10^6 (\sum n \le 10^6).OutputFor each test case, print one integer — the minimum number of minutes the policemen need to visit each point of the street.ExampleInput 6 4 1 2 7 7 1 10 2 6 8 5 2 2 1 2 20 4 14 Output 2 3 5 4 0 12
6 4 1 2 7 7 1 10 2 6 8 5 2 2 1 2 20 4 14
2 3 5 4 0 12
2 seconds
256 megabytes
['*special problem', 'binary search', 'brute force', 'math', '*1900']
B. RBS Deletiontime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example: bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"); bracket sequences ")(", "(" and ")" are not. You are given a string s, which is an RBS. You can apply any number of operations to this string. Each operation can have one of the following types: choose some non-empty prefix of s and remove it from s, so s is still an RBS. For example, we can apply this operation as follows: "(())()(())()()" \to "()()" (the first 10 characters are removed); choose some contiguous non-empty substring of s and remove it from s, so s is still an RBS. For example, we can apply this operation as follows: "(())()(())()()" \to "(())()()()" (the characters from the 7-th to the 10-th are removed). The operation 2 can be applied at most k times. Calculate the maximum number of operations you can apply until s becomes empty.InputThe first line contains one integer t (1 \le t \le 10^5) — the number of test cases.Each test case is described by two lines. The first line contains two integers n and k (2 \le n \le 2 \cdot 10^5; 1 \le k \le n; n is even) — the length of s and the maximum number of operations of type 2 you can apply.The second line contains a string s of n characters '(' and ')'. This string is an RBS.The sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the maximum number of operations you can apply.ExampleInput 3 12 2 (()())((())) 6 3 ()()() 8 1 (((()))) Output 4 3 2
3 12 2 (()())((())) 6 3 ()()() 8 1 (((())))
4 3 2
3 seconds
512 megabytes
['*special problem', 'greedy', '*1800']
A. From Zero To Ytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive (greater than zero) integers x and y. There is a variable k initially set to 0.You can perform the following two types of operations: add 1 to k (i. e. assign k := k + 1); add x \cdot 10^{p} to k for some non-negative p (i. e. assign k := k + x \cdot 10^{p} for some p \ge 0). Find the minimum number of operations described above to set the value of k to y.InputThe first line contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases.Each test case consists of one line containing two integer x and y (1 \le x, y \le 10^9).OutputFor each test case, print one integer — the minimum number of operations to set the value of k to y.ExampleInput 3 2 7 3 42 25 1337 Output 4 5 20 NoteIn the first test case you can use the following sequence of operations: add 1; add 2 \cdot 10^0 = 2; add 2 \cdot 10^0 = 2; add 2 \cdot 10^0 = 2. 1 + 2 + 2 + 2 = 7.In the second test case you can use the following sequence of operations: add 3 \cdot 10^1 = 30; add 3 \cdot 10^0 = 3; add 3 \cdot 10^0 = 3; add 3 \cdot 10^0 = 3; add 3 \cdot 10^0 = 3. 30 + 3 + 3 + 3 + 3 = 42.
3 2 7 3 42 25 1337
4 5 20
2 seconds
256 megabytes
['*special problem', 'math', '*900']
G. String Countingtime limit per test10 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou have c_1 letters 'a', c_2 letters 'b', ..., c_{26} letters 'z'. You want to build a beautiful string of length n from them (obviously, you cannot use the i-th letter more than c_i times). Each c_i is greater than \frac{n}{3}.A string is called beautiful if there are no palindromic contiguous substrings of odd length greater than 1 in it. For example, the string "abacaba" is not beautiful, it has several palindromic substrings of odd length greater than 1 (for example, "aca"). Another example: the string "abcaa" is beautiful.Calculate the number of different strings you can build, and print the answer modulo 998244353.InputThe first line contains one integer n (3 \le n \le 400).The second line contains 26 integers c_1, c_2, ..., c_{26} (\frac{n}{3} < c_i \le n).OutputPrint one integer — the number of strings you can build, taken modulo 998244353.ExamplesInput 4 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Output 422500 Input 3 2 2 2 2 2 2 3 3 3 2 2 2 2 2 2 3 3 3 2 2 3 2 2 3 2 2 Output 16900 Input 400 348 322 247 158 209 134 151 267 268 176 214 379 372 291 388 135 147 304 169 149 193 351 380 368 181 340 Output 287489790
4 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
422500
10 seconds
1024 megabytes
['combinatorics', 'dp', 'fft', 'math', '*2700']
F. Onestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive (greater than zero) integer n.You have to represent n as the sum of integers (possibly negative) consisting only of ones (digits '1'). For example, 24 = 11 + 11 + 1 + 1 and 102 = 111 - 11 + 1 + 1. Among all possible representations, you have to find the one that uses the minimum number of ones in total.InputThe single line contains one integer n (1 \le n < 10^{50}).OutputPrint one integer x — the minimum number of ones, such that there exist a representation of n as the sum of integers (possibly negative) that uses x ones in total.ExamplesInput 24 Output 6 Input 102 Output 7
24
6
3 seconds
256 megabytes
['dp', 'greedy', 'shortest paths', '*2900']
E. Cheap Dinnertime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIvan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.There are n_1 different types of first courses Ivan can buy (the i-th of them costs a_i coins), n_2 different types of second courses (the i-th of them costs b_i coins), n_3 different types of drinks (the i-th of them costs c_i coins) and n_4 different types of desserts (the i-th of them costs d_i coins).Some dishes don't go well with each other. There are m_1 pairs of first courses and second courses that don't go well with each other, m_2 pairs of second courses and drinks, and m_3 pairs of drinks and desserts that don't go well with each other.Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!InputThe first line contains four integers n_1, n_2, n_3 and n_4 (1 \le n_i \le 150000) — the number of types of first courses, second courses, drinks and desserts, respectively.Then four lines follow. The first line contains n_1 integers a_1, a_2, \dots, a_{n_1} (1 \le a_i \le 10^8), where a_i is the cost of the i-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way (1 \le b_i, c_i, d_i \le 10^8).The next line contains one integer m_1 (0 \le m_1 \le 200000) — the number of pairs of first and second courses that don't go well with each other. Each of the next m_1 lines contains two integers x_i and y_i (1 \le x_i \le n_1; 1 \le y_i \le n_2) denoting that the first course number x_i doesn't go well with the second course number y_i. All these pairs are different.The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other (0 \le m_2, m_3 \le 200000).OutputIf it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print -1. Otherwise, print one integer — the minimum total cost of the dinner.ExamplesInput 4 3 2 1 1 2 3 4 5 6 7 8 9 10 2 1 2 1 1 2 3 1 3 2 1 1 1 Output 26 Input 1 1 1 1 1 1 1 1 1 1 1 0 0 Output -1 NoteThe best option in the first example is to take the first course 2, the second course 1, the drink 2 and the dessert 1.In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner.
4 3 2 1 1 2 3 4 5 6 7 8 9 10 2 1 2 1 1 2 3 1 3 2 1 1 1
26
4 seconds
512 megabytes
['brute force', 'data structures', 'graphs', 'greedy', 'implementation', 'sortings', 'two pointers', '*2000']
D. Pythagorean Triplestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA Pythagorean triple is a triple of integer numbers (a, b, c) such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to a, b and c, respectively. An example of the Pythagorean triple is (3, 4, 5).Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: c = a^2 - b.Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple (3, 4, 5): 5 = 3^2 - 4, so, according to Vasya's formula, it is a Pythagorean triple.When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers (a, b, c) with 1 \le a \le b \le c \le n such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of one line containing one integer n (1 \le n \le 10^9).OutputFor each test case, print one integer — the number of triples of integers (a, b, c) with 1 \le a \le b \le c \le n such that they are Pythagorean according both to the real definition and to the formula Vasya came up with.ExampleInput 3 3 6 9 Output 0 1 1 NoteThe only Pythagorean triple satisfying c = a^2 - b with 1 \le a \le b \le c \le 9 is (3, 4, 5); that's why the answer for n = 3 is 0, and the answer for n = 6 (and for n = 9) is 1.
3 3 6 9
0 1 1
2 seconds
256 megabytes
['binary search', 'brute force', 'math', 'number theory', '*1500']
C. Minimum Tiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA big football championship will occur soon! n teams will compete in it, and each pair of teams will play exactly one game against each other.There are two possible outcomes of a game: the game may result in a tie, then both teams get 1 point; one team might win in a game, then the winning team gets 3 points and the losing team gets 0 points. The score of a team is the number of points it gained during all games that it played.You are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well.Your task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.Then the test cases follow. Each test case is described by one line containing one integer n (2 \le n \le 100) — the number of teams.OutputFor each test case, print \frac{n(n - 1)}{2} integers describing the results of the games in the following order: the first integer should correspond to the match between team 1 and team 2, the second — between team 1 and team 3, then 1 and 4, ..., 1 and n, 2 and 3, 2 and 4, ..., 2 and n, and so on, until the game between the team n - 1 and the team n.The integer corresponding to the game between the team x and the team y should be 1 if x wins, -1 if y wins, or 0 if the game results in a tie.All teams should get the same score, and the number of ties should be the minimum possible. If there are multiple optimal answers, print any of them. It can be shown that there always exists a way to make all teams have the same score.ExampleInput 2 2 3 Output 0 1 -1 1 NoteIn the first test case of the example, both teams get 1 point since the game between them is a tie.In the second test case of the example, team 1 defeats team 2 (team 1 gets 3 points), team 1 loses to team 3 (team 3 gets 3 points), and team 2 wins against team 3 (team 2 gets 3 points).
2 2 3
0 1 -1 1
1 second
256 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'graphs', 'greedy', 'implementation', 'math', '*1500']
B. Cat Cycletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are living with two cats: A and B. There are n napping spots where both cats usually sleep.Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically: Cat A changes its napping place in order: n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots In other words, at the first hour it's on the spot n and then goes in decreasing order cyclically; Cat B changes its napping place in order: 1, 2, 3, \dots, n - 1, n, 1, 2, \dots In other words, at the first hour it's on the spot 1 and then goes in increasing order cyclically. The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot x then the A takes this place and B moves to the next place in its order (if x < n then to x + 1, but if x = n then to 1). Cat B follows his order, so it won't return to the skipped spot x after A frees it, but will move to the spot x + 2 and so on.Calculate, where cat B will be at hour k?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first and only line of each test case contains two integers n and k (2 \le n \le 10^9; 1 \le k \le 10^9) — the number of spots and hour k.OutputFor each test case, print one integer — the index of the spot where cat B will sleep at hour k.ExampleInput 7 2 1 2 2 3 1 3 2 3 3 5 5 69 1337 Output 1 2 1 3 2 2 65 NoteIn the first and second test cases n = 2, so: at the 1-st hour, A is on spot 2 and B is on 1; at the 2-nd hour, A moves to spot 1 and B — to 2. If n = 3 then: at the 1-st hour, A is on spot 3 and B is on 1; at the 2-nd hour, A moves to spot 2; B'd like to move from 1 to 2, but this spot is occupied, so it moves to 3; at the 3-rd hour, A moves to spot 1; B also would like to move from 3 to 1, but this spot is occupied, so it moves to 2. In the sixth test case: A's spots at each hour are [5, 4, 3, 2, 1]; B's spots at each hour are [1, 2, 4, 5, 2].
7 2 1 2 2 3 1 3 2 3 3 5 5 69 1337
1 2 1 3 2 2 65
1 second
256 megabytes
['math', 'number theory', '*1200']
A. Arenatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn heroes fight against each other in the Arena. Initially, the i-th hero has level a_i.Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute).When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by 1.The winner of the tournament is the first hero that wins in at least 100^{500} fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament.Calculate the number of possible winners among n heroes.InputThe first line contains one integer t (1 \le t \le 500) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (2 \le n \le 100) — the number of heroes. The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100), where a_i is the initial level of the i-th hero.OutputFor each test case, print one integer — the number of possible winners among the given n heroes.ExampleInput 3 3 3 2 2 2 5 5 4 1 3 3 7 Output 1 0 3 NoteIn the first test case of the example, the only possible winner is the first hero.In the second test case of the example, each fight between the heroes results in nobody winning it, so the tournament lasts forever and there is no winner.
3 3 3 2 2 2 5 5 4 1 3 3 7
1 0 3
1 second
256 megabytes
['implementation', 'sortings', '*800']
F. Pairs of Pathstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices, and m simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs (i, j) (1 \leq i < j \leq m) such that path_i and path_j have exactly one vertex in common. InputFirst line contains a single integer n (1 \leq n \leq 3 \cdot 10^5).Next n - 1 lines describe the tree. Each line contains two integers u and v (1 \leq u, v \leq n) describing an edge between vertices u and v.Next line contains a single integer m (1 \leq m \leq 3 \cdot 10^5).Next m lines describe paths. Each line describes a path by it's two endpoints u and v (1 \leq u, v \leq n). The given path is all the vertices on the shortest path from u to v (including u and v).OutputOutput a single integer — the number of pairs of paths that intersect at exactly one vertex.ExamplesInput 5 1 2 1 3 1 4 3 5 4 2 3 2 4 3 4 3 5 Output 2 Input 1 3 1 1 1 1 1 1 Output 3 Input 5 1 2 1 3 1 4 3 5 6 2 3 2 4 3 4 3 5 1 1 1 2 Output 7 NoteThe tree in the first example and paths look like this. Pairs (1,4) and (3,4) intersect at one vertex.In the second example all three paths contain the same single vertex, so all pairs (1, 2), (1, 3) and (2, 3) intersect at one vertex.The third example is the same as the first example with two additional paths. Pairs (1,4), (1,5), (2,5), (3,4), (3,5), (3,6) and (5,6) intersect at one vertex.
5 1 2 1 3 1 4 3 5 4 2 3 2 4 3 4 3 5
2
6 seconds
512 megabytes
['combinatorics', 'data structures', 'dfs and similar', 'dp', 'trees', '*2600']
E. Paired Paymenttime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n cities and m bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter w. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city a to city b and then from city b to city c) and you will have to pay (w_{ab} + w_{bc})^2 money to go through those roads. Find out whether it is possible to travel from city 1 to every other city t and what's the minimum amount of money you need to get from 1 to t.InputFirst line contains two integers n, m (2 \leq n \leq 10^5, 1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)).Next m lines each contain three integers v_i, u_i, w_i (1 \leq v_i, u_i \leq n, 1 \leq w_i \leq 50, u_i \neq v_i). It's guaranteed that there are no multiple edges, i.e. for any edge (u_i, v_i) there are no other edges (u_i, v_i) or (v_i, u_i).OutputFor every city t print one integer. If there is no correct path between 1 and t output -1. Otherwise print out the minimum amount of money needed to travel from 1 to t.ExamplesInput 5 6 1 2 3 2 3 4 3 4 5 4 5 6 1 5 1 2 4 2 Output 0 98 49 25 114 Input 3 2 1 2 1 2 3 2 Output 0 -1 9 NoteThe graph in the first example looks like this.In the second example the path from 1 to 3 goes through 2, so the resulting payment is (1 + 2)^2 = 9.
5 6 1 2 3 2 3 4 3 4 5 4 5 6 1 5 1 2 4 2
0 98 49 25 114
4 seconds
512 megabytes
['binary search', 'brute force', 'constructive algorithms', 'dp', 'flows', 'graphs', 'shortest paths', '*2200']
D. Max Mediantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median.A median in an array of length n is an element which occupies position number \lfloor \frac{n + 1}{2} \rfloor after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1.Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},\ldots,a_r for some 1 \leq l \leq r \leq n, its length is r - l + 1.InputThe first line contains two integers n and k (1 \leq k \leq n \leq 2 \cdot 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n).OutputOutput one integer m — the maximum median you can get.ExamplesInput 5 3 1 2 3 2 1 Output 2Input 4 2 1 2 3 4 Output 3NoteIn the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too.In the second example median([3..4]) = 3.
5 3 1 2 3 2 1
2
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', '*2100']
C2. Guessing the Greatest (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array a of n different numbers. In one query you can ask the position of the second maximum element in a subsegment a[l..r]. Find the position of the maximum element in the array in no more than 20 queries.A subsegment a[l..r] is all the elements a_l, a_{l + 1}, ..., a_r. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.InputThe first line contains a single integer n (2 \leq n \leq 10^5) — the number of elements in the array.InteractionYou can ask queries by printing "? l r" (1 \leq l < r \leq n). The answer is the index of the second maximum of all elements a_l, a_{l + 1}, ..., a_r. Array a is fixed beforehand and can't be changed in time of interaction.You can output the answer by printing "! p", where p is the index of the maximum element in the array.You can ask no more than 20 queries. Printing the answer doesn't count as a query.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages HacksTo make a hack, use the following test format.In the first line output a single integer n (2 \leq n \leq 10^5). In the second line output a permutation of n integers 1 to n. The position of n in the permutation is the position of the maximumExampleInput 5 3 4 Output ? 1 5 ? 4 5 ! 1NoteIn the sample suppose a is [5, 1, 4, 2, 3]. So after asking the [1..5] subsegment 4 is second to max value, and it's position is 3. After asking the [4..5] subsegment 2 is second to max value and it's position in the whole array is 4.Note that there are other arrays a that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
5 3 4
? 1 5 ? 4 5 ! 1
1 second
256 megabytes
['binary search', 'interactive', '*1900']
C1. Guessing the Greatest (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array a of n different numbers. In one query you can ask the position of the second maximum element in a subsegment a[l..r]. Find the position of the maximum element in the array in no more than 40 queries.A subsegment a[l..r] is all the elements a_l, a_{l + 1}, ..., a_r. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.InputThe first line contains a single integer n (2 \leq n \leq 10^5) — the number of elements in the array.InteractionYou can ask queries by printing "? l r" (1 \leq l < r \leq n). The answer is the index of the second maximum of all elements a_l, a_{l + 1}, \ldots, a_r. Array a is fixed beforehand and can't be changed in time of interaction.You can output the answer by printing "! p", where p is the index of the maximum element in the array.You can ask no more than 40 queries. Printing the answer doesn't count as a query.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages HacksTo make a hack, use the following test format.In the first line output a single integer n (2 \leq n \leq 10^5). In the second line output a permutation of n integers 1 to n. The position of n in the permutation is the position of the maximumExampleInput 5 3 4 Output ? 1 5 ? 4 5 ! 1NoteIn the sample suppose a is [5, 1, 4, 2, 3]. So after asking the [1..5] subsegment 4 is second to max value, and it's position is 3. After asking the [4..5] subsegment 2 is second to max value and it's position in the whole array is 4.Note that there are other arrays a that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
5 3 4
? 1 5 ? 4 5 ! 1
1 second
256 megabytes
['binary search', 'interactive', '*1600']
B. Eastern Exhibitiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x. InputFirst line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 \leq x_i, y_i \leq 10^9).It's guaranteed that the sum of all n does not exceed 1000.OutputFor each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house.ExampleInput 6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0 Output 1 4 4 4 3 1 NoteHere are the images for the example test cases. Blue dots stand for the houses, green — possible positions for the exhibition.First test case.Second test case. Third test case. Fourth test case. Fifth test case. Sixth test case. Here both houses are located at (0, 0).
6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0
1 4 4 4 3 1
1 second
256 megabytes
['binary search', 'geometry', 'shortest paths', 'sortings', '*1500']
A. Shifting Stackstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n stacks of blocks. The i-th stack contains h_i blocks and it's height is the number of blocks in it. In one move you can take a block from the i-th stack (if there is at least one block) and put it to the i + 1-th stack. Can you make the sequence of heights strictly increasing?Note that the number of stacks always remains n: stacks don't disappear when they have 0 blocks.InputFirst 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 a single integer n (1 \leq n \leq 100). The second line of each test case contains n integers h_i (0 \leq h_i \leq 10^9) — starting heights of the stacks.It's guaranteed that the sum of all n does not exceed 10^4.OutputFor each test case output YES if you can make the sequence of heights strictly increasing and NO otherwise.You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).ExampleInput 6 2 1 2 2 1 0 3 4 4 4 2 0 0 3 0 1 0 4 1000000000 1000000000 1000000000 1000000000 Output YES YES YES NO NO YES NoteIn the first test case there is no need to make any moves, the sequence of heights is already increasing.In the second test case we need to move one block from the first stack to the second. Then the heights become 0 1.In the third test case we could move one block from the first stack to the second and then from the second to the third, which would make the heights 3 4 5.In the fourth test case we can't make a move, but the sequence is not increasing, so the answer is NO.In the fifth test case we can only make one move (from the second to the third stack), which would make the heights 0 0 1. Both 0 1 0 and 0 0 1 are not increasing sequences, so the answer is NO.
6 2 1 2 2 1 0 3 4 4 4 2 0 0 3 0 1 0 4 1000000000 1000000000 1000000000 1000000000
YES YES YES NO NO YES
1 second
256 megabytes
['greedy', 'implementation', '*900']
F. Copy or Prefix Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers b_1, b_2, \ldots, b_n.An array a_1, a_2, \ldots, a_n of integers is hybrid if for each i (1 \leq i \leq n) at least one of these conditions is true: b_i = a_i, or b_i = \sum_{j=1}^{i} a_j. Find the number of hybrid arrays a_1, a_2, \ldots, a_n. As the result can be very large, you should print the answer modulo 10^9 + 7.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 b_1, b_2, \ldots, b_n (-10^9 \le b_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 integer: the number of hybrid arrays a_1, a_2, \ldots, a_n modulo 10^9 + 7.ExampleInput 4 3 1 -1 1 4 1 2 3 4 10 2 -1 1 -2 2 3 -5 0 2 -1 4 0 0 0 1 Output 3 8 223 1 NoteIn the first test case, the hybrid arrays are [1, -2, 1], [1, -2, 2], [1, -1, 1].In the second test case, the hybrid arrays are [1, 1, 1, 1], [1, 1, 1, 4], [1, 1, 3, -1], [1, 1, 3, 4], [1, 2, 0, 1], [1, 2, 0, 4], [1, 2, 3, -2], [1, 2, 3, 4].In the fourth test case, the only hybrid array is [0, 0, 0, 1].
4 3 1 -1 1 4 1 2 3 4 10 2 -1 1 -2 2 3 -5 0 2 -1 4 0 0 0 1
3 8 223 1
2 seconds
256 megabytes
['combinatorics', 'data structures', 'dp', 'sortings', '*2400']
E. Move and Swaptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n - 1 integers a_2, \dots, a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s.Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: Move the red coin to any child of r. Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root.After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves?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 \leq n \leq 2 \cdot 10^5) — the number of vertices in the tree.The second line of each test case contains n-1 integers v_2, v_3, \dots, v_n (1 \leq v_i \leq n, v_i \neq i)  — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree.The third line of each test case contains n-1 integers a_2, \dots, a_n (1 \leq a_i \leq 10^9) — the numbers written on the vertices.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 integer: the maximum number of points you can gain after d moves.ExampleInput 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 NoteIn the first test case, an optimal solution is to: move 1: r = 4, b = 2; no swap; move 2: r = 7, b = 6; swap (after it r = 6, b = 7); move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. In the second test case, an optimal solution is to: move 1: r = 2, b = 2; no swap; move 2: r = 3, b = 4; no swap; move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45.
4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40
14 45 163 123
2 seconds
256 megabytes
['dfs and similar', 'dp', 'greedy', 'trees', '*2500']
D. Multiples and Power Differencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix a consisting of positive integers. It has n rows and m columns.Construct a matrix b consisting of positive integers. It should have the same size as a, and the following conditions should be met: 1 \le b_{i,j} \le 10^6; b_{i,j} is a multiple of a_{i,j}; the absolute value of the difference between numbers in any adjacent pair of cells (two cells that share the same side) in b is equal to k^4 for some integer k \ge 1 (k is not necessarily the same for all pairs, it is own for each pair). We can show that the answer always exists.InputThe first line contains two integers n and m (2 \le n,m \le 500).Each of the following n lines contains m integers. The j-th integer in the i-th line is a_{i,j} (1 \le a_{i,j} \le 16).OutputThe output should contain n lines each containing m integers. The j-th integer in the i-th line should be b_{i,j}.ExamplesInput 2 2 1 2 2 3 Output 1 2 2 3 Input 2 3 16 16 16 16 16 16 Output 16 32 48 32 48 64 Input 2 2 3 11 12 8 Output 327 583 408 664 NoteIn the first example, the matrix a can be used as the matrix b, because the absolute value of the difference between numbers in any adjacent pair of cells is 1 = 1^4.In the third example: 327 is a multiple of 3, 583 is a multiple of 11, 408 is a multiple of 12, 664 is a multiple of 8; |408 - 327| = 3^4, |583 - 327| = 4^4, |664 - 408| = 4^4, |664 - 583| = 3^4.
2 2 1 2 2 3
1 2 2 3
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'math', 'number theory', '*2200']
C. Floor and Modtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA pair of positive integers (a,b) is called special if \lfloor \frac{a}{b} \rfloor = a \bmod b. Here, \lfloor \frac{a}{b} \rfloor is the result of the integer division between a and b, while a \bmod b is its remainder.You are given two integers x and y. Find the number of special pairs (a,b) such that 1\leq a \leq x and 1 \leq b \leq y.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.The only line of the description of each test case contains two integers x, y (1 \le x,y \le 10^9).OutputFor each test case print the answer on a single line.ExampleInput 9 3 4 2 100 4 3 50 3 12 4 69 420 12345 6789 123456 789 12345678 9 Output 1 0 2 3 5 141 53384 160909 36 NoteIn the first test case, the only special pair is (3, 2).In the second test case, there are no special pairs.In the third test case, there are two special pairs: (3, 2) and (4, 3).
9 3 4 2 100 4 3 50 3 12 4 69 420 12345 6789 123456 789 12345678 9
1 0 2 3 5 141 53384 160909 36
2 seconds
256 megabytes
['binary search', 'brute force', 'math', 'number theory', '*1700']
B. Replace and Keep Sortedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a positive integer k, two arrays are called k-similar if: they are strictly increasing; they have the same length; all their elements are positive integers between 1 and k (inclusive); they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i \leq r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}\ldots,a_{r_i}]. InputThe first line contains three integers n, q and k (1\leq n, q \leq 10^5, n\leq k \leq 10^9) — the length of array a, the number of queries and number k.The second line contains n integers a_1, a_2, \ldots,a_n (1 \leq a_i \leq k). This array is strictly increasing  — a_1 < a_2 < \ldots < a_n.Each of the following q lines contains two integers l_i, r_i (1 \leq l_i \leq r_i \leq n).OutputPrint q lines. The i-th of them should contain the answer to the i-th query.ExamplesInput 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 NoteIn the first example:In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5].In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5].
4 2 5 1 2 4 5 2 3 3 4
4 3
2 seconds
256 megabytes
['dp', 'implementation', 'math', '*1200']
A. Add and Dividetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have two positive integers a and b.You can perform two kinds of operations: a = \lfloor \frac{a}{b} \rfloor (replace a with the integer part of the division between a and b) b=b+1 (increase b by 1) Find the minimum number of operations required to make a=0.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.The only line of the description of each test case contains two integers a, b (1 \le a,b \le 10^9).OutputFor each test case, print a single integer: the minimum number of operations required to make a=0.ExampleInput 6 9 2 1337 1 1 1 50000000 4 991026972 997 1234 5678 Output 4 9 2 12 3 1 NoteIn the first test case, one of the optimal solutions is: Divide a by b. After this operation a = 4 and b = 2. Divide a by b. After this operation a = 2 and b = 2. Increase b. After this operation a = 2 and b = 3. Divide a by b. After this operation a = 0 and b = 3.
6 9 2 1337 1 1 1 50000000 4 991026972 997 1234 5678
4 9 2 12 3 1
1 second
256 megabytes
['brute force', 'greedy', 'math', 'number theory', '*1000']
H. Examtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis year a Chunin Selection Exam is held again in Konoha, and taking part in it are n ninjas named s_1, s_2, ..., s_n. All names are distinct. One of the exam stages consists of fights between the participants. This year the rules determining the ninjas for each fight are the following: ninjas i and j fight against each other if the following conditions are held: i \neq j; s_{j} is a substring of s_{i}; there is no k except i and j that s_{j} is a substring of s_{k}, and s_{k} is a substring of s_{i}. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Your task is to find out how many fights are going to take place this year.InputThe first line consists of the only integer n (1 \leq n \leq 10^{6}) standing for the number of examinees.The following n lines contain their names. No two names coincide, all names are non-empty and consist of lowercase English letters. The total length of all names doesn't exceed 10^6.OutputPrint the only integer standing for the number of fights.ExamplesInput 5 hidan dan hanabi bi nabi Output 3 Input 4 abacaba abaca acaba aca Output 4 NoteIn the first example hidan fights against dan, and hanabi fights against nabi, who also fights bi. Ninjas named hanabi and bi don't fight each other since there is the ninja called nabi who breaks the third condition for them.In the second example the fights are held between abacaba and acaba, abacaba and abaca, acaba and aca, abaca and aca.
5 hidan dan hanabi bi nabi
3
2 seconds
512 megabytes
['data structures', 'string suffix structures', 'trees', '*3400']
G. Vabanktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGustaw is the chief bank manager in a huge bank. He has unlimited access to the database system of the bank, in a few clicks he can move any amount of money from the bank's reserves to his own private account. However, the bank uses some fancy AI fraud detection system that makes stealing more difficult.Gustaw knows that the anti-fraud system just detects any operation that exceeds some fixed limit M euros and these operations are checked manually by a number of clerks. Thus, any fraud operation exceeding this limit is detected, while any smaller operation gets unnoticed.Gustaw doesn't know the limit M and wants to find it out. In one operation, he can choose some integer X and try to move X euros from the bank's reserves to his own account. Then, the following happens. If X \le M, the operation is unnoticed and Gustaw's account balance raises by X euros. Otherwise, if X > M, the fraud is detected and cancelled. Moreover, Gustaw has to pay X euros from his own account as a fine. If he has less than X euros on the account, he is fired and taken to the police. Initially Gustaw has 1 euro on his account. Help him find the exact value of M in no more than 105 operations without getting him fired.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000).For each test case, there is no input prior to your first query, but you can be sure that M is integer, and 0 \le M \le 10^{14}.OutputFor each test case, when you know the exact value of M, print a single line with format "! M". After that your program should proceed to the next test case or terminate, if it is the last one.InteractionWhen you want to make an operation, print a single line with format "? X", denoting that you try to move X euros (1 \le X \le 10^{14}). As a response, read a single line that can take the following values: "Lucky!", if X \le M. Your balance raises by X. "Fraudster!", if X > M. Your balance decreases by X. "Fired!", if X > M, but you can't pay X euros of fine. In this case your program must terminate immediately. You also get this response if you exceed the number of queries. You can make at most 105 such queries in each test case.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. HacksTo make a hack, prepare an input in the following format.The first line contains a single integer t (1 \le t \le 1000) — the number of test cases.Each test case is described with a line containing a single integer M (0 \le M \le 10^{14}).ExampleInput 1 Lucky! Lucky! Lucky! Lucky! Lucky! Fraudster! Output ? 1 ? 2 ? 3 ? 4 ? 5 ? 6 ! 5 NoteIn the example M = 5, so the operation with X = 6 is detected. At this moment, Gustaw's balance is 16 euros, so he just pays fine.
1 Lucky! Lucky! Lucky! Lucky! Lucky! Fraudster!
? 1 ? 2 ? 3 ? 4 ? 5 ? 6 ! 5
2 seconds
256 megabytes
['binary search', 'interactive', '*3200']
F. Useful Edgestime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a weighted undirected graph on n vertices along with q triples (u, v, l), where in each triple u and v are vertices and l is a positive integer. An edge e is called useful if there is at least one triple (u, v, l) and a path (not necessarily simple) with the following properties: u and v are the endpoints of this path, e is one of the edges of this path, the sum of weights of all edges on this path doesn't exceed l. Please print the number of useful edges in this graph.InputThe first line contains two integers n and m (2\leq n\leq 600, 0\leq m\leq \frac{n(n-1)}2). Each of the following m lines contains three integers u, v and w (1\leq u, v\leq n, u\neq v, 1\leq w\leq 10^9), denoting an edge connecting vertices u and v and having a weight w.The following line contains the only integer q (1\leq q\leq \frac{n(n-1)}2) denoting the number of triples.Each of the following q lines contains three integers u, v and l (1\leq u, v\leq n, u\neq v, 1\leq l\leq 10^9) denoting a triple (u, v, l).It's guaranteed that: the graph doesn't contain loops or multiple edges; all pairs (u, v) in the triples are also different. OutputPrint a single integer denoting the number of useful edges in the graph.ExamplesInput 4 6 1 2 1 2 3 1 3 4 1 1 3 3 2 4 3 1 4 5 1 1 4 4 Output 5 Input 4 2 1 2 10 3 4 10 6 1 2 11 1 3 11 1 4 11 2 3 11 2 4 11 3 4 9 Output 1 Input 3 2 1 2 1 2 3 2 1 1 2 5 Output 2 NoteIn the first example each edge is useful, except the one of weight 5.In the second example only edge between 1 and 2 is useful, because it belongs to the path 1-2, and 10 \leq 11. The edge between 3 and 4, on the other hand, is not useful.In the third example both edges are useful, for there is a path 1-2-3-2 of length exactly 5. Please note that the path may pass through a vertex more than once.
4 6 1 2 1 2 3 1 3 4 1 1 3 3 2 4 3 1 4 5 1 1 4 4
5
5 seconds
512 megabytes
['graphs', 'shortest paths', '*2400']
E. Skyline Phototime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice is visiting New York City. To make the trip fun, Alice will take photos of the city skyline and give the set of photos as a present to Bob. However, she wants to find the set of photos with maximum beauty and she needs your help. There are n buildings in the city, the i-th of them has positive height h_i. All n building heights in the city are different. In addition, each building has a beauty value b_i. Note that beauty can be positive or negative, as there are ugly buildings in the city too. A set of photos consists of one or more photos of the buildings in the skyline. Each photo includes one or more buildings in the skyline that form a contiguous segment of indices. Each building needs to be in exactly one photo. This means that if a building does not appear in any photo, or if a building appears in more than one photo, the set of pictures is not valid. The beauty of a photo is equivalent to the beauty b_i of the shortest building in it. The total beauty of a set of photos is the sum of the beauty of all photos in it. Help Alice to find the maximum beauty a valid set of photos can have. InputThe first line contains an integer n (1 \le n \le 3 \cdot 10^5), the number of buildings on the skyline. The second line contains n distinct integers h_1, h_2, \ldots, h_n (1 \le h_i \le n). The i-th number represents the height of building i.The third line contains n integers b_1, b_2, \ldots, b_n (-10^9 \le b_i \le 10^9). The i-th number represents the beauty of building i.OutputPrint one number representing the maximum beauty Alice can achieve for a valid set of photos of the skyline. ExamplesInput 5 1 2 3 5 4 1 5 3 2 4 Output 15 Input 5 1 4 3 2 5 -3 4 -10 2 7 Output 10 Input 2 2 1 -2 -3 Output -3 Input 10 4 7 3 2 5 1 9 10 6 8 -4 40 -46 -8 -16 4 -10 41 12 3 Output 96 NoteIn the first example, Alice can achieve maximum beauty by taking five photos, each one containing one building. In the second example, Alice can achieve a maximum beauty of 10 by taking four pictures: three just containing one building, on buildings 1, 2 and 5, each photo with beauty -3, 4 and 7 respectively, and another photo containing building 3 and 4, with beauty 2. In the third example, Alice will just take one picture of the whole city.In the fourth example, Alice can take the following pictures to achieve maximum beauty: photos with just one building on buildings 1, 2, 8, 9, and 10, and a single photo of buildings 3, 4, 5, 6, and 7.
5 1 2 3 5 4 1 5 3 2 4
15
2.5 seconds
256 megabytes
['data structures', 'divide and conquer', 'dp', '*2100']
D. Playlisttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady has a playlist that initially consists of n songs, numerated from 1 to n in the order they appear in the playlist. Arkady starts listening to the songs in the playlist one by one, starting from song 1. The playlist is cycled, i. e. after listening to the last song, Arkady will continue listening from the beginning.Each song has a genre a_i, which is a positive integer. Let Arkady finish listening to a song with genre y, and the genre of the next-to-last listened song be x. If \operatorname{gcd}(x, y) = 1, he deletes the last listened song (with genre y) from the playlist. After that he continues listening normally, skipping the deleted songs, and forgetting about songs he listened to before. In other words, after he deletes a song, he can't delete the next song immediately.Here \operatorname{gcd}(x, y) denotes the greatest common divisor (GCD) of integers x and y.For example, if the initial songs' genres were [5, 9, 2, 10, 15], then the playlist is converted as follows: [5, 9, 2, 10, 15] \to [5, 9, 2, 10, 15] \to [5, 2, 10, 15] (because \operatorname{gcd}(5, 9) = 1) \to [5, 2, 10, 15] \to [5, 2, 10, 15] \to [5, 2, 10, 15] \to [5, 2, 10, 15] \to [5, 2, 10, 15] \to [5, 10, 15] (because \operatorname{gcd}(5, 2) = 1) \to [5, 10, 15] \to [5, 10, 15] \to ... The bold numbers represent the two last played songs. Note that after a song is deleted, Arkady forgets that he listened to that and the previous songs.Given the initial playlist, please determine which songs are eventually deleted and the order these songs are deleted.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10\,000). 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 number of songs.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the genres of the songs.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print a single line. First, print a single integer k — the number of deleted songs. After that print k distinct integers: deleted songs in the order of their deletion.ExampleInput 5 5 5 9 2 10 15 6 1 2 4 2 4 2 2 1 2 1 1 1 2 Output 2 2 3 2 2 1 2 2 1 1 1 0 NoteExplanation of the first test case is given in the statement.In the second test case, the playlist is converted as follows: [1, 2, 4, 2, 4, 2] \to [1, 2, 4, 2, 4, 2] \to [1, 4, 2, 4, 2] (because \operatorname{gcd}(1, 2) = 1) \to [1, 4, 2, 4, 2] \to [1, 4, 2, 4, 2] \to [1, 4, 2, 4, 2] \to [1, 4, 2, 4, 2] \to [1, 4, 2, 4, 2] \to [4, 2, 4, 2] (because \operatorname{gcd}(2, 1) = 1) \to [4, 2, 4, 2] \to ...In the third test case, the playlist is converted as follows: [1, 2] \to [1, 2] \to [1] (because \operatorname{gcd}(1, 2) = 1) \to [1] \to [1] (Arkady listened to the same song twice in a row) \to [] (because \operatorname{gcd}(1, 1) = 1).The fourth test case is same as the third after deletion of the second song.In the fifth test case, the same song is listened to over and over again, but since \operatorname{gcd}(2, 2) \ne 1, it is not deleted.
5 5 5 9 2 10 15 6 1 2 4 2 4 2 2 1 2 1 1 1 2
2 2 3 2 2 1 2 2 1 1 1 0
2 seconds
256 megabytes
['data structures', 'dsu', 'implementation', 'shortest paths', '*1900']
C. Basic Diplomacytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAleksey has n friends. He is also on a vacation right now, so he has m days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these m days.On each of these days some friends will be available for playing, and all others will not. On each day Aleksey must choose one of his available friends to offer him playing the game (and they, of course, always agree). However, if any of them happens to be chosen strictly more than \left\lceil\dfrac{m}{2}\right\rceil times, then all other friends are offended. Of course, Aleksey doesn't want to offend anyone.Help him to choose teammates so that nobody is chosen strictly more than \left\lceil\dfrac{m}{2}\right\rceil times.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10\,000). Description of the test cases follows.The first line of each test case contains two integers n and m (1\leq n, m\leq 100\,000) standing for the number of friends and the number of days to play, respectively.The i-th of the following m lines contains an integer k_i (1\leq k_i\leq n), followed by k_i distinct integers f_{i1}, ..., f_{ik_i} (1\leq f_{ij}\leq n), separated by spaces — indices of available friends on the day i.It is guaranteed that the sums of n and m over all test cases do not exceed 100\,000. It's guaranteed that the sum of all k_i over all days of all test cases doesn't exceed 200\,000.OutputPrint an answer for each test case. If there is no way to achieve the goal, print "NO".Otherwise, in the first line print "YES", and in the second line print m space separated integers c_1, ..., c_m. Each c_i must denote the chosen friend on day i (and therefore must be one of f_{ij}).No value must occur more than \left\lceil\dfrac{m}{2}\right\rceil times. If there is more than one possible answer, print any of them.ExampleInput 2 4 6 1 1 2 1 2 3 1 2 3 4 1 2 3 4 2 2 3 1 3 2 2 1 1 1 1 Output YES 1 2 1 1 2 3 NO
2 4 6 1 1 2 1 2 3 1 2 3 4 1 2 3 4 2 2 3 1 3 2 2 1 1 1 1
YES 1 2 1 1 2 3 NO
2 seconds
512 megabytes
['brute force', 'constructive algorithms', 'greedy', 'implementation', '*1600']
B. Restore Modulotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor the first place at the competition, Alex won many arrays of integers and was assured that these arrays are very expensive. After the award ceremony Alex decided to sell them. There is a rule in arrays pawnshop: you can sell array only if it can be compressed to a generator.This generator takes four non-negative numbers n, m, c, s. n and m must be positive, s non-negative and for c it must be true that 0 \leq c < m. The array a of length n is created according to the following rules: a_1 = s \bmod m, here x \bmod y denotes remainder of the division of x by y; a_i = (a_{i-1} + c) \bmod m for all i such that 1 < i \le n. For example, if n = 5, m = 7, c = 4, and s = 10, then a = [3, 0, 4, 1, 5].Price of such an array is the value of m in this generator.Alex has a question: how much money he can get for each of the arrays. Please, help him to understand for every array whether there exist four numbers n, m, c, s that generate this array. If yes, then maximize m.InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of arrays.The first line of array description contains a single integer n (1 \leq n \leq 10^5) — the size of this array.The second line of array description contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9 ) — elements of the array. It is guaranteed that the sum of array sizes does not exceed 10^5.OutputFor every array print: -1, if there are no such four numbers that generate this array; 0, if m can be arbitrary large; the maximum value m and any appropriate c (0 \leq c < m) in other cases. ExampleInput 6 6 1 9 17 6 14 3 3 4 2 2 3 7 3 4 3 2 2 4 5 0 1000000000 0 1000000000 0 2 1 1 Output 19 8 -1 -1 -1 2000000000 1000000000 0
6 6 1 9 17 6 14 3 3 4 2 2 3 7 3 4 3 2 2 4 5 0 1000000000 0 1000000000 0 2 1 1
19 8 -1 -1 -1 2000000000 1000000000 0
1 second
256 megabytes
['implementation', 'math', '*1500']
A. Prison Breaktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMichael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.The prison can be represented as a rectangle a\times b which is divided into ab cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible.Your task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.InputThe first line contains a single integer t (1\leq t\leq 100) — the number of test cases.Each of the following t lines contains two integers a and b (1\leq a, b\leq 100), representing a corresponding test case.OutputFor each test case print the single integer on a separate line — the answer to the problem.ExampleInput 2 2 2 1 3 Output 4 3 NoteSome possible escape plans for the example test cases are shown below. Broken walls are shown in gray, not broken walls are shown in black.
2 2 2 1 3
4 3
1 second
256 megabytes
['math', '*800']
F. AB Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd. The problem is:You are given a connected tree rooted at node 1.You should assign a character a or b to every node in the tree so that the total number of a's is equal to x and the total number of b's is equal to n - x.Let's define a string for each node v of the tree as follows: if v is root then the string is just one character assigned to v: otherwise, let's take a string defined for the v's parent p_v and add to the end of it a character assigned to v. You should assign every node a character in a way that minimizes the number of distinct strings among the strings of all nodes.InputThe first line contains two integers n and x (1 \leq n \leq 10^5; 0 \leq x \leq n) — the number of vertices in the tree the number of a's.The second line contains n - 1 integers p_2, p_3, \dots, p_{n} (1 \leq p_i \leq n; p_i \neq i), where p_i is the parent of node i.It is guaranteed that the input describes a connected tree.OutputIn the first line, print the minimum possible total number of distinct strings.In the second line, print n characters, where all characters are either a or b and the i-th character is the character assigned to the i-th node.Make sure that the total number of a's is equal to x and the total number of b's is equal to n - x.If there is more than one answer you can print any of them.ExampleInput 9 3 1 2 2 4 4 4 3 1 Output 4 aabbbbbba NoteThe tree from the sample is shown below: The tree after assigning characters to every node (according to the output) is the following: Strings for all nodes are the following: string of node 1 is: a string of node 2 is: aa string of node 3 is: aab string of node 4 is: aab string of node 5 is: aabb string of node 6 is: aabb string of node 7 is: aabb string of node 8 is: aabb string of node 9 is: aa The set of unique strings is \{\text{a}, \text{aa}, \text{aab}, \text{aabb}\}, so the number of distinct strings is 4.
9 3 1 2 2 4 4 4 3 1
4 aabbbbbba
2 seconds
256 megabytes
['dp', 'greedy', 'trees', '*3100']
E. Sorting Bookstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are n books standing in a row on the shelf, the i-th book has color a_i.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?InputThe first line contains one integer n (1 \le n \le 5 \cdot 10^5) — the number of books.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the book colors.OutputOutput the minimum number of operations to make the shelf beautiful.ExamplesInput 5 1 2 2 1 3 Output 2 Input 5 1 2 2 1 1 Output 1 NoteIn the first example, we have the bookshelf [1, 2, 2, 1, 3] and can, for example: take a book on position 4 and move to the right end: we'll get [1, 2, 2, 3, 1]; take a book on position 1 and move to the right end: we'll get [2, 2, 3, 1, 1]. In the second example, we can move the first book to the end of the bookshelf and get [2,2,1,1,1].
5 1 2 2 1 3
2
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', '*2500']
D. AB Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u \neq v) has both directed edges (u, v) and (v, u).Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.InputThe first line contains a single integer t (1 \le t \le 500) — the number of test cases.The first line of each test case contains two integers n and m (2 \leq n \leq 1000; 1 \leq m \leq 10^{5}) — the number of vertices in the graph and desirable length of the palindrome.Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.Every character is either 'a' or 'b' if i \neq j, or '*' if i = j, since the graph doesn't contain self-loops.It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.OutputFor each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.Otherwise, (if there is no answer) print "NO".ExampleInput 5 3 1 *ba b*b ab* 3 3 *ba b*b ab* 3 4 *ba b*b ab* 4 6 *aaa b*ba ab*a bba* 2 6 *a b* Output YES 1 2 YES 2 1 3 2 YES 1 3 1 3 1 YES 1 2 1 3 4 1 4 NO NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is [1,2] which means that the path is:1 \xrightarrow{\text{b}} 2So the string that is obtained by the given path is b.In the second test case, the answer sequence is [2,1,3,2] which means that the path is:2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2So the string that is obtained by the given path is bab.In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
5 3 1 *ba b*b ab* 3 3 *ba b*b ab* 3 4 *ba b*b ab* 4 6 *aaa b*ba ab*a bba* 2 6 *a b*
YES 1 2 YES 2 1 3 2 YES 1 3 1 3 1 YES 1 2 1 3 4 1 4 NO
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'graphs', 'greedy', 'implementation', '*2000']
C. Fence Paintingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou finally woke up after this crazy dream and decided to walk around to clear your head. Outside you saw your house's fence — so plain and boring, that you'd like to repaint it. You have a fence consisting of n planks, where the i-th plank has the color a_i. You want to repaint the fence in such a way that the i-th plank has the color b_i.You've invited m painters for this purpose. The j-th painter will arrive at the moment j and will recolor exactly one plank to color c_j. For each painter you can choose which plank to recolor, but you can't turn them down, i. e. each painter has to color exactly one plank.Can you get the coloring b you want? If it's possible, print for each painter which plank he must paint.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of each test case contains two integers n and m (1 \le n, m \le 10^5) — the number of planks in the fence and the number of painters.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the initial colors of the fence.The third line of each test case contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le n) — the desired colors of the fence.The fourth line of each test case contains m integers c_1, c_2, \dots, c_m (1 \le c_j \le n) — the colors painters have.It's guaranteed that the sum of n doesn't exceed 10^5 and the sum of m doesn't exceed 10^5 over all test cases.OutputFor each test case, output "NO" if it is impossible to achieve the coloring b.Otherwise, print "YES" and m integers x_1, x_2, \dots, x_m, where x_j is the index of plank the j-th painter should paint.You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes" and "YES" are all recognized as positive answer).ExampleInput 6 1 1 1 1 1 5 2 1 2 2 1 1 1 2 2 1 1 1 2 3 3 2 2 2 2 2 2 2 3 2 10 5 7 3 2 1 7 9 4 2 7 9 9 9 2 1 4 9 4 2 3 9 9 9 7 4 3 5 2 1 2 2 1 1 1 2 2 1 1 3 3 6 4 3 4 2 4 1 2 2 3 1 3 1 1 2 2 3 4 Output YES 1 YES 2 2 YES 1 1 1 YES 2 1 9 5 9 NO NO
6 1 1 1 1 1 5 2 1 2 2 1 1 1 2 2 1 1 1 2 3 3 2 2 2 2 2 2 2 3 2 10 5 7 3 2 1 7 9 4 2 7 9 9 9 2 1 4 9 4 2 3 9 9 9 7 4 3 5 2 1 2 2 1 1 1 2 2 1 1 3 3 6 4 3 4 2 4 1 2 2 3 1 3 1 1 2 2 3 4
YES 1 YES 2 2 YES 1 1 1 YES 2 1 9 5 9 NO NO
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'greedy', '*1600']
B. New Colonytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you). You are given an array h_1, h_2, \dots, h_n, where h_i is the height of the i-th mountain, and k — the number of boulders you have.You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is h_i): if h_i \ge h_{i + 1}, the boulder will roll to the next mountain; if h_i < h_{i + 1}, the boulder will stop rolling and increase the mountain height by 1 (h_i = h_i + 1); if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the k-th boulder or determine that it will fall into the waste collection system.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.Each test case consists of two lines. The first line in each test case contains two integers n and k (1 \le n \le 100; 1 \le k \le 10^9) — the number of mountains and the number of boulders.The second line contains n integers h_1, h_2, \dots, h_n (1 \le h_i \le 100) — the height of the mountains.It is guaranteed that the sum of n over all test cases does not exceed 100.OutputFor each test case, print -1 if the k-th boulder will fall into the collection system. Otherwise, print the position of the k-th boulder.ExampleInput 4 4 3 4 1 2 3 2 7 1 8 4 5 4 1 2 3 3 1 5 3 1 Output 2 1 -1 -1 NoteLet's simulate the first case: The first boulder starts at i = 1; since h_1 \ge h_2 it rolls to i = 2 and stops there because h_2 < h_3. The new heights are [4,2,2,3]. The second boulder starts at i = 1; since h_1 \ge h_2 the boulder rolls to i = 2; since h_2 \ge h_3 the boulder rolls to i = 3 and stops there because h_3 < h_4. The new heights are [4,2,3,3]. The third boulder starts at i = 1; since h_1 \ge h_2 it rolls to i = 2 and stops there because h_2 < h_3. The new heights are [4,3,3,3]. The positions where each boulder stopped are the following: [2,3,2].In the second case, all 7 boulders will stop right at the first mountain rising its height from 1 to 8.The third case is similar to the first one but now you'll throw 5 boulders. The first three will roll in the same way as in the first test case. After that, mountain heights will be equal to [4, 3, 3, 3], that's why the other two boulders will fall into the collection system.In the fourth case, the first and only boulders will fall straight into the collection system.
4 4 3 4 1 2 3 2 7 1 8 4 5 4 1 2 3 3 1 5 3 1
2 1 -1 -1
2 seconds
256 megabytes
['brute force', 'greedy', 'implementation', '*1100']
A. Space Navigation time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces. Space can be represented as the XY plane. You are starting at point (0, 0), and Planetforces is located in point (p_x, p_y).The piloting system of your spaceship follows its list of orders which can be represented as a string s. The system reads s from left to right. Suppose you are at point (x, y) and current order is s_i: if s_i = \text{U}, you move to (x, y + 1); if s_i = \text{D}, you move to (x, y - 1); if s_i = \text{R}, you move to (x + 1, y); if s_i = \text{L}, you move to (x - 1, y). Since string s could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, you can delete some orders from s but you can't change their positions.Can you delete several orders (possibly, zero) from s in such a way, that you'll reach Planetforces after the system processes all orders?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of two lines. The first line in each test case contains two integers p_x and p_y (-10^5 \le p_x, p_y \le 10^5; (p_x, p_y) \neq (0, 0)) — the coordinates of Planetforces (p_x, p_y).The second line contains the string s (1 \le |s| \le 10^5: |s| is the length of string s) — the list of orders.It is guaranteed that the sum of |s| over all test cases does not exceed 10^5.OutputFor each test case, print "YES" if you can delete several orders (possibly, zero) from s in such a way, that you'll reach Planetforces. Otherwise, print "NO". You can print each letter in any case (upper or lower).ExampleInput 6 10 5 RRRRRRRRRRUUUUU 1 1 UDDDRLLL -3 -5 LDLDLDDDR 1 2 LLLLUU 3 -2 RDULRLLDR -1 6 RUDURUUUUR Output YES YES YES NO YES NO NoteIn the first case, you don't need to modify s, since the given s will bring you to Planetforces.In the second case, you can delete orders s_2, s_3, s_4, s_6, s_7 and s_8, so s becomes equal to "UR".In the third test case, you have to delete order s_9, otherwise, you won't finish in the position of Planetforces.
6 10 5 RRRRRRRRRRUUUUU 1 1 UDDDRLLL -3 -5 LDLDLDDDR 1 2 LLLLUU 3 -2 RDULRLLDR -1 6 RUDURUUUUR
YES YES YES NO YES NO
2 seconds
256 megabytes
['greedy', 'strings', '*800']
B. The Great Herotime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe great hero guards the country where Homer lives. The hero has attack power A and initial health value B. There are n monsters in front of the hero. The i-th monster has attack power a_i and initial health value b_i. The hero or a monster is said to be living, if his or its health value is positive (greater than or equal to 1); and he or it is said to be dead, if his or its health value is non-positive (less than or equal to 0).In order to protect people in the country, the hero will fight with monsters until either the hero is dead or all the monsters are dead. In each fight, the hero can select an arbitrary living monster and fight with it. Suppose the i-th monster is selected, and the health values of the hero and the i-th monster are x and y before the fight, respectively. After the fight, the health values of the hero and the i-th monster become x-a_i and y-A, respectively. Note that the hero can fight the same monster more than once.For the safety of the people in the country, please tell them whether the great hero can kill all the monsters (even if the great hero himself is dead after killing the last monster).InputEach test contains multiple test cases. The first line contains t (1 \le t \le 10^5) — the number of test cases. Description of the test cases follows.The first line of each test case contains three integers A (1 \leq A \leq 10^6), B (1 \leq B \leq 10^6) and n (1 \leq n \leq 10^5) — the attack power of the great hero, the initial health value of the great hero, and the number of monsters.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^6), where a_i denotes the attack power of the i-th monster.The third line of each test case contains n integers b_1, b_2, \dots, b_n (1 \leq b_i \leq 10^6), where b_i denotes the initial health value of the i-th monster.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print the answer: "YES" (without quotes) if the great hero can kill all the monsters. Otherwise, print "NO" (without quotes).ExampleInput 5 3 17 1 2 16 10 999 3 10 20 30 100 50 30 1000 1000 4 200 300 400 500 1000 1000 1000 1000 999 999 1 1000 1000 999 999 1 1000000 999 Output YES YES YES NO YES NoteIn the first example: There will be 6 fights between the hero and the only monster. After that, the monster is dead and the health value of the hero becomes 17 - 6 \times 2 = 5 > 0. So the answer is "YES", and moreover, the hero is still living.In the second example: After all monsters are dead, the health value of the hero will become 709, regardless of the order of all fights. So the answer is "YES".In the third example: A possible order is to fight with the 1-st, 2-nd, 3-rd and 4-th monsters. After all fights, the health value of the hero becomes -400. Unfortunately, the hero is dead, but all monsters are also dead. So the answer is "YES".In the fourth example: The hero becomes dead but the monster is still living with health value 1000 - 999 = 1. So the answer is "NO".
5 3 17 1 2 16 10 999 3 10 20 30 100 50 30 1000 1000 4 200 300 400 500 1000 1000 1000 1000 999 999 1 1000 1000 999 999 1 1000000 999
YES YES YES NO YES
2 seconds
512 megabytes
['greedy', 'implementation', 'sortings', '*900']
A. Yet Another String Gametime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputHomer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string s = s_1 s_2 \dots s_n of length n consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.In a move, a player must choose an index i (1 \leq i \leq n) that has not been chosen before, and change s_i to any other lowercase English letter c that c \neq s_i.When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.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. InputEach test contains multiple test cases. The first line contains t (1 \le t \le 1000)  — the number of test cases. Description of the test cases follows.The only line of each test case contains a single string s (1 \leq |s| \leq 50) consisting of lowercase English letters.OutputFor each test case, print the final string in a single line.ExampleInput 3 a bbbb az Output b azaz by NoteIn the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.
3 a bbbb az
b azaz by
2 seconds
512 megabytes
['games', 'greedy', 'strings', '*800']
E. School Clubstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn Homer's school, there are n students who love clubs. Initially, there are m clubs, and each of the n students is in exactly one club. In other words, there are a_i students in the i-th club for 1 \leq i \leq m and a_1+a_2+\dots+a_m = n.The n students are so unfriendly that every day one of them (chosen uniformly at random from all of the n students) gets angry. The student who gets angry will do one of the following things. With probability \frac 1 2, he leaves his current club, then creates a new club himself and joins it. There is only one student (himself) in the new club he creates. With probability \frac 1 2, he does not create new clubs. In this case, he changes his club to a new one (possibly the same club he is in currently) with probability proportional to the number of students in it. Formally, suppose there are k clubs and there are b_i students in the i-th club for 1 \leq i \leq k (before the student gets angry). He leaves his current club, and then joins the i-th club with probability \frac {b_i} {n}. We note that when a club becomes empty, students will never join it because any student who gets angry will join an empty club with probability 0 according to the above statement.Homer wonders the expected number of days until every student is in the same club for the first time.We can prove that the answer can be represented as a rational number \frac p q with \gcd(p, q) = 1. Therefore, you are asked to find the value of pq^{-1} \bmod 998\,244\,353. It can be shown that q \bmod 998\,244\,353 \neq 0 under the given constraints of the problem.InputThe first line contains an integer m (1 \leq m \leq 1000) — the number of clubs initially.The second line contains m integers a_1, a_2, \dots, a_m (1 \leq a_i \leq 4 \cdot 10^8) with 1 \leq a_1+a_2+\dots+a_m \leq 4 \cdot 10^8, where a_i denotes the number of students in the i-th club initially.OutputPrint one integer — the expected number of days until every student is in the same club for the first time, modulo 998\,244\,353.ExamplesInput 2 1 1 Output 4 Input 2 1 2 Output 18 Input 3 1 1 1 Output 21 Input 1 400000000 Output 0 Input 10 1 2 3 4 5 6 7 8 9 10 Output 737609878 NoteIn the first example, no matter which student gets angry, the two students will become in the same club with probability \frac 1 4. So the expected number of days until every student is in the same club should be 4.In the second example, we note that in the first day: The only student in the first club will get angry with probability \frac 1 3. If he gets angry, then he will create a new club and join it with probability \frac 1 2 (In this case, there will be three clubs which have 0, 1, 2 students in it, respectively), leave his current club and join the second club with probability \frac 1 2 \cdot \frac 2 3 = \frac 1 3, or stay still with probability \frac 1 2 \cdot \frac 1 3 = \frac 1 6; Each of the two students in the second club will get angry with probability \frac 1 3. If one of them gets angry, then he will create a new club and join it with probability \frac 1 2, leave his current club and join the second club with probability \frac 1 2 \cdot \frac 1 3 = \frac 1 6, or stay still with probability \frac 1 2 \cdot \frac 2 3 = \frac 1 3. In the fourth example, there is only one club initially. That is, every student has already been in the same club. So the answer is 0.
2 1 1
4
4 seconds
512 megabytes
['dp', 'fft', 'math', 'number theory', 'probabilities', '*3500']
D. Odd Mineral Resourcetime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIn Homer's country, there are n cities numbered 1 to n and they form a tree. That is, there are (n-1) undirected roads between these n cities and every two cities can reach each other through these roads. Homer's country is an industrial country, and each of the n cities in it contains some mineral resource. The mineral resource of city i is labeled a_i. Homer is given the plans of the country in the following q years. The plan of the i-th year is described by four parameters u_i, v_i, l_i and r_i, and he is asked to find any mineral resource c_i such that the following two conditions hold: mineral resource c_i appears an odd number of times between city u_i and city v_i; and l_i \leq c_i \leq r_i. As the best friend of Homer, he asks you for help. For every plan, find any such mineral resource c_i, or tell him that there doesn't exist one.InputThe first line contains two integers n (1 \leq n \leq 3 \cdot 10^5) and q (1 \leq q \leq 3 \cdot 10^5), indicating the number of cities and the number of plans.The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq n).Then the i-th line of the following (n-1) lines contains two integers x_i and y_i (1 \leq x_i, y_i \leq n) with x_i \neq y_i, indicating that there is a bidirectional road between city x_i and city y_i. It is guaranteed that the given roads form a tree.Then the i-th line of the following q lines contains four integers u_i, v_i, l_i, r_i (1 \leq u_i \leq n, 1 \leq v_i \leq n, 1 \leq l_i \leq r_i \leq n), indicating the plan of the i-th year.OutputPrint q lines, the i-th of which contains an integer c_i such that c_i = {-1} if there is no such mineral resource that meets the required condition; or c_i is the label of the chosen mineral resource of the i-th year. The chosen mineral resource c_i should meet those conditions in the i-th year described above in the problem statement. If there are multiple choices of c_i, you can print any of them. ExampleInput 6 8 3 2 1 3 1 3 1 2 1 3 2 4 2 5 4 6 3 5 1 1 3 5 1 3 3 5 1 3 1 1 2 2 1 1 3 3 1 4 1 5 1 6 1 3 1 6 1 3 Output -1 2 3 -1 3 2 2 3NoteIn the first three queries, there are four cities between city 3 and city 5, which are city 1, city 2, city 3 and city 5. The mineral resources appear in them are mineral resources 1 (appears in city 3 and city 5), 2 (appears in city 2) and 3 (appears in city 1). It is noted that The first query is only to check whether mineral source 1 appears an odd number of times between city 3 and city 5. The answer is no, because mineral source 1 appears twice (an even number of times) between city 3 and city 5. The second and the third queries are the same but they can choose different mineral resources. Both mineral resources 2 and 3 are available.
6 8 3 2 1 3 1 3 1 2 1 3 2 4 2 5 4 6 3 5 1 1 3 5 1 3 3 5 1 3 1 1 2 2 1 1 3 3 1 4 1 5 1 6 1 3 1 6 1 3
-1 2 3 -1 3 2 2 3
5 seconds
1024 megabytes
['binary search', 'bitmasks', 'brute force', 'data structures', 'probabilities', 'trees', '*2900']
C. Continuous Citytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSome time ago Homer lived in a beautiful city. There were n blocks numbered from 1 to n and m directed roads between them. Each road had a positive length, and each road went from the block with the smaller index to the block with the larger index. For every two (different) blocks, there was at most one road between them. Homer discovered that for some two numbers L and R the city was (L, R)-continuous. The city is said to be (L, R)-continuous, if all paths from block 1 to block n are of length between L and R (inclusive); and for every L \leq d \leq R, there is exactly one path from block 1 to block n whose length is d. A path from block u to block v is a sequence u = x_0 \to x_1 \to x_2 \to \dots \to x_k = v, where there is a road from block x_{i-1} to block x_{i} for every 1 \leq i \leq k. The length of a path is the sum of lengths over all roads in the path. Two paths x_0 \to x_1 \to \dots \to x_k and y_0 \to y_1 \to \dots \to y_l are different, if k \neq l or x_i \neq y_i for some 0 \leq i \leq \min\{k, l\}. After moving to another city, Homer only remembers the two special numbers L and R but forgets the numbers n and m of blocks and roads, respectively, and how blocks are connected by roads. However, he believes the number of blocks should be no larger than 32 (because the city was small).As the best friend of Homer, please tell him whether it is possible to find a (L, R)-continuous city or not. InputThe single line contains two integers L and R (1 \leq L \leq R \leq 10^6).OutputIf it is impossible to find a (L, R)-continuous city within 32 blocks, print "NO" in a single line.Otherwise, print "YES" in the first line followed by a description of a (L, R)-continuous city. The second line should contain two integers n (2 \leq n \leq 32) and m (1 \leq m \leq \frac {n(n-1)} 2), where n denotes the number of blocks and m denotes the number of roads.Then m lines follow. The i-th of the m lines should contain three integers a_i, b_i (1 \leq a_i < b_i \leq n) and c_i (1 \leq c_i \leq 10^6) indicating that there is a directed road from block a_i to block b_i of length c_i. It is required that for every two blocks, there should be no more than 1 road connecting them. That is, for every 1 \leq i < j \leq m, either a_i \neq a_j or b_i \neq b_j.ExamplesInput 1 1 Output YES 2 1 1 2 1 Input 4 6 Output YES 5 6 1 2 3 1 3 4 1 4 5 2 5 1 3 5 1 4 5 1 NoteIn the first example there is only one path from block 1 to block n = 2, and its length is 1. In the second example there are three paths from block 1 to block n = 5, which are 1 \to 2 \to 5 of length 4, 1 \to 3 \to 5 of length 5 and 1 \to 4 \to 5 of length 6.
1 1
YES 2 1 1 2 1
2 seconds
512 megabytes
['bitmasks', 'constructive algorithms', '*2500']
B2. Painting the Array IItime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between the two versions is that this version asks the minimal possible answer.Homer likes arrays a lot. Today he is painting an array a_1, a_2, \dots, a_n with two kinds of colors, white and black. A painting assignment for a_1, a_2, \dots, a_n is described by an array b_1, b_2, \dots, b_n that b_i indicates the color of a_i (0 for white and 1 for black).According to a painting assignment b_1, b_2, \dots, b_n, the array a is split into two new arrays a^{(0)} and a^{(1)}, where a^{(0)} is the sub-sequence of all white elements in a and a^{(1)} is the sub-sequence of all black elements in a. For example, if a = [1,2,3,4,5,6] and b = [0,1,0,1,0,0], then a^{(0)} = [1,3,5,6] and a^{(1)} = [2,4].The number of segments in an array c_1, c_2, \dots, c_k, denoted \mathit{seg}(c), is the number of elements if we merge all adjacent elements with the same value in c. For example, the number of segments in [1,1,2,2,3,3,3,2] is 4, because the array will become [1,2,3,2] after merging adjacent elements with the same value. Especially, the number of segments in an empty array is 0.Homer wants to find a painting assignment b, according to which the number of segments in both a^{(0)} and a^{(1)}, i.e. \mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)}), is as small as possible. Find this number.InputThe first line contains an integer n (1 \leq n \leq 10^5).The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq n).OutputOutput a single integer, indicating the minimal possible total number of segments.ExamplesInput 6 1 2 3 1 2 2 Output 4 Input 7 1 2 1 2 1 2 1 Output 2 NoteIn the first example, we can choose a^{(0)} = [1,1,2,2], a^{(1)} = [2,3] and \mathit{seg}(a^{(0)}) = \mathit{seg}(a^{(1)}) = 2. So the answer is 2+2 = 4.In the second example, we can choose a^{(0)} = [1,1,1,1], a^{(1)} = [2,2,2] and \mathit{seg}(a^{(0)}) = \mathit{seg}(a^{(1)}) = 1. So the answer is 1+1 = 2.
6 1 2 3 1 2 2
4
2 seconds
512 megabytes
['constructive algorithms', 'data structures', 'dp', 'greedy', 'implementation', '*2100']
B1. Painting the Array Itime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between the two versions is that this version asks the maximal possible answer.Homer likes arrays a lot. Today he is painting an array a_1, a_2, \dots, a_n with two kinds of colors, white and black. A painting assignment for a_1, a_2, \dots, a_n is described by an array b_1, b_2, \dots, b_n that b_i indicates the color of a_i (0 for white and 1 for black).According to a painting assignment b_1, b_2, \dots, b_n, the array a is split into two new arrays a^{(0)} and a^{(1)}, where a^{(0)} is the sub-sequence of all white elements in a and a^{(1)} is the sub-sequence of all black elements in a. For example, if a = [1,2,3,4,5,6] and b = [0,1,0,1,0,0], then a^{(0)} = [1,3,5,6] and a^{(1)} = [2,4].The number of segments in an array c_1, c_2, \dots, c_k, denoted \mathit{seg}(c), is the number of elements if we merge all adjacent elements with the same value in c. For example, the number of segments in [1,1,2,2,3,3,3,2] is 4, because the array will become [1,2,3,2] after merging adjacent elements with the same value. Especially, the number of segments in an empty array is 0.Homer wants to find a painting assignment b, according to which the number of segments in both a^{(0)} and a^{(1)}, i.e. \mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)}), is as large as possible. Find this number.InputThe first line contains an integer n (1 \leq n \leq 10^5).The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq n).OutputOutput a single integer, indicating the maximal possible total number of segments.ExamplesInput 7 1 1 2 2 3 3 3 Output 6 Input 7 1 2 3 4 5 6 7 Output 7 NoteIn the first example, we can choose a^{(0)} = [1,2,3,3], a^{(1)} = [1,2,3] and \mathit{seg}(a^{(0)}) = \mathit{seg}(a^{(1)}) = 3. So the answer is 3+3 = 6.In the second example, we can choose a^{(0)} = [1,2,3,4,5,6,7] and a^{(1)} is empty. We can see that \mathit{seg}(a^{(0)}) = 7 and \mathit{seg}(a^{(1)}) = 0. So the answer is 7+0 = 7.
7 1 1 2 2 3 3 3
6
2 seconds
512 megabytes
['constructive algorithms', 'data structures', 'dp', 'greedy', 'implementation', '*1900']
A. Searching Local Minimumtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Homer likes arrays a lot and he wants to play a game with you. Homer has hidden from you a permutation a_1, a_2, \dots, a_n of integers 1 to n. You are asked to find any index k (1 \leq k \leq n) which is a local minimum. For an array a_1, a_2, \dots, a_n, an index i (1 \leq i \leq n) is said to be a local minimum if a_i < \min\{a_{i-1},a_{i+1}\}, where a_0 = a_{n+1} = +\infty. An array is said to be a permutation of integers 1 to n, if it contains all integers from 1 to n exactly once.Initially, you are only given the value of n without any other information about this permutation.At each interactive step, you are allowed to choose any i (1 \leq i \leq n) and make a query with it. As a response, you will be given the value of a_i. You are asked to find any index k which is a local minimum after at most 100 queries.InteractionYou begin the interaction by reading an integer n (1\le n \le 10^5) on a separate line.To make a query on index i (1 \leq i \leq n), you should output "? i" in a separate line. Then read the value of a_i in a separate line. The number of the "?" queries is limited within 100.When you find an index k (1 \leq k \leq n) which is a local minimum, output "! k" in a separate line and terminate your program. In case your query format is invalid, or you have made more than 100 "?" queries, you will receive Wrong Answer verdict. After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack FormatThe first line of the hack should contain a single integer n (1 \leq n \leq 10^5).The second line should contain n distinct integers a_1, a_2, \dots, a_n (1 \leq a_i \leq n).ExampleInput 5 3 2 1 4 5 Output ? 1 ? 2 ? 3 ? 4 ? 5 ! 3 NoteIn the example, the first line contains an integer 5 indicating that the length of the array is n = 5.The example makes five "?" queries, after which we conclude that the array is a = [3,2,1,4,5] and k = 3 is local minimum.
5 3 2 1 4 5
? 1 ? 2 ? 3 ? 4 ? 5 ! 3
2 seconds
512 megabytes
['binary search', 'interactive', 'ternary search', '*1700']
C. Nezzar and Symmetric Arraytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLong time ago there was a symmetric array a_1,a_2,\ldots,a_{2n} consisting of 2n distinct integers. Array a_1,a_2,\ldots,a_{2n} is called symmetric if for each integer 1 \le i \le 2n, there exists an integer 1 \le j \le 2n such that a_i = -a_j.For each integer 1 \le i \le 2n, Nezzar wrote down an integer d_i equal to the sum of absolute differences from a_i to all integers in a, i. e. d_i = \sum_{j = 1}^{2n} {|a_i - a_j|}.Now a million years has passed and Nezzar can barely remember the array d and totally forget a. Nezzar wonders if there exists any symmetric array a consisting of 2n distinct integers that generates the array d.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. The first line of each test case contains a single integer n (1 \le n \le 10^5).The second line of each test case contains 2n integers d_1, d_2, \ldots, d_{2n} (0 \le d_i \le 10^{12}).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print "YES" in a single line if there exists a possible array a. Otherwise, print "NO".You can print letters in any case (upper or lower).ExampleInput 6 2 8 12 8 12 2 7 7 9 11 2 7 11 7 11 1 1 1 4 40 56 48 40 80 56 80 48 6 240 154 210 162 174 154 186 240 174 186 162 210 Output YES NO NO NO NO YES NoteIn the first test case, a=[1,-3,-1,3] is one possible symmetric array that generates the array d=[8,12,8,12].In the second test case, it can be shown that there is no symmetric array consisting of distinct integers that can generate array d.
6 2 8 12 8 12 2 7 7 9 11 2 7 11 7 11 1 1 1 4 40 56 48 40 80 56 80 48 6 240 154 210 162 174 154 186 240 174 186 162 210
YES NO NO NO NO YES
2 seconds
512 megabytes
['implementation', 'math', 'sortings', '*1700']
B. Nezzar and Lucky Numbertime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputNezzar's favorite digit among 1,\ldots,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,\ldots,a_q, for each 1 \le i \le q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers.InputThe first line contains a single integer t (1 \le t \le 9) — the number of test cases.The first line of each test case contains two integers q and d (1 \le q \le 10^4, 1 \le d \le 9).The second line of each test case contains q integers a_1,a_2,\ldots,a_q (1 \le a_i \le 10^9).OutputFor each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO".You can print letters in any case (upper or lower).ExampleInput 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO NoteIn the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers.
2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60
YES NO YES YES YES NO YES YES YES YES YES YES NO
1 second
512 megabytes
['brute force', 'dp', 'greedy', 'math', '*1100']
A. Nezzar and Colorful Ballstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputNezzar has n balls, numbered with integers 1, 2, \ldots, n. Numbers a_1, a_2, \ldots, a_n are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that a_i \leq a_{i+1} for all 1 \leq i < n.Nezzar wants to color the balls using the minimum number of colors, such that the following holds. For any color, numbers on balls will form a strictly increasing sequence if he keeps balls with this chosen color and discards all other balls. Note that a sequence with the length at most 1 is considered as a strictly increasing sequence.Please help Nezzar determine the minimum number of colors.InputThe first line contains a single integer t (1 \le t \le 100) — the number of testcases. The first line of each test case contains a single integer n (1 \le n \le 100).The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le n). It is guaranteed that a_1 \leq a_2 \leq \ldots \leq a_n.OutputFor each test case, output the minimum number of colors Nezzar can use.ExampleInput 5 6 1 1 1 2 3 4 5 1 1 2 2 3 4 2 2 2 2 3 1 2 3 1 1 Output 3 2 4 1 1 NoteLet's match each color with some numbers. Then:In the first test case, one optimal color assignment is [1,2,3,3,2,1].In the second test case, one optimal color assignment is [1,2,1,2,1].
5 6 1 1 1 2 3 4 5 1 1 2 2 3 4 2 2 2 2 3 1 2 3 1 1
3 2 4 1 1
1 second
512 megabytes
['brute force', 'greedy', '*800']
F. Nezzar and Chocolate Barstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputNezzar buys his favorite snack — n chocolate bars with lengths l_1,l_2,\ldots,l_n. However, chocolate bars might be too long to store them properly! In order to solve this problem, Nezzar designs an interesting process to divide them into small pieces. Firstly, Nezzar puts all his chocolate bars into a black box. Then, he will perform the following operation repeatedly until the maximum length over all chocolate bars does not exceed k. Nezzar picks a chocolate bar from the box with probability proportional to its length x. After step 1, Nezzar uniformly picks a real number r \in (0,x) and divides the chosen chocolate bar into two chocolate bars with lengths r and x-r. Lastly, he puts those two new chocolate bars into the black box. Nezzar now wonders, what is the expected number of operations he will perform to divide his chocolate bars into small pieces.It can be shown that the answer can be represented as \frac{P}{Q}, where P and Q are coprime integers and Q \not \equiv 0 (\bmod 998\,244\,353). Print the value of P\cdot Q^{-1} \mod 998\,244\,353.InputThe first line contains two integers n and k (1 \le n \le 50, 1 \le k \le 2000).The second line contains n integers l_1, l_2, \ldots, l_n (1 \le l_i, \sum_{i=1}^{n} l_i \le 2000).OutputPrint a single integer — the expected number of operations Nezzar will perform to divide his chocolate bars into small pieces modulo 998\,244\,353.ExamplesInput 1 1 2 Output 4 Input 1 1 1 Output 0 Input 1 5 1234 Output 15630811 Input 2 1 2 3 Output 476014684 Input 10 33 10 20 30 40 50 60 70 80 90 100 Output 675105648
1 1 2
4
5 seconds
512 megabytes
['combinatorics', 'fft', 'math', 'probabilities', '*3500']
E. Nezzar and Tournamentstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn the famous Oh-Suit-United tournament, two teams are playing against each other for the grand prize of precious pepper points.The first team consists of n players, and the second team consists of m players. Each player has a potential: the potential of the i-th player in the first team is a_i, and the potential of the i-th player in the second team is b_i.In the tournament, all players will be on the stage in some order. There will be a scoring device, initially assigned to an integer k, which will be used to value the performance of all players.The scores for all players will be assigned in the order they appear on the stage. Let the potential of the current player be x, and the potential of the previous player be y (y equals x for the first player). Then, x-y is added to the value in the scoring device, Afterwards, if the value in the scoring device becomes negative, the value will be reset to 0. Lastly, the player's score is assigned to the current value on the scoring device. The score of a team is the sum of the scores of all its members.As an insane fan of the first team, Nezzar desperately wants the biggest win for the first team. He now wonders what is the maximum difference between scores of the first team and the second team.Formally, let the score of the first team be score_f and the score of the second team be score_s. Nezzar wants to find the maximum value of score_f - score_s over all possible orders of players on the stage.However, situation often changes and there are q events that will happen. There are three types of events: 1 pos x — change a_{pos} to x; 2 pos x — change b_{pos} to x; 3 x — tournament is held with k = x and Nezzar wants you to compute the maximum value of score_f - score_s. Can you help Nezzar to answer the queries of the third type?InputThe first line contains three integers n, m, and q (1 \le n,m \le 2 \cdot 10^5, 1 \le q \le 5 \cdot 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^6).The third line contains m integers b_1, b_2, \ldots, b_m (0 \le b_i \le 10^6).The following q lines contain descriptions of events, described in the statement, each in one of the three possible formats: 1 pos x (1 \le pos \le n, 0 \le x \le 10^6); 2 pos x (1 \le pos \le m, 0 \le x \le 10^6); 3 x (0 \le x \le 10^6). OutputFor each query of the third type print the answer to this query.ExamplesInput 3 4 3 1 2 7 3 4 5 6 3 5 1 1 10 3 5 Output -4 9 Input 7 8 12 958125 14018 215153 35195 90380 30535 204125 591020 930598 252577 333333 999942 1236 9456 82390 3 123458 2 4 444444 3 123456 1 2 355555 3 123478 3 1111 2 6 340324 3 1111 2 8 999999 2 7 595959 3 222222 3 100 Output 1361307 1361311 1702804 1879305 1821765 1078115 1675180 NoteIn the first query of the first test, the tournament is held with k = 5. It would be optimal to arrange players in such way (here their potentials are written):\underline{7}, 3, 5, 4, 6, \underline{1}, \underline{2} (underlined numbers are potentials of players that are from the first team). The individual scores of players, numbered in the order of their appearance, are: \max(5 + (7 - 7), 0) = 5 for the \underline{1}-st player; \max(5 + (3 - 7), 0) = 1 for the 2-nd player; \max(1 + (5 - 3), 0) = 3 for the 3-rd player; \max(3 + (4 - 5), 0) = 2 for the 4-th player; \max(2 + (6 - 4), 0) = 4 for the 5-th player; \max(4 + (1 - 6), 0) = 0 for the \underline{6}-th player; \max(0 + (2 - 1), 0) = 1 for the \underline{7}-th player. So, score_f = 5 + 0 + 1 = 6 and score_s = 1 + 3 + 2 + 4 = 10. The score difference is 6 - 10 = -4. It can be proven, that it is the maximum possible score difference.
3 4 3 1 2 7 3 4 5 6 3 5 1 1 10 3 5
-4 9
5 seconds
512 megabytes
['data structures', 'greedy', '*3300']
D. Nezzar and Hidden Permutationstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputNezzar designs a brand new game "Hidden Permutations" and shares it with his best friend, Nanako.At the beginning of the game, Nanako and Nezzar both know integers n and m. The game goes in the following way: Firstly, Nezzar hides two permutations p_1,p_2,\ldots,p_n and q_1,q_2,\ldots,q_n of integers from 1 to n, and Nanako secretly selects m unordered pairs (l_1,r_1),(l_2,r_2),\ldots,(l_m,r_m); After that, Nanako sends his chosen pairs to Nezzar; On receiving those m unordered pairs, Nezzar checks if there exists 1 \le i \le m, such that (p_{l_i}-p_{r_i}) and (q_{l_i}-q_{r_i}) have different signs. If so, Nezzar instantly loses the game and gets a score of -1. Otherwise, the score Nezzar gets is equal to the number of indices 1 \le i \le n such that p_i \neq q_i. However, Nezzar accidentally knows Nanako's unordered pairs and decides to take advantage of them. Please help Nezzar find out two permutations p and q such that the score is maximized.InputThe first line contains a single integer t (1 \le t \le 5 \cdot 10^5) — the number of test cases.The first line of each test case contains two integers n,m (1 \le n \le 5 \cdot 10^5, 0 \le m \le \min(\frac{n(n-1)}{2},5 \cdot 10^5)). Then m lines follow, i-th of them contains two integers l_i,r_i (1 \le l_i,r_i \le n, l_i \neq r_i), describing the i-th unordered pair Nanako chooses. It is guaranteed that all m unordered pairs are distinct.It is guaranteed that the sum of n for all test cases does not exceed 5 \cdot 10^5, and the sum of m for all test cases does not exceed 5\cdot 10^5.OutputFor each test case, print two permutations p_1,p_2,\ldots,p_n and q_1,q_2,\ldots,q_n such that the score Nezzar gets is maximized.ExampleInput 3 4 2 1 2 3 4 6 4 1 2 1 3 3 5 3 6 2 1 1 2 Output 1 2 3 4 3 4 1 2 2 3 4 1 6 5 1 4 3 2 5 6 1 2 1 2 NoteFor first test case, for each pair given by Nanako: for the first pair (1,2): p_1 - p_2 = 1 - 2 = -1, q_1 - q_2 = 3 - 4 = -1, they have the same sign; for the second pair (3,4): p_3 - p_4 = 3 - 4 = -1, q_3 - q_4 = 1 - 2 = -1, they have the same sign. As Nezzar does not lose instantly, Nezzar gains the score of 4 as p_i \neq q_i for all 1 \leq i \leq 4. Obviously, it is the maximum possible score Nezzar can get.
3 4 2 1 2 3 4 6 4 1 2 1 3 3 5 3 6 2 1 1 2
1 2 3 4 3 4 1 2 2 3 4 1 6 5 1 4 3 2 5 6 1 2 1 2
5 seconds
512 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', '*2800']
C. Nezzar and Nice Beatmaptime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputNezzar loves the game osu!.osu! is played on beatmaps, which can be seen as an array consisting of distinct points on a plane. A beatmap is called nice if for any three consecutive points A,B,C listed in order, the angle between these three points, centered at B, is strictly less than 90 degrees. Points A,B,C on the left have angle less than 90 degrees, so they can be three consecutive points of a nice beatmap; Points A',B',C' on the right have angle greater or equal to 90 degrees, so they cannot be three consecutive points of a nice beatmap. Now Nezzar has a beatmap of n distinct points A_1,A_2,\ldots,A_n. Nezzar would like to reorder these n points so that the resulting beatmap is nice.Formally, you are required to find a permutation p_1,p_2,\ldots,p_n of integers from 1 to n, such that beatmap A_{p_1},A_{p_2},\ldots,A_{p_n} is nice. If it is impossible, you should determine it.InputThe first line contains a single integer n (3 \le n \le 5000).Then n lines follow, i-th of them contains two integers x_i, y_i (-10^9 \le x_i, y_i \le 10^9) — coordinates of point A_i.It is guaranteed that all points are distinct.OutputIf there is no solution, print -1.Otherwise, print n integers, representing a valid permutation p.If there are multiple possible answers, you can print any.ExampleInput 5 0 0 5 0 4 2 2 1 3 0 Output 1 2 5 3 4 NoteHere is the illustration for the first test: Please note that the angle between A_1, A_2 and A_5, centered at A_2, is treated as 0 degrees. However, angle between A_1, A_5 and A_2, centered at A_5, is treated as 180 degrees.
5 0 0 5 0 4 2 2 1 3 0
1 2 5 3 4
2 seconds
512 megabytes
['constructive algorithms', 'geometry', 'greedy', 'math', 'sortings', '*2200']
B. Nezzar and Binary Stringtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputNezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.InputThe first line contains a single integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases.The first line of each test case contains two integers n,q (1 \le n \le 2 \cdot 10^5, 0 \le q \le 2 \cdot 10^5).The second line of each test case contains a binary string s of length n.The third line of each test case contains a binary string f of length n.Then q lines follow, i-th of them contains two integers l_i,r_i (1 \le l_i \le r_i \le n)  — bounds of the segment, that Nanako will inspect on the i-th day.It is guaranteed that the sum of n for all test cases doesn't exceed 2 \cdot 10^5, and the sum of q for all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInput 4 5 2 00000 00111 1 5 1 3 2 1 00 01 1 2 10 6 1111111111 0110001110 1 10 5 9 7 10 1 7 3 5 6 10 5 2 10000 11000 2 5 1 3 Output YES NO YES NO NoteIn the first test case, \underline{00000} \rightarrow \underline{000}11 \rightarrow 00111 is one of the possible sequences of string changes.In the second test case, it can be shown that it is impossible to have the string f at the end.
4 5 2 00000 00111 1 5 1 3 2 1 00 01 1 2 10 6 1111111111 0110001110 1 10 5 9 7 10 1 7 3 5 6 10 5 2 10000 11000 2 5 1 3
YES NO YES NO
2 seconds
512 megabytes
['data structures', 'greedy', '*1900']
A. Nezzar and Boardtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputn distinct integers x_1,x_2,\ldots,x_n are written on the board. Nezzar can perform the following operation multiple times. Select two integers x,y (not necessarily distinct) on the board, and write down 2x-y. Note that you don't remove selected numbers. Now, Nezzar wonders if it is possible to have his favorite number k on the board after applying above operation multiple times.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. The first line of each test case contains two integers n,k (2 \le n \le 2 \cdot 10^5, -10^{18} \le k \le 10^{18}).The second line of each test case contains n distinct integers x_1,x_2,\ldots,x_n (-10^{18} \le x_i \le 10^{18}).It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print "YES" on a single line if it is possible to have k on the board. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInput 6 2 1 1 2 3 0 2 3 7 2 -1 31415926 27182818 2 1000000000000000000 1 1000000000000000000 2 -1000000000000000000 -1000000000000000000 123 6 80 -5 -20 13 -14 -2 -11 Output YES YES NO YES YES NO NoteIn the first test case, the number 1 is already on the board.In the second test case, Nezzar could perform the following operations to write down k=0 on the board: Select x=3 and y=2 and write down 4 on the board. Select x=4 and y=7 and write down 1 on the board. Select x=1 and y=2 and write down 0 on the board. In the third test case, it is impossible to have the number k = -1 on the board.
6 2 1 1 2 3 0 2 3 7 2 -1 31415926 27182818 2 1000000000000000000 1 1000000000000000000 2 -1000000000000000000 -1000000000000000000 123 6 80 -5 -20 13 -14 -2 -11
YES YES NO YES YES NO
2 seconds
512 megabytes
['constructive algorithms', 'math', 'number theory', '*1800']