problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
C. Almost All Multiplestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven two integers n and x, a permutation^{\dagger} p of length n is called funny if p_i is a multiple of i for all 1 \leq i \leq n - 1, p_n = 1, and p_1 = x.Find the lexicographically minimal^{\ddagger} funny permutation, or report that no such permutation exists.^{\dagger} A permutation of length n is an array consisting of each of the integers from 1 to n exactly once.^{\ddagger} Let a and b be permutations of length n. Then a is lexicographically smaller than b if in the first position i where a and b differ, a_i < b_i. A permutation is lexicographically minimal if it is lexicographically smaller than all other permutations.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases. The description of the test cases follows.The only line of each test case contains two integers n and x (2 \leq n \leq 2 \cdot 10^5; 1 < x \leq n).The sum of n across all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, if the answer exists, output n distinct integers p_1, p_2, \dots, p_n (1 \leq p_i \leq n) — the lexicographically minimal funny permutation p. Otherwise, output -1.ExampleInput 33 34 25 4Output 3 2 1 2 4 3 1 -1 NoteIn the first test case, the permutation [3,2,1] satisfies all the conditions: p_1=3, p_3=1, and: p_1=3 is a multiple of 1. p_2=2 is a multiple of 2. In the second test case, the permutation [2,4,3,1] satisfies all the conditions: p_1=2, p_4=1, and: p_1=2 is a multiple of 1. p_2=4 is a multiple of 2. p_3=3 is a multiple of 3. We can show that these permutations are lexicographically minimal.No such permutations exist in the third test case.
33 34 25 4
3 2 1 2 4 3 1 -1
1 second
256 megabytes
['greedy', 'number theory', '*1400']
B. XOR = Averagetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n. Find a sequence of n integers a_1, a_2, \dots, a_n such that 1 \leq a_i \leq 10^9 for all i and a_1 \oplus a_2 \oplus \dots \oplus a_n = \frac{a_1 + a_2 + \dots + a_n}{n}, where \oplus represents the bitwise XOR.It can be proven that there exists a sequence of integers that satisfies all the conditions above.InputThe first line of input contains t (1 \leq t \leq 10^4) — the number of test cases.The first and only line of each test case contains one integer n (1 \leq n \leq 10^5) — the length of the sequence you have to find.The sum of n over all test cases does not exceed 10^5.OutputFor each test case, output n space-separated integers a_1, a_2, \dots, a_n satisfying the conditions in the statement. If there are several possible answers, you can output any of them.ExampleInput 3143Output 69 13 2 8 1 7 7 7 NoteIn the first test case, 69 = \frac{69}{1} = 69.In the second test case, 13 \oplus 2 \oplus 8 \oplus 1 = \frac{13 + 2 + 8 + 1}{4} = 6.
3143
69 13 2 8 1 7 7 7
1 second
256 megabytes
['constructive algorithms', '*900']
A. SSeeeeiinngg DDoouubblleetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA palindrome is a string that reads the same backward as forward. For example, the strings \texttt{z}, \texttt{aaa}, \texttt{aba}, and \texttt{abccba} are palindromes, but \texttt{codeforces} and \texttt{ab} are not.The double of a string s is obtained by writing each character twice. For example, the double of \texttt{seeing} is \texttt{sseeeeiinngg}.Given a string s, rearrange its double to form a palindrome. Output the rearranged string. It can be proven that such a rearrangement always exists.InputThe first line of input contains t (1 \leq t \leq 1000) — the number of test cases.The only line of each test case contains a single string s (1 \leq |s| \leq 100) consisting only of lowercase English letters.Note that the sum of |s| over all test cases is not bounded.OutputFor each test case, output a palindromic string of length 2 \cdot |s| that is a rearrangement of the double of s.ExampleInput 4asururuerrorgornanutforajaroftunaOutput aa suurruurruus rgnororerrerorongr aannuuttffoorraajjaarrooffttuunnaa NoteIn the first test case, the double of \texttt{a} is \texttt{aa}, which is already a palindrome.In the second test case, the double of \texttt{sururu} is \texttt{ssuurruurruu}. If we move the first \texttt{s} to the end, we get \texttt{suurruurruus}, which is a palindrome.In the third test case, the double of \texttt{errorgorn} is \texttt{eerrrroorrggoorrnn}. We can rearrange the characters to form \texttt{rgnororerrerorongr}, which is a palindrome.
4asururuerrorgornanutforajaroftuna
aa suurruurruus rgnororerrerorongr aannuuttffoorraajjaarrooffttuunnaa
1 second
256 megabytes
['constructive algorithms', 'strings', '*800']
B. Kevin and Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor his birthday, Kevin received the set of pairwise distinct numbers 1, 2, 3, \ldots, n as a gift.He is going to arrange these numbers in a way such that the minimum absolute difference between two consecutive numbers be maximum possible. More formally, if he arranges numbers in order p_1, p_2, \ldots, p_n, he wants to maximize the value \min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert, where |x| denotes the absolute value of x.Help Kevin to do that.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. Description of the test cases follows.The only line of each test case contains an integer n (2 \le n \leq 1\,000) — the size of the set.OutputFor each test case print a single line containing n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n) describing the arrangement that maximizes the minimum absolute difference of consecutive elements. Formally, you have to print a permutation p which maximizes the value \min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert.If there are multiple optimal solutions, print any of them.ExampleInput 243Output 2 4 1 3 1 2 3 NoteIn the first test case the minimum absolute difference of consecutive elements equals \min \{\lvert 4 - 2 \rvert, \lvert 1 - 4 \rvert, \lvert 3 - 1 \rvert \} = \min \{2, 3, 2\} = 2. It's easy to prove that this answer is optimal.In the second test case each permutation of numbers 1, 2, 3 is an optimal answer. The minimum absolute difference of consecutive elements equals to 1.
243
2 4 1 3 1 2 3
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*800']
A. Technical Supporttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved.Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by one or several messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions.Due to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. It is guaranteed that the dialog begins with the question of the client.You have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). Description of the test cases follows.The first line of each test case contains one integer n (1 \le n \le 100) — the total number of messages in the dialog.The second line of each test case consists of n characters "Q" and "A", describing types of messages in the dialog in chronological order. Character "Q" denotes the message with client question, and character "A" — the message with technical support manager answer. It is guaranteed that the first character in the line equals to "Q".OutputFor each test case print "Yes" (without quotes) if dialog may correspond to the rules of work, or "No" (without quotes) otherwise.ExampleInput 54QQAA4QQAQ3QAA1Q14QAQQAQAAQQQAAAOutput Yes No Yes No Yes NoteIn the first test case the two questions from the client are followed with two specialist's answers. So this dialog may correspond to the rules of work.In the second test case one of the first two questions was not answered.In the third test case the technical support manager sent two messaged as the answer to the only message of the client.
54QQAA4QQAQ3QAA1Q14QAQQAQAAQQQAAA
Yes No Yes No Yes
1 second
256 megabytes
['greedy', '*800']
F. Minecraft Seriestime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLittle Misha goes to the programming club and solves nothing there. It may seem strange, but when you find out that Misha is filming a Minecraft series, everything will fall into place...Misha is inspired by Manhattan, so he built a city in Minecraft that can be imagined as a table of size n \times m. k students live in a city, the i-th student lives in the house, located at the intersection of the x_i-th row and the y_i-th column. Also, each student has a degree of his aggressiveness w_i. Since the city turned out to be very large, Misha decided to territorially limit the actions of his series to some square s, which sides are parallel to the coordinate axes. The length of the side of the square should be an integer from 1 to \min(n, m) cells.According to the plot, the main hero will come to the city and accidentally fall into the square s. Possessing a unique degree of aggressiveness 0, he will be able to show his leadership qualities and assemble a team of calm, moderate and aggressive students.In order for the assembled team to be versatile and close-knit, degrees of aggressiveness of all students of the team must be pairwise distinct and must form a single segment of consecutive integers. Formally, if there exist students with degrees of aggressiveness l, l+1, \ldots, -1, 1, \ldots, r-1, r inside the square s, where l \le 0 \le r, the main hero will be able to form a team of r-l+1 people (of course, he is included in this team).Notice, that it is not required to take all students from square s to the team.Misha thinks that the team should consist of at least t people. That is why he is interested, how many squares are there in the table in which the main hero will be able to form a team of at least t people. Help him to calculate this.InputThe first line contains four integers n, m, k and t (1 \le n, m \le 40\,000, 1 \le n \cdot m \le 40\,000, 1 \le k \le 10^6, 1 \le t \le k + 1) — the number of rows and columns in the table, and the number of students living in the city, respectively.Each of the following k lines contains three integers x_i, y_i and w_i (1 \le x_i \le n, 1 \le y_i \le m, 1 \le \lvert w_i \rvert \le 10^9) — the number of row and column, where the i-th student is living, and the degree of his aggressiveness.OutputPrint one integer — the number of ways to choose the square s in such way that the main hero will be able to form a team of at least t people.ExamplesInput 2 2 1 2 1 1 2 Output 0 Input 2 2 2 2 1 1 1 2 2 2 Output 2 Input 2 2 4 2 1 1 1 1 1 -1 1 2 1 2 2 1 Output 4 Note In the first example the main hero will not be able to form a team of more than one person in any square s. Illustration for the first example. In the second example there are two ways to select square s. Both of them are illustrated below. In one of them the main hero will be able to form a team of students with degrees of aggressiveness [0, 1], and in the another — with degrees of aggressiveness [0, 1, 2]. Notice, that the main hero with degree of aggressiveness 0 will be included to the team regardless of the chosen square. Illustration for the second example. In the third example there are four ways to select square s. All of them are illustrated below. The main hero will be able to form a team with degrees of aggressiveness: [-1,0,1], [0,1], [0,1], [-1, 0, 1], respectively. Illustration for the third example.
2 2 1 2 1 1 2
0
6 seconds
512 megabytes
['brute force', 'two pointers', '*3500']
E. N Machinestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have been invited as a production process optimization specialist to some very large company. The company has n machines at its factory, standing one behind another in the production chain. Each machine can be described in one of the following two ways: (+,~a_i) or (*,~a_i).If a workpiece with the value x is supplied to the machine of kind (+,~a_i), then the output workpiece has value x + a_i.If a workpiece with the value x is supplied to the machine of kind (*,~a_i), then the output workpiece has value x \cdot a_i.The whole production process is as follows. The workpiece with the value 1 is supplied to the first machine, then the workpiece obtained after the operation of the first machine is supplied to the second machine, then the workpiece obtained after the operation of the second machine is supplied to the third machine, and so on. The company is not doing very well, so now the value of the resulting product does not exceed 2 \cdot 10^9.The directors of the company are not satisfied with the efficiency of the production process and have given you a budget of b coins to optimize it.To optimize production you can change the order of machines in the chain. Namely, by spending p coins, you can take any machine of kind (+,~a_i) and move it to any place in the chain without changing the order of other machines. Also, by spending m coins, you can take any machine of kind (*,~a_i) and move it to any place in the chain.What is the maximum value of the resulting product that can be achieved if the total cost of movements that are made should not exceed b coins?InputThe first line contains four integers n, b, p and m (1 \le n \le 10^6, 1 \le b, p, m \le 10^9) — the number of machine at the factory, your budget and costs of movements of both kinds of machines.Each of the following n lines contains description of a machine. The description begins with one of the following characters: "+" or "*", that denotes the kind of the machine. Then an integer a_i follows (1 \le a_i \le 2 \cdot 10^9).It's guaranteed that the current value of the resulting product does not exceed 2 \cdot 10^9.OutputPrint one integer — the maximum value of the resulting product that can be achieved if the total cost of movements that are made does not exceed b coins.ExamplesInput 3 2 1 3 * 2 + 1 + 1 Output 6 Input 4 2 2 2 * 2 + 1 * 3 + 2 Output 21 Input 8 2 1 1 * 2 + 1 * 4 + 1 + 1 + 1 * 5 + 3 Output 240 NoteIn the first example our budget is too low to move machine (*,~2), but we can move both machines (+,~1) to the beginning of the chain. So the final chain will be (+,~1) (+,~1) (*,~2). If the workpiece with the value 1 is supplied to the first machine, its value will be changed in the following way: 1, 2, 3, 6.In the second example we can move only one machine. Let's move machine (+,~2) to the beginning of the chain. The final chain will be (+,~2) (*,~2) (+,~1) (*,~3). The value of the workpiece will be changed in the following way: 1, 3, 6, 7, 21.In the third example we can place machine (*,~4) before the machine (*,~5), and move machine (+,~3) to the beginning of the chain. The final chain will be (+,~3) (*,~2) (+,~1) (+,~1) (+,~1) (+,~1) (*,~4) (*,~5). The value of the workpiece will be changed in the following way: 1, 4, 8, 9, 10, 11, 12, 48, 240.
3 2 1 3 * 2 + 1 + 1
6
1 second
256 megabytes
['binary search', 'brute force', 'greedy', '*3300']
D. The Beachtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrew loves the sea. That's why, at the height of the summer season, he decided to go to the beach, taking a sunbed with him to sunbathe.The beach is a rectangular field with n rows and m columns. Some cells of the beach are free, some have roads, stones, shops and other non-movable objects. Some of two adjacent along the side cells can have sunbeds located either horizontally or vertically.Andrew hopes to put his sunbed somewhere, but that's a bad luck, there may no longer be free places for him! That's why Andrew asked you to help him to find a free place for his sunbed. Andrew's sunbed also should be places on two adjacent cells. If there are no two adjacent free cells, then in order to free some place for a sunbed, you will have to disturb other tourists. You can do the following actions: Come to some sunbed and, after causing p units of discomfort to its owner, lift the sunbed by one of its sides and rotate it by 90 degrees. One half of the sunbed must remain in the same cell and another half of the sunbed must move to the free cell. At the same time, anything could be on the way of a sunbed during the rotation . Rotation of the sunbed by 90 degrees around cell (1, 2). Come to some sunbed and, after causing q units of discomfort to its owner, shift the sunbed along its long side by one cell. One half of the sunbed must move to the place of another, and another — to the free cell. Shift of the sunbed by one cell to the right. In any moment each sunbed occupies two adjacent free cells. You cannot move more than one sunbed at a time.Help Andrew to free a space for his sunbed, causing the minimum possible number of units of discomfort to other tourists, or detect that it is impossible.InputThe first line contains two integers n and m (1 \le n, m \le 300\,000, 1 \le n \cdot m \le 300\,000) — the number of rows and columns in rectangle.The second line contains two integers p and q (1 \le p, q \le 10^9) — the number of units of discomfort caused by rotation and shift of a sunbed, respectively.Each of the following n lines contains m characters, describing cells of the rectangle. Each lines consists of characters "L", "R", "D", "U", "." and "#", denoting the type of the cell. Characters "L", "R", "D" and "U" denote a half of a sunbed placed in the cell — left, right, bottom and top half, respectively. Character "." denotes a free cell and character "#" — a cell, occupied by some non-movable object.OutputPrint one integer — the minimum possible number of units of discomfort, caused to other tourists, to free a space for a sunbed. If it is impossible to free a space for a sunbed, print -1.ExamplesInput 2 55 2.LR####LR.Output 4 Input 2 34 5LR.#.#Output -1 Input 4 310 10.LR###UU#DD.Output -1 Input 3 610 7.U##.##DLR##.##LR.Output 24 NoteIn the first example we can shift upper sunbed to the left and lower sunbed — to the right. Andrew will be able to put his sunbed vertically in the middle of the beach. We well cause 2 + 2 = 4 units of discomfort. It is easy to prove that it is an optimal answer. Optimal strategy in the first example (Andrew's sunbed is colored white). In the second example it is impossible to free a space for Andrew's sunbed. All possible states of the beach after any rotates and shifts are illustrated in the problem statement.
2 55 2.LR####LR.
4
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'shortest paths', '*2400']
C. Wish I Knew How to Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary array a (all elements of the array are 0 or 1) of length n. You wish to sort this array, but unfortunately, your algorithms teacher forgot to teach you sorting algorithms. You perform the following operations until a is sorted: Choose two random indices i and j such that i < j. Indices are chosen equally probable among all pairs of indices (i, j) such that 1 \le i < j \le n. If a_i > a_j, then swap elements a_i and a_j. What is the expected number of such operations you will perform before the array becomes sorted?It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{998\,244\,353}. Output the integer equal to p \cdot q^{-1} \bmod 998\,244\,353. In other words, output such an integer x that 0 \le x < 998\,244\,353 and x \cdot q \equiv p \pmod{998\,244\,353}.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 200\,000) — the number of elements in the binary array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (a_i \in \{0, 1\}) — elements of the array.It's guaranteed that sum of n over all test cases does not exceed 200\,000.OutputFor each test case print one integer — the value p \cdot q^{-1} \bmod 998\,244\,353.ExampleInput 330 1 050 0 1 1 161 1 1 0 0 1Output 3 0 249561107 NoteConsider the first test case. If the pair of indices (2, 3) will be chosen, these elements will be swapped and array will become sorted. Otherwise, if one of pairs (1, 2) or (1, 3) will be selected, nothing will happen. So, the probability that the array will become sorted after one operation is \frac{1}{3}, the probability that the array will become sorted after two operations is \frac{2}{3} \cdot \frac{1}{3}, the probability that the array will become sorted after three operations is \frac{2}{3} \cdot \frac{2}{3} \cdot \frac{1}{3} and so on. The expected number of operations is \sum \limits_{i=1}^{\infty} \left(\frac{2}{3} \right)^{i - 1} \cdot \frac{1}{3} \cdot i = 3.In the second test case the array is already sorted so the expected number of operations is zero.In the third test case the expected number of operations equals to \frac{75}{4} so the answer is 75 \cdot 4^{-1} \equiv 249\,561\,107 \pmod {998\,244\,353}.
330 1 050 0 1 1 161 1 1 0 0 1
3 0 249561107
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*2000']
B. Factorial Divisibilitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer x and an array of integers a_1, a_2, \ldots, a_n. You have to determine if the number a_1! + a_2! + \ldots + a_n! is divisible by x!.Here k! is a factorial of k — the product of all positive integers less than or equal to k. For example, 3! = 1 \cdot 2 \cdot 3 = 6, and 5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120.InputThe first line contains two integers n and x (1 \le n \le 500\,000, 1 \le x \le 500\,000).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le x) — elements of given array.OutputIn the only line print "Yes" (without quotes) if a_1! + a_2! + \ldots + a_n! is divisible by x!, and "No" (without quotes) otherwise.ExamplesInput 6 4 3 2 2 2 3 3 Output Yes Input 8 3 3 2 2 2 2 2 1 1 Output Yes Input 7 8 7 7 7 7 7 7 7 Output No Input 10 5 4 3 2 1 4 3 2 4 3 4 Output No Input 2 500000 499999 499999 Output No NoteIn the first example 3! + 2! + 2! + 2! + 3! + 3! = 6 + 2 + 2 + 2 + 6 + 6 = 24. Number 24 is divisible by 4! = 24.In the second example 3! + 2! + 2! + 2! + 2! + 2! + 1! + 1! = 18, is divisible by 3! = 6.In the third example 7! + 7! + 7! + 7! + 7! + 7! + 7! = 7 \cdot 7!. It is easy to prove that this number is not divisible by 8!.
6 4 3 2 2 2 3 3
Yes
2 seconds
256 megabytes
['math', 'number theory', '*1600']
A2. Make Nonzero Sum (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference is that in this version the array contains zeros. You can make hacks only if both versions of the problem are solved.You are given an array [a_1, a_2, \ldots a_n] consisting of integers -1, 0 and 1. You have to build a partition of this array into the set of segments [l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k] with the following property: Denote the alternating sum of all elements of the i-th segment as s_i: s_i = a_{l_i} - a_{l_i+1} + a_{l_i+2} - a_{l_i+3} + \ldots \pm a_{r_i}. For example, the alternating sum of elements of segment [2, 4] in array [1, 0, -1, 1, 1] equals to 0 - (-1) + 1 = 2. The sum of s_i over all segments of partition should be equal to zero. Note that each s_i does not have to be equal to zero, this property is about sum of s_i over all segments of partition.The set of segments [l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k] is called a partition of the array a of length n if 1 = l_1 \le r_1, l_2 \le r_2, \ldots, l_k \le r_k = n and r_i + 1 = l_{i+1} for all i = 1, 2, \ldots k-1. In other words, each element of the array must belong to exactly one segment.You have to build a partition of the given array with properties described above or determine that such partition does not exist.Note that it is not required to minimize the number of segments in the partition.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 an integer n (1 \le n \le 200\,000) — the length of array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (a_i is -1, 0, or 1) — the elements of the given array.It's guaranteed that the sum of n over all test cases does not exceed 200\,000.OutputFor each test case print an integer k — the number of segments in the partition. If required partition does not exist, print -1.If partition exists, in the i-th of the following k lines print two integers l_i and r_i — description of the i-th segment. The following conditions should be satisfied: l_i \le r_i for each i from 1 to k. l_{i + 1} = r_i + 1 for each i from 1 to (k - 1). l_1 = 1, r_k = n. If there are multiple correct partitions of the array, print any of them.ExampleInput 540 0 0 07-1 1 0 1 0 1 050 -1 1 0 131 0 111Output 4 1 1 2 2 3 3 4 4 4 1 1 2 2 3 5 6 7 -1 2 1 1 2 3 -1 NoteIn the first test case we can build a partition of 4 segments — each of them will contain only one element of the array equals to 0. So the sum will be equal to 0 + 0 + 0 + 0 = 0.In the second test case we can build a partition of 4 segments. The alternating sum of the first segment will be equal to -1, the alternating sum of the second segment will be equal to 1, of the third segment — 0 - 1 + 0 = -1, of the fourth segment — 1 - 0 = 1. The sum will be equal to -1 + 1 -1 + 1 = 0.In the third test case it can be proved that the required partition does not exist.
540 0 0 07-1 1 0 1 0 1 050 -1 1 0 131 0 111
4 1 1 2 2 3 3 4 4 4 1 1 2 2 3 5 6 7 -1 2 1 1 2 3 -1
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*1500']
A1. Make Nonzero Sum (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference is that in this version the array can not contain zeros. You can make hacks only if both versions of the problem are solved.You are given an array [a_1, a_2, \ldots a_n] consisting of integers -1 and 1. You have to build a partition of this array into the set of segments [l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k] with the following property: Denote the alternating sum of all elements of the i-th segment as s_i: s_i = a_{l_i} - a_{l_i+1} + a_{l_i+2} - a_{l_i+3} + \ldots \pm a_{r_i}. For example, the alternating sum of elements of segment [2, 4] in array [1, 0, -1, 1, 1] equals to 0 - (-1) + 1 = 2. The sum of s_i over all segments of partition should be equal to zero. Note that each s_i does not have to be equal to zero, this property is about sum of s_i over all segments of partition.The set of segments [l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k] is called a partition of the array a of length n if 1 = l_1 \le r_1, l_2 \le r_2, \ldots, l_k \le r_k = n and r_i + 1 = l_{i+1} for all i = 1, 2, \ldots k-1. In other words, each element of the array must belong to exactly one segment.You have to build a partition of the given array with properties described above or determine that such partition does not exist.Note that it is not required to minimize the number of segments in the partition.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 an integer n (1 \le n \le 200\,000) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (a_i is -1 or 1) — the elements of the given array.It's guaranteed that the sum of n over all test cases does not exceed 200\,000.OutputFor each test case, if required partition does not exist, print -1. Otherwise, print an integer k — the number of segments in the partition. Then in the i-th of the following k lines print two integers l_i and r_i — description of the i-th segment. The following conditions should be satisfied: l_i \le r_i for each i from 1 to k. l_{i + 1} = r_i + 1 for each i from 1 to (k - 1). l_1 = 1, r_k = n. If there are multiple correct partitions of the array, print any of them.ExampleInput 441 1 1 16-1 1 1 1 1 131 -1 111Output 1 1 4 2 1 3 4 6 -1 -1 NoteIn the first test case we can build a partition of one segment of length 4. The sum of this segment will be equal to 1 - 1 + 1 - 1 = 0.In the second test case we can build a partition of two segments of length 3. The sum of the first segment will be equal to -1 -1 + 1 = -1, and the sum of the second segment: 1 - 1 + 1 = 1. So, the total sum will be equal to -1 + 1 = 0.In the third and in the fourth test cases it can be proved that there are no required partition.
441 1 1 16-1 1 1 1 1 131 -1 111
1 1 4 2 1 3 4 6 -1 -1
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*1300']
H. BinaryStringForcestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s of length n. We define a maximal substring as a substring that cannot be extended while keeping all elements equal. For example, in the string 11000111 there are three maximal substrings: 11, 000 and 111.In one operation, you can select two maximal adjacent substrings. Since they are maximal and adjacent, it's easy to see their elements must have different values. Let a be the length of the sequence of ones and b be the length of the sequence of zeros. Then do the following: If a \ge b, then replace b selected zeros with b ones. If a < b, then replace a selected ones with a zeros.As an example, for 1110000 we make it 0000000, for 0011 we make it 1111. We call a string being good if it can be turned into 1111...1111 using the aforementioned operation any number of times (possibly, zero). Find the number of good substrings among all \frac{n(n+1)}{2} non-empty substrings of s.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The description of test cases follows.The first line of each test case contains n (1 \le n \le 2 \cdot 10^5) — the length of the string s.The second line of each test case contains the binary string s of length n. It is guaranteed that sum of n across all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the number of good substrings.ExampleInput 4610001131015111116010101Output 8 5 15 18 NoteLet's define a substring from index l to index r as [l, r].For the first test case, the good substrings are: [1,1], [1,2], [3,6], [4,5], [4,6], [5,5], [5,6], [6,6]. In the second test case, all substrings are good except [2,2].In the third test case, all substrings are good.
4610001131015111116010101
8 5 15 18
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'dp', '*3500']
G. Dopingtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe call an array a of length n fancy if for each 1 < i \le n it holds that a_i = a_{i-1} + 1.Let's call f(p) applied to a permutation^\dagger of length n as the minimum number of subarrays it can be partitioned such that each one of them is fancy. For example f([1,2,3]) = 1, while f([3,1,2]) = 2 and f([3,2,1]) = 3.Given n and a permutation p of length n, we define a permutation p' of length n to be k-special if and only if: p' is lexicographically smaller^\ddagger than p, and f(p') = k. Your task is to count for each 1 \le k \le n the number of k-special permutations modulo m.^\dagger A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).^\ddagger A permutation a of length n is lexicographically smaller than a permutation b of length n if and only if the following holds: in the first position where a and b differ, the permutation a has a smaller element than the corresponding element in b.InputThe first line contains two integers n and m (1 \le n \le 2000, 10 \le m \le 10^9) — the length of the permutation and the required modulo.The second line contains n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n) — the permutation p.OutputPrint n integers, where the k-th integer is the number of k-special permutations modulo m.ExamplesInput 4 666012 1 3 4 2 Output 1 0 1 1 Input 3 10 3 2 1 Output 1 2 2 Input 7 1000000000 7 2 1 3 5 4 6 Output 1 6 40 201 705 1635 1854 Input 10 11 10 9 8 7 6 5 4 3 2 1 Output 1 9 9 0 1 5 5 0 1 0 NoteIn the first example, the permutations that are lexicographically smaller than [1,3,4,2] are: [1,2,3,4], f([1,2,3,4])=1; [1,2,4,3], f([1,2,4,3])=3; [1,3,2,4], f([1,3,2,4])=4. Thus our answer is [1,0,1,1].In the second example, the permutations that are lexicographically smaller than [3,2,1] are: [1,2,3], f([1,2,3])=1; [1,3,2], f([1,3,2])=3; [2,1,3], f([2,1,3])=3; [2,3,1], f([2,3,1])=2; [3,1,2], f([3,1,2])=2. Thus our answer is [1,2,2].
4 666012 1 3 4 2
1 0 1 1
3 seconds
512 megabytes
['combinatorics', 'dp', 'math', '*3300']
F. Majoritytime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputEveryone was happy coding, until suddenly a power shortage happened and the best competitive programming site went down. Fortunately, a system administrator bought some new equipment recently, including some UPSs. Thus there are some servers that are still online, but we need all of them to be working in order to keep the round rated.Imagine the servers being a binary string s of length n. If the i-th server is online, then s_i = 1, and s_i = 0 otherwise.A system administrator can do the following operation called electricity spread, that consists of the following phases: Select two servers at positions 1 \le i < j \le n such that both are online (i.e. s_i=s_j=1). The spread starts only from online servers. Check if we have enough power to make the spread. We consider having enough power if the number of turned on servers in range [i, j] is at least the number of turned off servers in range [i, j]. More formally, check whether 2 \cdot (s_i + s_{i+1} + \ldots + s_j) \ge j - i + 1. If the check is positive, turn on all the offline servers in range [i, j]. More formally, make s_k := 1 for all k from i to j. We call a binary string s of length n rated if we can turn on all servers (i.e. make s_i = 1 for 1 \le i \le n) using the electricity spread operation any number of times (possibly, 0). Your task is to find the number of rated strings of length n modulo m.InputThe first and only line contains two integers n and m (1 \le n \le 5000, 10 \le m \le 10^9) — the length of the string and the required module.OutputPrint a single integer — the number of rated binary strings of length n. Since this number can be large, print it modulo m.ExamplesInput 2 100 Output 1Input 3 10 Output 2Input 4 3271890 Output 4Input 17 123456 Output 32347NoteIn the first example, the only rated string is 11. So the answer is 1.In the second example, the rated strings are: 111; 101, because we can perform an operation with i = 1 and j = 3. So the answer is 2.In the third sample, the rated strings are: 1001; 1111; 1011; 1101. So the answer is 4.
2 100
1
2 seconds
1024 megabytes
['combinatorics', 'dp', 'math', 'strings', '*2700']
E. Bracket Costtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDaemon Targaryen decided to stop looking like a Metin2 character. He turned himself into the most beautiful thing, a bracket sequence.For a bracket sequence, we can do two kind of operations: Select one of its substrings^\dagger and cyclic shift it to the right. For example, after a cyclic shift to the right, "(())" will become ")(()"; Insert any bracket, opening '(' or closing ')', wherever you want in the sequence. We define the cost of a bracket sequence as the minimum number of such operations to make it balanced^\ddagger.Given a bracket sequence s of length n, find the sum of costs across all its \frac{n(n+1)}{2} non-empty substrings. Note that for each substring we calculate the cost independently.^\dagger 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.^\ddagger A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences "(())()", "()", and "(()(()))" are balanced, while ")(", "(()", and "(()))(" are not.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the bracket sequence.The second line of each test case contains a string s, consisting only of characters '(' and ')', of length n — the bracket sequence.It is guaranteed that sum of n across all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the sum of costs of all substrings of s.ExampleInput 51)4)()(3())5(((((10)(())))())Output 1 9 6 35 112 NoteIn the first test case, there is the only substring ")". Its cost is 1 because we can insert '(' to the beginning of this substring and get a string "()", that is a balanced string.In the second test case, the cost of each substring of length one is 1. The cost of a substring ")(" is 1 because we can cyclically shift it to right and get a string "()". The cost of strings ")()" and "()(" is 1 because its enough to insert one bracket to each of them. The cost of substring ")()(" is 1 because we can cyclically shift it to right and get a string "()()". So there are 4 + 2 + 2 + 1 = 9 substring of cost 1 and 1 substring of cost 0. So the sum of the costs is 9.In the third test case, "(", the cost is 1; "()", the cost is 0; "())", the cost is 1; ")", the cost is 1; "))", the cost is 2; ")", the cost is 1. So the sum of the costs is 6.
51)4)()(3())5(((((10)(())))())
1 9 6 35 112
2 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'dp', 'greedy', 'strings', '*2400']
D. Count GCDtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and m and an array a of n integers. For each 1 \le i \le n it holds that 1 \le a_i \le m.Your task is to count the number of different arrays b of length n such that: 1 \le b_i \le m for each 1 \le i \le n, and \gcd(b_1,b_2,b_3,...,b_i) = a_i for each 1 \le i \le n. Here \gcd(a_1,a_2,\dots,a_i) denotes the greatest common divisor (GCD) of integers a_1,a_2,\ldots,a_i.Since this number can be too large, print it modulo 998\,244\,353.InputEach test consist of multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and m (1 \le n \le 2 \cdot 10^5, 1 \le m \le 10^9) — the length of the array a and the maximum possible value of the element.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le m) — the elements of the array a.It is guaranteed that the sum of n across all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the number of different arrays satisfying the conditions above. Since this number can be large, print it modulo 998\,244\,353.ExampleInput 53 54 2 12 11 15 502 3 5 2 34 100000000060 30 1 12 10000000001000000000 2Output 3 1 0 595458194 200000000 NoteIn the first test case, the possible arrays b are: [4,2,1]; [4,2,3]; [4,2,5]. In the second test case, the only array satisfying the demands is [1,1].In the third test case, it can be proven no such array exists.
53 54 2 12 11 15 502 3 5 2 34 100000000060 30 1 12 10000000001000000000 2
3 1 0 595458194 200000000
2 seconds
256 megabytes
['combinatorics', 'math', 'number theory', '*1800']
C. Complementary XORtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have two binary strings a and b of length n. You would like to make all the elements of both strings equal to 0. Unfortunately, you can modify the contents of these strings using only the following operation: You choose two indices l and r (1 \le l \le r \le n); For every i that respects l \le i \le r, change a_i to the opposite. That is, a_i := 1 - a_i; For every i that respects either 1 \le i < l or r < i \le n, change b_i to the opposite. That is, b_i := 1 - b_i. Your task is to determine if this is possible, and if it is, to find such an appropriate chain of operations. The number of operations should not exceed n + 5. It can be proven that if such chain of operations exists, one exists with at most n + 5 operations. InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the length of the strings.The second line of each test case contains a binary string a, consisting only of characters 0 and 1, of length n.The third line of each test case contains a binary string b, consisting only of characters 0 and 1, of length n.It is guaranteed that sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print first "YES" if it's possible to make all the elements of both strings equal to 0. Otherwise, print "NO". If the answer is "YES", on the next line print a single integer k (0 \le k \le n + 5) — the number of operations. Then k lines follows, each contains two integers l and r (1 \le l \le r \le n) — the description of the operation.If there are several correct answers, print any of them.ExampleInput 5301010121110410000011210103111111Output YES 1 2 2 NO NO YES 2 1 2 2 2 YES 2 1 1 2 3NoteIn the first test case, we can perform one operation with l = 2 and r = 2. So a_2 := 1 - 1 = 0 and string a became equal to 000. b_1 := 1 - 1 = 0, b_3 := 1 - 1 = 0 and string b became equal to 000.In the second and in the third test cases, it can be proven that it's impossible to make all elements of both strings equal to 0.In the fourth test case, we can perform an operation with l = 1 and r = 2, then string a became equal to 01, and string b doesn't change. Then we perform an operation with l = 2 and r = 2, then a_2 := 1 - 1 = 0 and b_1 = 1 - 1 = 0. So both of string a and b became equal to 00.In the fifth test case, we can perform an operation with l = 1 and r = 1. Then string a became equal to 011 and string b became equal to 100. Then we can perform an operation with l = 2 and r = 3, so both of string a and b became equal to 000.
5301010121110410000011210103111111
YES 1 2 2 NO NO YES 2 1 2 2 2 YES 2 1 1 2 3
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1400']
B. Maximum Substringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA binary string is a string consisting only of the characters 0 and 1. You are given a binary string s.For some non-empty substring^\dagger t of string s containing x characters 0 and y characters 1, define its cost as: x \cdot y, if x > 0 and y > 0; x^2, if x > 0 and y = 0; y^2, if x = 0 and y > 0. Given a binary string s of length n, find the maximum cost across all its non-empty substrings.^\dagger 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.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the string s.The second line of each test case contains a binary string s of length n.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the maximum cost across all substrings.ExampleInput 6511100711001106011110710010104100010Output 9 12 16 12 9 1 NoteIn the first test case, we can take a substring 111. It contains 3 characters 1 and 0 characters 0. So a = 3, b = 0 and its cost is 3^2 = 9.In the second test case, we can take the whole string. It contains 4 characters 1 and 3 characters 0. So a = 4, b = 3 and its cost is 4 \cdot 3 = 12.In the third test case, we can can take a substring 1111 and its cost is 4^2 = 16.In the fourth test case, we can take the whole string and cost is 4 \cdot 3 = 12.In the fifth test case, we can take a substring 000 and its cost is 3 \cdot 3 = 9.In the sixth test case, we can only take the substring 0 and its cost is 1 \cdot 1 = 1.
6511100711001106011110710010104100010
9 12 16 12 9 1
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*800']
A. Indirect Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation a_1, a_2, \ldots, a_n of size n, where each integer from 1 to n appears exactly once.You can do the following operation any number of times (possibly, zero): Choose any three indices i, j, k (1 \le i < j < k \le n). If a_i > a_k, replace a_i with a_i + a_j. Otherwise, swap a_j and a_k. Determine whether you can make the array a sorted in non-descending order.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 5000) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (3 \le n \le 10) — the length of the array a.The second line contains n integers a_1,a_2,\dots,a_n (1 \le a_i \le n, a_i \neq a_j if i \neq j) — the elements of the array a.OutputFor each test case, output "Yes" (without quotes) if the array can be sorted in non-descending order, and "No" (without quotes) otherwise.You can output "Yes" and "No" in any case (for example, strings "YES", "yEs" and "yes" will be recognized as a positive response).ExampleInput 731 2 331 3 275 3 4 7 6 2 177 6 5 4 3 2 152 1 4 5 352 1 3 4 571 2 6 7 4 3 5Output Yes Yes No No No No Yes NoteIn the first test case, [1,2,3] is already sorted in non-descending order.In the second test case, we can choose i = 1,j = 2,k = 3. Since a_1 \le a_3, swap a_2 and a_3, the array then becomes [1,2,3], which is sorted in non-descending order.In the seventh test case, we can do the following operations successively: Choose i = 5,j = 6,k = 7. Since a_5 \le a_7, swap a_6 and a_7, the array then becomes [1,2,6,7,4,5,3]. Choose i = 5,j = 6,k = 7. Since a_5 > a_7, replace a_5 with a_5+a_6=9, the array then becomes [1,2,6,7,9,5,3]. Choose i = 2,j = 5,k = 7. Since a_2 \le a_7, swap a_5 and a_7, the array then becomes [1,2,6,7,3,5,9]. Choose i = 2,j = 4,k = 6. Since a_2 \le a_6, swap a_4 and a_6, the array then becomes [1,2,6,5,3,7,9]. Choose i = 1,j = 3,k = 5. Since a_1 \le a_5, swap a_3 and a_5, the array then becomes [1,2,3,5,6,7,9], which is sorted in non-descending order. In the third, the fourth, the fifth and the sixth test cases, it can be shown that the array cannot be sorted in non-descending order.
731 2 331 3 275 3 4 7 6 2 177 6 5 4 3 2 152 1 4 5 352 1 3 4 571 2 6 7 4 3 5
Yes Yes No No No No Yes
1 second
256 megabytes
['constructive algorithms', 'implementation', 'math', '*800']
F. Distance to the Pathtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. Initially, each vertex has a value 0.You need to perform m queries of two types: You are given a vertex index v. Print the value of the vertex v. You are given two vertex indices u and v and values k and d (d \le 20). You need to add k to the value of each vertex such that the distance from that vertex to the path from u to v is less than or equal to d. The distance between two vertices x and y is equal to the number of edges on the path from x to y. For example, the distance from x to x itself is equal to 0.The distance from the vertex v to some path from x to y is equal to the minimum among distances from v to any vertex on the path from x to y.InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.Next n - 1 lines contain the edges of the tree — one per line. Each line contains two integers u and v (1 \le u, v \le n; u \neq v) representing one edge of the tree. It's guaranteed that the given edges form a tree.The next line contains a single integer m (1 \le m \le 2 \cdot 10^5) — the number of queries.Next m lines contain the queries — one per line. Each query has one of the following two types: 1 v (1 \le v \le n) — the query of the first type; 2 u v k d (1 \le u, v \le n; 1 \le k \le 1000; 0 \le d \le 20) — the query of the second type. Additional constraint on the input: there is at least one query of the first type.OutputFor each query of the first type, print the value of the corresponding vertex.ExampleInput 6 1 2 1 3 4 2 5 2 3 6 14 2 4 5 10 2 1 3 1 6 2 1 1 10 20 2 6 6 10 20 1 3 2 3 2 10 0 2 5 2 10 1 1 1 1 2 1 3 1 4 1 5 1 6 Output 10 0 30 50 50 40 40 40 20 NoteThe tree from the first example: Some query explanations: "2 4 5 10 2": affected vertices are \{4, 2, 5, 1, 3\}; "2 1 1 10 20" and "2 6 6 10 20": all vertices are affected, since distance to 1 (6) is less that 20 for any vertex; "2 3 2 10 0": affected vertices are \{3, 1, 2\}; "2 5 2 10 1": affected vertices are \{5, 2, 4, 1\}.
6 1 2 1 3 4 2 5 2 3 6 14 2 4 5 10 2 1 3 1 6 2 1 1 10 20 2 6 6 10 20 1 3 2 3 2 10 0 2 5 2 10 1 1 1 1 2 1 3 1 4 1 5 1 6
10 0 30 50 50 40 40 40 20
4 seconds
512 megabytes
['data structures', 'dfs and similar', 'trees', '*2800']
E. Cactus Walltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing Minecraft and wants to build a wall of cacti. He wants to build it on a field of sand of the size of n \times m cells. Initially, there are cacti in some cells of the field. Note that, in Minecraft, cacti cannot grow on cells adjacent to each other by side — and the initial field meets this restriction. Monocarp can plant new cacti (they must also fulfil the aforementioned condition). He can't chop down any of the cacti that are already growing on the field — he doesn't have an axe, and the cacti are too prickly for his hands.Monocarp believes that the wall is complete if there is no path from the top row of the field to the bottom row, such that: each two consecutive cells in the path are adjacent by side; no cell belonging to the path contains a cactus. Your task is to plant the minimum number of cacti to build a wall (or to report that this is impossible).InputThe first line contains a single integer t (1 \le t \le 10^3) — number of test cases.The first line of each test case contains two integers n and m (2 \le n, m \le 2 \cdot 10^5; n \times m \le 4 \cdot 10^5) — the number of rows and columns, respectively.Then n rows follow, i-th row contains a string s_i of length m, where s_{i, j} is '#', if a cactus grows at the intersection of the i-th row and the j-th column. Otherwise, s_{i, j} is '.'.The sum of n \times m over all test cases does not exceed 4 \cdot 10^5.OutputFor each test case, print NO in the first line if it is impossible to build a cactus wall without breaking the rules. Otherwise, print YES in the first line, then print n lines of m characters each — the field itself, where the j-th character of the i-th line is equal to '#', if there is a cactus on the intersection of the i-th row and the j-th column, otherwise it is '.'. If there are multiple optimal answers, print any of them.ExampleInput 42 4.#....#.3 3#.#....#.5 5.........................4 3#...#.#.#...Output YES .#.# #.#. NO YES ....# ...#. ..#.. .#... #.... YES #.. .#. #.# ...
42 4.#....#.3 3#.#....#.5 5.........................4 3#...#.#.#...
YES .#.# #.#. NO YES ....# ...#. ..#.. .#... #.... YES #.. .#. #.# ...
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'shortest paths', '*2400']
D. Counting Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider an array a of length n with elements numbered from 1 to n. It is possible to remove the i-th element of a if gcd(a_i, i) = 1, where gcd denotes the greatest common divisor. After an element is removed, the elements to the right are shifted to the left by one position.An array b with n integers such that 1 \le b_i \le n - i + 1 is a removal sequence for the array a if it is possible to remove all elements of a, if you remove the b_1-th element, then the b_2-th, ..., then the b_n-th element. For example, let a = [42, 314]: [1, 1] is a removal sequence: when you remove the 1-st element of the array, the condition gcd(42, 1) = 1 holds, and the array becomes [314]; when you remove the 1-st element again, the condition gcd(314, 1) = 1 holds, and the array becomes empty. [2, 1] is not a removal sequence: when you try to remove the 2-nd element, the condition gcd(314, 2) = 1 is false. An array is ambiguous if it has at least two removal sequences. For example, the array [1, 2, 5] is ambiguous: it has removal sequences [3, 1, 1] and [1, 2, 1]. The array [42, 314] is not ambiguous: the only removal sequence it has is [1, 1].You are given two integers n and m. You have to calculate the number of ambiguous arrays a such that the length of a is from 1 to n and each a_i is an integer from 1 to m.InputThe only line of the input contains two integers n and m (2 \le n \le 3 \cdot 10^5; 1 \le m \le 10^{12}).OutputPrint one integer — the number of ambiguous arrays a such that the length of a is from 1 to n and each a_i is an integer from 1 to m. Since the answer can be very large, print it modulo 998244353.ExamplesInput 2 3 Output 6 Input 4 2 Output 26 Input 4 6 Output 1494 Input 1337 424242424242 Output 119112628
2 3
6
2 seconds
512 megabytes
['combinatorics', 'dp', 'math', 'number theory', '*1900']
C. Number Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game. They have an array of positive integers a of size n.Before starting the game, Alice chooses an integer k \ge 0. The game lasts for k stages, the stages are numbered from 1 to k. During the i-th stage, Alice must remove an element from the array that is less than or equal to k - i + 1. After that, if the array is not empty, Bob must add k - i + 1 to an arbitrary element of the array. Note that both Alice's move and Bob's move are two parts of the same stage of the game. If Alice can't delete an element during some stage, she loses. If the k-th stage ends and Alice hasn't lost yet, she wins.Your task is to determine the maximum value of k such that Alice can win if both players play optimally. Bob plays against Alice, so he tries to make her lose the game, if it's possible.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 100) — the size of the array a.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n).OutputFor each test case, print one integer — the maximum value of k such that Alice can win if both players play optimally.ExampleInput 431 1 244 4 4 41151 3 2 1 1Output 2 0 1 3
431 1 244 4 4 41151 3 2 1 1
2 0 1 3
2 seconds
256 megabytes
['binary search', 'data structures', 'games', 'greedy', 'implementation', '*1400']
B. Death's Blessingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a computer game. To pass the current level, you have to kill a big horde of monsters. In this horde, there are n monsters standing in the row, numbered from 1 to n. The i-th monster has a_i health and a special "Death's Blessing" spell of strength b_i attached to it.You are going to kill all of them one by one. It takes exactly h seconds to kill a monster with health h.When the i-th monster dies, it casts its spell that increases the health of its neighbors by b_i (the neighbors of the j-th monster in the row are the monsters on places j - 1 and j + 1. The first and the last monsters have only one neighbor each).After each monster is killed, the row shrinks, so its former neighbors become adjacent to each other (so if one of them dies, the other one is affected by its spell). For example, imagine a situation with 4 monsters with health a = [2, 6, 7, 3] and spells b = [3, 6, 0, 5]. One of the ways to get rid of the monsters is shown below: 2673\xrightarrow{6\ s}8133\xrightarrow{13\ s}83\xrightarrow{8\ s}6\xrightarrow{6\ s}\{\}3605305355 The first row represents the health of each monster, the second one — the power of the spells. As a result, we can kill all monsters in 6 + 13 + 8 + 6 = 33 seconds. Note that it's only an example and may not be the fastest way to get rid of the monsters.What is the minimum time required to kill all monsters in the row?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 number of monsters in the row.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the initial health of corresponding monsters.The third line contains n integers b_1, b_2, \dots, b_n (0 \le b_i \le 10^9), where b_i is the strength of the spell for the i-th monster.It's guaranteed that the sum of n doesn't exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the minimum possible total time to kill all monsters.ExampleInput 411003100 1 1001 100 142 6 7 33 6 0 521000000000 10000000001000000000 1000000000Output 10 203 26 3000000000 NoteIn the first test case, there is only one monster that will be killed in 10 seconds.In the second test case, it's optimal to kill the first monster, the last monster and then the middle one. It will take 100 + 100 + (1 + 1 + 1) = 203 seconds.In the third test case, it's optimal to kill the first monster, then the third one, then the fourth one and finally the second one. It will take 2 + 7 + (3 + 0) + (3 + 6 + 5) = 26 seconds.
411003100 1 1001 100 142 6 7 33 6 0 521000000000 10000000001000000000 1000000000
10 203 26 3000000000
2 seconds
256 megabytes
['greedy', '*900']
A. Cowardly Rookstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere's a chessboard of size n \times n. m rooks are placed on it in such a way that: no two rooks occupy the same cell; no two rooks attack each other. A rook attacks all cells that are in its row or column.Is it possible to move exactly one rook (you can choose which one to move) into a different cell so that no two rooks still attack each other? A rook can move into any cell in its row or column if no other rook stands on its path.InputThe first line contains a single integer t (1 \le t \le 2000) — the number of testcases.The first line of each testcase contains two integers n and m (1 \le n, m \le 8) — the size of the chessboard and the number of the rooks.The i-th of the next m lines contains two integers x_i and y_i (1 \le x_i, y_i \le n) — the position of the i-th rook: x_i is the row and y_i is the column.No two rooks occupy the same cell. No two rooks attack each other.OutputFor each testcase, print "YES" if it's possible to move exactly one rook into a different cell so that no two rooks still attack each other. Otherwise, print "NO".ExampleInput 22 21 22 13 12 2Output NO YES NoteIn the first testcase, the rooks are in the opposite corners of a 2 \times 2 board. Each of them has a move into a neighbouring corner, but moving there means getting attacked by another rook.In the second testcase, there's a single rook in a middle of a 3 \times 3 board. It has 4 valid moves, and every move is fine because there's no other rook to attack it.
22 21 22 13 12 2
NO YES
2 seconds
256 megabytes
['greedy', 'implementation', '*800']
F. Circular Xor Reversaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a_0, a_1, \ldots, a_{n-1} of length n. Initially, a_i = 2^i for all 0 \le i \lt n. Note that array a is zero-indexed. You want to reverse this array (that is, make a_i equal to 2^{n-1-i} for all 0 \le i \lt n). To do this, you can perform the following operation no more than 250\,000 times: Select an integer i (0 \le i \lt n) and replace a_i by a_i \oplus a_{(i+1)\bmod n}. Here, \oplus denotes the bitwise XOR operation.Your task is to find any sequence of operations that will result in the array a being reversed. It can be shown that under the given constraints, a solution always exists.InputThe first line contains a single integer n (2 \le n \le 400) — the length of the array a.OutputOn the first line print one integer k (0 \le k \le 250\,000) — the number of operations performed.On the second line print k integers i_1,i_2,\ldots,i_k (0 \le i_j \lt n). Here, i_j should be the integer selected on the j-th operation.Note that you don't need to minimize the number of operations.ExamplesInput 2 Output 3 1 0 1 Input 3 Output 9 1 0 1 0 2 1 0 1 0 NoteIn the notes, the elements on which the operations are performed are colored red.In the first test case, array a will change in the following way: [1,\color{red}{2}] \rightarrow [\color{red}{1},3] \rightarrow [2,\color{red}{3}] \rightarrow [2,1].In the second test case, array a will change in the following way:[1,\color{red}{2},4] \rightarrow [\color{red}{1},6,4] \rightarrow [7,\color{red}{6},4] \rightarrow [\color{red}{7},2,4] \rightarrow [5,2,\color{red}{4}] \rightarrow [5,\color{red}{2},1] \rightarrow [\color{red}{5},3,1] \rightarrow [6,\color{red}{3},1] \rightarrow [\color{red}{6},2,1] \rightarrow [4,2,1].
2
3 1 0 1
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', '*3000']
E. Yet Another Array Counting Problemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe position of the leftmost maximum on the segment [l; r] of array x = [x_1, x_2, \ldots, x_n] is the smallest integer i such that l \le i \le r and x_i = \max(x_l, x_{l+1}, \ldots, x_r).You are given an array a = [a_1, a_2, \ldots, a_n] of length n. Find the number of integer arrays b = [b_1, b_2, \ldots, b_n] of length n that satisfy the following conditions: 1 \le b_i \le m for all 1 \le i \le n; for all pairs of integers 1 \le l \le r \le n, the position of the leftmost maximum on the segment [l; r] of the array b is equal to the position of the leftmost maximum on the segment [l; r] of the array a. Since the answer might be very large, print its remainder modulo 10^9+7.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^3) — the number of test cases.The first line of each test case contains two integers n and m (2 \le n,m \le 2 \cdot 10^5, n \cdot m \le 10^6).The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le m) — the array a.It is guaranteed that the sum of n \cdot m over all test cases doesn't exceed 10^6.OutputFor each test case print one integer — the number of arrays b that satisfy the conditions from the statement, modulo 10^9+7.ExampleInput 43 31 3 24 22 2 2 26 96 9 6 9 6 99 10010 40 20 20 100 60 80 60 60Output 8 5 11880 351025663 NoteIn the first test case, the following 8 arrays satisfy the conditions from the statement: [1,2,1]; [1,2,2]; [1,3,1]; [1,3,2]; [1,3,3]; [2,3,1]; [2,3,2]; [2,3,3]. In the second test case, the following 5 arrays satisfy the conditions from the statement: [1,1,1,1]; [2,1,1,1]; [2,2,1,1]; [2,2,2,1]; [2,2,2,2].
43 31 3 24 22 2 2 26 96 9 6 9 6 99 10010 40 20 20 100 60 80 60 60
8 5 11880 351025663
2 seconds
512 megabytes
['binary search', 'data structures', 'divide and conquer', 'dp', 'flows', 'math', 'trees', '*2300']
D. ConstructOR time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a, b, and d. Your task is to find any integer x which satisfies all of the following conditions, or determine that no such integers exist: 0 \le x \lt 2^{60}; a|x is divisible by d; b|x is divisible by d. Here, | denotes the bitwise OR operation.InputEach test contains multiple test cases. The first line of input contains one integer t (1 \le t \le 10^4) — the number of test cases. Each test case consists of one line, containing three integers a, b, and d (1 \le a,b,d \lt 2^{30}).OutputFor each test case print one integer. If there exists an integer x which satisfies all of the conditions from the statement, print x. Otherwise, print -1.If there are multiple solutions, you may print any of them. ExampleInput 812 39 56 8 14100 200 2003 4 62 2 218 27 3420 666 69987654321 123456789 999999999Output 18 14 -1 -1 0 11 25599 184470016815529983NoteIn the first test case, x=18 is one of the possible solutions, since 39|18=55 and 12|18=30, both of which are multiples of d=5.In the second test case, x=14 is one of the possible solutions, since 8|14=6|14=14, which is a multiple of d=14.In the third and fourth test cases, we can show that there are no solutions.
812 39 56 8 14100 200 2003 4 62 2 218 27 3420 666 69987654321 123456789 999999999
18 14 -1 -1 0 11 25599 184470016815529983
2 seconds
256 megabytes
['bitmasks', 'chinese remainder theorem', 'combinatorics', 'constructive algorithms', 'math', 'number theory', '*2100']
C. Zero-Sum Prefixestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe score of an array v_1,v_2,\ldots,v_n is defined as the number of indices i (1 \le i \le n) such that v_1+v_2+\ldots+v_i = 0.You are given an array a_1,a_2,\ldots,a_n of length n. You can perform the following operation multiple times: select an index i (1 \le i \le n) such that a_i=0; then replace a_i by an arbitrary integer. What is the maximum possible score of a that can be obtained by performing a sequence of such operations?InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains 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 (-10^9 \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, print the maximum possible score of the array a after performing a sequence of operations.ExampleInput 552 0 1 -1 031000000000 1000000000 040 0 0 083 0 2 -10 10 -30 30 091 0 0 1 -1 0 1 0 -1Output 3 1 4 4 5 NoteIn the first test case, it is optimal to change the value of a_2 to -2 in one operation.The resulting array a will be [2,-2,1,-1,0], with a score of 3: a_1+a_2=2-2=0; a_1+a_2+a_3+a_4=2-2+1-1=0; a_1+a_2+a_3+a_4+a_5=2-2+1-1+0=0. In the second test case, it is optimal to change the value of a_3 to -2\,000\,000\,000, giving us an array with a score of 1.In the third test case, it is not necessary to perform any operations.
552 0 1 -1 031000000000 1000000000 040 0 0 083 0 2 -10 10 -30 30 091 0 0 1 -1 0 1 0 -1
3 1 4 4 5
1 second
256 megabytes
['brute force', 'data structures', 'dp', 'greedy', 'implementation', '*1600']
B. Diverse Substringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA non-empty digit string is diverse if the number of occurrences of each character in it doesn't exceed the number of distinct characters in it.For example: string "7" is diverse because 7 appears in it 1 time and the number of distinct characters in it is 1; string "77" is not diverse because 7 appears in it 2 times and the number of distinct characters in it is 1; string "1010" is diverse because both 0 and 1 appear in it 2 times and the number of distinct characters in it is 2; string "6668" is not diverse because 6 appears in it 3 times and the number of distinct characters in it is 2. You are given a string s of length n, consisting of only digits 0 to 9. Find how many of its \frac{n(n+1)}{2} substrings are diverse.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.Note that if the same diverse string appears in s multiple times, each occurrence should be counted independently. For example, there are two diverse substrings in "77" both equal to "7", so the answer for the string "77" is 2.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the length of the string s.The second line of each test case contains a string s of length n. It is guaranteed that all characters of s are digits from 0 to 9.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print one integer — the number of diverse substrings of the given string s. ExampleInput 71727741010501100639999652345618789987887987998798Output 1 2 10 12 10 15 106 NoteIn the first test case, the diverse substring is "7".In the second test case, the only diverse substring is "7", which appears twice, so the answer is 2.In the third test case, the diverse substrings are "0" (2 times), "01", "010", "1" (2 times), "10" (2 times), "101" and "1010".In the fourth test case, the diverse substrings are "0" (3 times), "01", "011", "0110", "1" (2 times), "10", "100", "110" and "1100".In the fifth test case, the diverse substrings are "3", "39", "399", "6", "9" (4 times), "96" and "996".In the sixth test case, all 15 non-empty substrings of "23456" are diverse.
71727741010501100639999652345618789987887987998798
1 2 10 12 10 15 106
1 second
256 megabytes
['brute force', 'implementation', 'strings', '*1400']
A. The Ultimate Squaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n rectangular wooden blocks, which are numbered from 1 to n. The i-th block is 1 unit high and \lceil \frac{i}{2} \rceil units long.Here, \lceil \frac{x}{2} \rceil denotes the result of division of x by 2, rounded up. For example, \lceil \frac{4}{2} \rceil = 2 and \lceil \frac{5}{2} \rceil = \lceil 2.5 \rceil = 3.For example, if n=5, then the blocks have the following sizes: 1 \times 1, 1 \times 1, 1 \times 2, 1 \times 2, 1 \times 3. The available blocks for n=5 Find the maximum possible side length of a square you can create using these blocks, without rotating any of them. Note that you don't have to use all of the blocks. One of the ways to create 3 \times 3 square using blocks 1 through 5 InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^9) — the number of blocks.OutputFor each test case, print one integer — the maximum possible side length of a square you can create.ExampleInput 325197654321Output 1 3 98827161 NoteIn the first test case, you can create a 1 \times 1 square using only one of the blocks.In the second test case, one of the possible ways to create a 3 \times 3 square is shown in the statement. It is impossible to create a 4 \times 4 or larger square, so the answer is 3.
325197654321
1 3 98827161
1 second
256 megabytes
['math', '*800']
E. List Generationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor given integers n and m, let's call a pair of arrays a and b of integers good, if they satisfy the following conditions: a and b have the same length, let their length be k. k \ge 2 and a_1 = 0, a_k = n, b_1 = 0, b_k = m. For each 1 < i \le k the following holds: a_i \geq a_{i - 1}, b_i \geq b_{i - 1}, and a_i + b_i \neq a_{i - 1} + b_{i - 1}.Find the sum of |a| over all good pairs of arrays (a,b). Since the answer can be very large, output it modulo 10^9 + 7.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4)  — the number of test cases. The description of the test cases follows.The only line of each test case contains two integers n and m (1 \leq n, m \leq 5 \cdot 10^6).It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^6 and the sum of m over all test cases does not exceed 5 \cdot 10^6.OutputFor each test case, output a single integer  — the sum of |a| over all good pairs of arrays (a,b) modulo 10^9 + 7.ExampleInput 41 11 22 2100 100Output 8 26 101 886336572 NoteIn the first testcase, the good pairs of arrays are ([0, 1], [0, 1]), length = 2. ([0, 1, 1], [0, 0, 1]), length = 3. ([0, 0, 1], [0, 1, 1]), length = 3. Hence the sum of the lengths would be {2 + 3 + 3} = 8.
41 11 22 2100 100
8 26 101 886336572
1 second
256 megabytes
['combinatorics', 'dp', 'math', '*2900']
D. Yet Another Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers a_1, a_2, a_3, \ldots, a_n.You have to answer q independent queries, each consisting of two integers l and r. Consider the subarray a[l:r] = [a_l, a_{l+1}, \ldots, a_r]. You can apply the following operation to the subarray any number of times (possibly zero)- Choose two integers L, R such that l \le L \le R \le r and R - L + 1 is odd. Replace each element in the subarray from L to R with the XOR of the elements in the subarray [L, R]. The answer to the query is the minimum number of operations required to make all elements of the subarray a[l:r] equal to 0 or -1 if it is impossible to make all of them equal to 0. You can find more details about XOR operation here.InputThe first line contains two integers n and q (1 \le n, q \le 2 \cdot 10^5)  — the length of the array a and the number of queries.The next line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \lt 2^{30})  — the elements of the array a.The i-th of the next q lines contains two integers l_i and r_i (1 \le l_i \le r_i \le n)  — the description of the i-th query.OutputFor each query, output a single integer  — the answer to that query.ExampleInput 7 6 3 0 3 3 1 2 3 3 4 4 6 3 7 5 6 1 6 2 2 Output -1 1 1 -1 2 0 NoteIn the first query, l = 3, r = 4, subarray = [3, 3]. We can apply operation only to the subarrays of length 1, which won't change the array; hence it is impossible to make all elements equal to 0.In the second query, l = 4, r = 6, subarray = [3, 1, 2]. We can choose the whole subarray (L = 4, R = 6) and replace all elements by their XOR (3 \oplus 1 \oplus 2) = 0, making the subarray [0, 0, 0].In the fifth query, l = 1, r = 6, subarray = [3, 0, 3, 3, 1, 2]. We can make the operations as follows: Choose L = 4, R = 6, making the subarray [3, 0, 3, 0, 0, 0]. Choose L = 1, R = 5, making the subarray [0, 0, 0, 0, 0, 0].
7 6 3 0 3 3 1 2 3 3 4 4 6 3 7 5 6 1 6 2 2
-1 1 1 -1 2 0
1 second
256 megabytes
['binary search', 'bitmasks', 'constructive algorithms', 'data structures', '*1900']
C. Swap Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game on an array a of n positive integers. Alice and Bob make alternating moves with Alice going first.In his/her turn, the player makes the following move: If a_1 = 0, the player loses the game, otherwise: Player chooses some i with 2\le i \le n. Then player decreases the value of a_1 by 1 and swaps a_1 with a_i. Determine the winner of the game if both players play optimally.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 2 \cdot 10^4)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 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 \leq a_i \leq 10^9)  — the elements of the array a.It is guaranteed that sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, if Alice will win the game, output "Alice". Otherwise, output "Bob".You can output each letter in any case. For example, "alIcE", "Alice", "alice" will all be considered identical.ExampleInput 321 122 135 4 4Output Bob Alice Alice NoteIn the first testcase, in her turn, Alice can only choose i = 2, making the array equal [1, 0]. Then Bob, in his turn, will also choose i = 2 and make the array equal [0, 0]. As a_1 = 0, Alice loses.In the second testcase, once again, players can only choose i = 2. Then the array will change as follows: [2, 1] \to [1, 1] \to [1, 0] \to [0, 0], and Bob loses.In the third testcase, we can show that Alice has a winning strategy.
321 122 135 4 4
Bob Alice Alice
1 second
256 megabytes
['games', '*1200']
B. BAN BANtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n.Let's define s(n) as the string "BAN" concatenated n times. For example, s(1) = "BAN", s(3) = "BANBANBAN". Note that the length of the string s(n) is equal to 3n.Consider s(n). You can perform the following operation on s(n) any number of times (possibly zero): Select any two distinct indices i and j (1 \leq i, j \leq 3n, i \ne j). Then, swap s(n)_i and s(n)_j. You want the string "BAN" to not appear in s(n) as a subsequence. What's the smallest number of operations you have to do to achieve this? Also, find one such shortest sequence of operations.A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 100)  — the number of test cases. The description of the test cases follows.The only line of each test case contains a single integer n (1 \leq n \leq 100).OutputFor each test case, in the first line output m (0 \le m \le 10^5) — the minimum number of operations required. It's guaranteed that the objective is always achievable in at most 10^5 operations under the constraints of the problem. Then, output m lines. The k-th of these lines should contain two integers i_k, j_k (1\leq i_k, j_k \leq 3n, i_k \ne j_k) denoting that you want to swap characters at indices i_k and j_k at the k-th operation. After all m operations, "BAN" must not appear in s(n) as a subsequence. If there are multiple possible answers, output any.ExampleInput 2 1 2 Output 1 1 2 1 2 6 NoteIn the first testcase, s(1) = "BAN", we can swap s(1)_1 and s(1)_2, converting s(1) to "ABN", which does not contain "BAN" as a subsequence.In the second testcase, s(2) = "BANBAN", we can swap s(2)_2 and s(2)_6, converting s(2) to "BNNBAA", which does not contain "BAN" as a subsequence.
2 1 2
1 1 2 1 2 6
1 second
256 megabytes
['constructive algorithms', '*900']
A. Two Groupstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. You want to distribute these n integers into two groups s_1 and s_2 (groups can be empty) so that the following conditions are satisfied: For each i (1 \leq i \leq n), a_i goes into exactly one group. The value |sum(s_1)| - |sum(s_2)| is the maximum possible among all such ways to distribute the integers.Here sum(s_1) denotes the sum of the numbers in the group s_1, and sum(s_2) denotes the sum of the numbers in the group s_2.Determine the maximum possible value of |sum(s_1)| - |sum(s_2)|.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 2 \cdot 10^4)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 10^5)  — the length of the array a.The second line of each test case contains n integers a_1,a_2 \ldots a_n (-10^9 \leq a_i \leq 10^9)  — elements of the 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 a single integer  — the maximum possible value of |sum(s_1)| - |sum(s_2)|.ExampleInput 4210 -104-2 -1 11 032 3 25-9 2 0 0 -4Output 0 8 7 11 NoteIn the first testcase, we can distribute as s_1 = \{10\}, s_2 = \{-10\}. Then the value will be |10| - |-10| = 0.In the second testcase, we can distribute as s_1 = \{0, 11, -1\}, s_2 = \{-2\}. Then the value will be |0 + 11 - 1| - |-2| = 10 - 2 = 8.In the third testcase, we can distribute as s_1 = \{2, 3, 2\}, s_2 = \{\}. Then the value will be |2 + 3 + 2| - |0| = 7.In the fourth testcase, we can distribute as s_1 = \{-9, -4, 0\}, s_2 = \{2, 0\}. Then the value will be |-9 - 4 + 0| - |2 + 0| = 13 - 2 = 11.
4210 -104-2 -1 11 032 3 25-9 2 0 0 -4
0 8 7 11
1 second
256 megabytes
['constructive algorithms', 'greedy', '*800']
G. Olympiad Trainingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton decided to get ready for an Olympiad in Informatics. Ilya prepared n tasks for him to solve. It is possible to submit the solution for the i-th task in the first d_{i} days only. Anton cannot solve more than one task a day. Ilya estimated the usefulness of the i-th tasks as r_{i} and divided the tasks into three topics, the topic of the i-th task is type_{i}.Anton wants to solve exactly a tasks on the first topic, b tasks on the second topic and c tasks on the third topic. Tell Anton if it is possible to do so, and if it is, calculate the maximum total usefulness of the tasks he may solve.InputThe first line of input contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains four integers n, a, b, c (1 \le n \le 10^5, 0 \le a, b, c \le n).The following n lines contain three integers each — r_i, type_i, d_i (0 \le r_i \le 10^{9}, 1 \le type_i \le 3, 1 \le d_i \le n).The sum of n over all test cases does not exceed 10^5.OutputFor each test case print -1 if Anton cannot reach his goal; otherwise, print the maximum usefulness of the tasks he will solve.ExampleInput 44 1 1 01 2 11 1 10 1 21 2 23 1 1 11 1 27 2 19 3 24 2 1 0100 2 15 2 37 1 25 1 25 1 1 110 3 19 2 320 1 116 1 41 3 4Output 2 -1 17 35 NoteIn the first test case from the sample test Anton can solve tasks 2 and 4.In the second test case from the sample test it is impossible to fulfill Anton's wish.In the third test case from the sample test it is optimal to solve tasks 2, 3 and 4.In the last test case from the sample test it is optimal to solve tasks 1, 2 and 4.
44 1 1 01 2 11 1 10 1 21 2 23 1 1 11 1 27 2 19 3 24 2 1 0100 2 15 2 37 1 25 1 25 1 1 110 3 19 2 320 1 116 1 41 3 4
2 -1 17 35
1 second
256 megabytes
['binary search', 'data structures', 'dp', 'flows', 'geometry', 'implementation', 'sortings', '*3500']
F. Kazaeetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a consisting of n positive integers and you have to handle q queries of the following types: 1 i x: change a_{i} to x, 2 l r k: check if the number of occurrences of every positive integer in the subarray a_{l}, a_{l+1}, \ldots a_{r} is a multiple of k (check the example for better understanding). InputThe first line of the input contains two integers n and q (1 \le n , q \le 3 \cdot 10^5), the length of a and the number of queries.Next line contains n integers a_{1}, a_{2}, \ldots a_{n} (1 \le a_{i} \le 10^9) — the elements of a.Each of the next q lines describes a query. It has one of the following forms. 1 i x, (1 \le i \le n , 1 \le x \le 10^9), or 2 l r k, (1 \le l \le r \le n , 1 \le k \le n). OutputFor each query of the second type, if answer of the query is yes, print "YES", otherwise print "NO".ExampleInput10 81234 2 3 3 2 1 1 2 3 42 1 6 21 1 12 1 6 22 1 9 21 10 52 1 9 31 3 52 3 10 2OutputNOYESNOYESYESNoteIn the first query, requested subarray is [1234, 2, 3, 3, 2, 1], and it's obvious that the number of occurrence of 1 isn't divisible by k = 2. So the answer is "NO".In the third query, requested subarray is [1, 2, 3, 3, 2, 1], and it can be seen that the number of occurrence of every integer in this sub array is divisible by k = 2. So the answer is "YES".In the sixth query, requested subarray is [1, 2, 3, 3, 2, 1, 1, 2, 3], and it can be seen that the number of occurrence of every integer in this sub array is divisible by k = 3. So the answer is "YES".
Input10 81234 2 3 3 2 1 1 2 3 42 1 6 21 1 12 1 6 22 1 9 21 10 52 1 9 31 3 52 3 10 2
OutputNOYESNOYESYES
3 seconds
256 megabytes
['data structures', 'hashing', 'probabilities', '*2800']
E2. Joking (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and the hard version is the maximum number of questions.This is an interactive problem.There is a hidden integer 1 \le x \le n which you have to find. In order to find it you can ask at most \mathbf{53} questions.In each question you can choose a non-empty integer set S and ask if x belongs to S or not, after each question, if x belongs to S, you'll receive "YES", otherwise "NO".But the problem is that not all answers are necessarily true (some of them are joking), it's just guaranteed that for each two consecutive questions, at least one of them is answered correctly.Additionally to the questions, you can make at most 2 guesses for the answer x. Each time you make a guess, if you guess x correctly, you receive ":)" and your program should terminate, otherwise you'll receive ":(".As a part of the joking, we will not fix the value of x in the beginning. Instead, it can change throughout the interaction as long as all the previous responses are valid as described above.Note that your answer guesses are always answered correctly. If you ask a question before and after a guess, at least one of these two questions is answered correctly, as normal.InputThe only line of the input contains a single integer n (1 \le n \le 10^5), the maximum possible value of x.InteractionFor each question, if you want to ask about a set S, first print the character '?', then print the size of S and then print the elements of S one by one. Each element should be an integer between 1 and n, the elements must be distinct. After each question, read a string "YES" or "NO", as explained in the statement. You can make at most 53 such questions.If you want to guess for x, first print the character '!' and then print your guess. After each guess, read ":)" or ":(". If you guess x correctly, the answer is ":)" and your program should terminate immediately, otherwise you'll receive ":(". You can make at most 2 such guesses.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. Hacking is not allowed in this problem.ExampleInput6NO:(NO:)Output? 5 1 2 5 4 3! 6? 4 1 2 3 4! 5NoteIf the answer of the first question were correct, then x would have been equal to 6, but as we can see in the first guess, 6 is not the answer.So the answer of the first question is joking. As we know, the answer of at least one of our two questions is correct, since the answer of the first question was joking, the answer of the second question should be correct.So we will understand that x is not equal to 1, 2, 3 or 4, and we also knew that x is not equal to 6 either. Hence x should be equal to 5.
Input6NO:(NO:)
Output? 5 1 2 5 4 3! 6? 4 1 2 3 4! 5
1 second
256 megabytes
['dp', 'interactive', '*3200']
E1. Joking (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and the hard version is the maximum number of questions.This is an interactive problem.There is a hidden integer 1 \le x \le n which you have to find. In order to find it you can ask at most \mathbf{82} questions.In each question you can choose a non-empty integer set S and ask if x belongs to S or not, after each question, if x belongs to S, you'll receive "YES", otherwise "NO".But the problem is that not all answers are necessarily true (some of them are joking), it's just guaranteed that for each two consecutive questions, at least one of them is answered correctly.Additionally to the questions, you can make at most 2 guesses for the answer x. Each time you make a guess, if you guess x correctly, you receive ":)" and your program should terminate, otherwise you'll receive ":(".As a part of the joking, we will not fix the value of x in the beginning. Instead, it can change throughout the interaction as long as all the previous responses are valid as described above.Note that your answer guesses are always answered correctly. If you ask a question before and after a guess, at least one of these two questions is answered correctly, as normal.InputThe only line of the input contains a single integer n (1 \le n \le 10^5), the maximum possible value of x.InteractionFor each question, if you want to ask about a set S, first print the character '?', then print the size of S and then print the elements of S one by one. Each element should be an integer between 1 and n, the elements must be distinct. After each question, read a string "YES" or "NO", as explained in the statement. You can make at most 82 such questions.If you want to guess for x, first print the character '!' and then print your guess. After each guess, read ":)" or ":(". If you guess x correctly, the answer is ":)" and your program should terminate immediately, otherwise you'll receive ":(". You can make at most 2 such guesses.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. Hacking is not allowed in this problem.ExampleInput6NO:(NO:)Output? 5 1 2 5 4 3! 6? 4 1 2 3 4! 5NoteIf the answer of the first question were correct, then x would have been equal to 6, but as we can see in the first guess, 6 is not the answer.So the answer of the first question is joking. As we know, the answer of at least one of our two questions is correct, since the answer of the first question was joking, the answer of the second question should be correct.So we will understand that x is not equal to 1, 2, 3 or 4, and we also knew that x is not equal to 6 either. Hence x should be equal to 5.
Input6NO:(NO:)
Output? 5 1 2 5 4 3! 6? 4 1 2 3 4! 5
1 second
256 megabytes
['binary search', 'constructive algorithms', 'interactive', 'ternary search', '*2500']
D. Paths on the Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree consisting of n vertices. The vertices are numbered from 1 to n, and the root is the vertex 1. You are also given a score array s_1, s_2, \ldots, s_n.A multiset of k simple paths is called valid if the following two conditions are both true. Each path starts from 1. Let c_i be the number of paths covering vertex i. For each pair of vertices (u,v) (2\le u,v\le n) that have the same parent, |c_u-c_v|\le 1 holds. The value of the path multiset is defined as \sum\limits_{i=1}^n c_i s_i.It can be shown that it is always possible to find at least one valid multiset. Find the maximum value among all valid multisets.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains two space-separated integers n (2 \le n \le 2 \cdot 10^5) and k (1 \le k \le 10^9) — the size of the tree and the required number of paths.The second line contains n - 1 space-separated integers p_2,p_3,\ldots,p_n (1\le p_i\le n), where p_i is the parent of the i-th vertex. It is guaranteed that this value describe a valid tree with root 1.The third line contains n space-separated integers s_1,s_2,\ldots,s_n (0 \le s_i \le 10^4) — the scores of the vertices.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10 ^ 5.OutputFor each test case, print a single integer — the maximum value of a path multiset.ExampleInput 25 41 2 1 36 2 1 5 75 31 2 1 36 6 1 4 10Output 54 56 NoteIn the first test case, one of optimal solutions is four paths 1 \to 2 \to 3 \to 5, 1 \to 2 \to 3 \to 5, 1 \to 4, 1 \to 4, here c=[4,2,2,2,2]. The value equals to 4\cdot 6+ 2\cdot 2+2\cdot 1+2\cdot 5+2\cdot 7=54.In the second test case, one of optimal solution is three paths 1 \to 2 \to 3 \to 5, 1 \to 2 \to 3 \to 5, 1 \to 4, here c=[3,2,2,1,2]. The value equals to 3\cdot 6+ 2\cdot 6+2\cdot 1+1\cdot 4+2\cdot 10=56.
25 41 2 1 36 2 1 5 75 31 2 1 36 6 1 4 10
54 56
3 seconds
256 megabytes
['dfs and similar', 'dp', 'greedy', 'sortings', 'trees', '*1900']
C. Permutation Operationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation a of size n and you should perform n operations on it. In the i-th operation, you can choose a non-empty suffix of a and increase all of its elements by i. How can we perform the operations to minimize the number of inversions in the final array?Note that you can perform operations on the same suffix any number of times you want.A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. A suffix is several consecutive elements of an array that include the last element of the array. An inversion in an array a is a pair of indices (i, j) such that i > j and a_{i} < a_{j}.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). 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 size of the array.The second line contains n distinct integers a_{1}, a_{2}, \dots, a_{n} (1 \le a_i \le n), the initial permutation a.It's guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print n integers x_{1}, x_{2}, \ldots, x_{n} (1 \le x_{i} \le n for each 1 \le i \le n) indicating that the i-th operation must be applied to the suffix starting at index x_{i}. If there are multiple answers, print any of them.ExampleInput 441 2 3 451 3 2 4 532 3 111Output 1 1 1 1 1 4 3 2 1 1 3 3 1NoteIn the first test case one of the optimal solutions is to increase the whole array on each operation (that is, choose the suffix starting at index 1). The final array [11, 12, 13, 14] contains 0 inversions.In the second test case, a will be equal to [2, 4, 3, 5, 6], [2, 4, 3, 7, 8], [2, 4, 6, 10, 11], [2, 8, 10, 14, 15] and [7, 13, 15, 19, 20] after the first, second, third, fourth, and fifth operations, respectively. So the final array a has zero inversions.
441 2 3 451 3 2 4 532 3 111
1 1 1 1 1 4 3 2 1 1 3 3 1
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*1300']
B. Rebelliontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a of size n consisting only of zeroes and ones. You can do the following operation: choose two indices 1 \le i , j \le n, i \ne j, add a_{i} to a_{j}, remove a_{i} from a. Note that elements of a can become bigger than 1 after performing some operations. Also note that n becomes 1 less after the operation.What is the minimum number of operations needed to make a non-decreasing, i. e. that each element is not less than the previous element?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 10^5), the size of array a.Next line contains n integers a_{1}, a_{2}, \ldots a_{n} (a_i is 0 or 1), elements of array a.It's guaranteed that sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case print a single integer, minimum number of operations needed to make a non-decreasing.ExampleInput 480 0 1 1 1 1 1 151 0 0 1 121 0111 1 0 0 1 0 0 1 1 1 0Output 0 1 1 3 NoteIn the first test case, a is already non-decreasing, so you don't need to do any operations and the answer is 0.In the second test case, you can perform an operation for i = 1 and j = 5, so a will be equal to [0, 0, 1, 2] and it becomes non-decreasing.In the third test case, you can perform an operation for i = 2 and j = 1, so a will be equal to [1] and it becomes non-decreasing.
480 0 1 1 1 1 1 151 0 0 1 121 0111 1 0 0 1 0 0 1 1 1 0
0 1 1 3
1 second
256 megabytes
['constructive algorithms', 'greedy', 'two pointers', '*800']
A. Maxminatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a of size n consisting only of zeroes and ones and an integer k. In one operation you can do one of the following: Select 2 consecutive elements of a and replace them with their minimum (that is, let a := [a_{1}, a_{2}, \ldots, a_{i-1}, \min(a_{i}, a_{i+1}), a_{i+2}, \ldots, a_{n}] for some 1 \le i \le n-1). This operation decreases the size of a by 1. Select k consecutive elements of a and replace them with their maximum (that is, let a := [a_{1}, a_{2}, \ldots, a_{i-1}, \max(a_{i}, a_{i+1}, \ldots, a_{i+k-1}), a_{i+k}, \ldots, a_{n}] for some 1 \le i \le n-k+1). This operation decreases the size of a by k-1. Determine if it's possible to turn a into [1] after several (possibly zero) operations.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). The description of the test cases follows.The first line of each test case contains two integers n and k (2 \le k \le n \le 50), the size of array a and the length of segments that you can perform second type operation on.The second line contains n integers a_{1}, a_{2}, \ldots, a_{n} (a_i is 0 or 1), elements of array a.OutputFor each test case, if it is possible to turn a into [1], print "YES", otherwise print "NO".ExampleInput 73 20 1 05 31 0 1 1 02 21 14 40 0 0 06 30 0 1 0 0 17 51 1 1 1 1 1 15 30 0 1 0 0Output YES YES YES NO YES YES YES NoteIn the first test case, you can perform the second type operation on second and third elements so a becomes [0, 1], then you can perform the second type operation on first and second elements, so a turns to [1].In the fourth test case, it's obvious to see that you can't make any 1, no matter what you do.In the fifth test case, you can first perform a type 2 operation on the first three elements so that a becomes [1, 0, 0, 1], then perform a type 2 operation on the elements in positions two through four, so that a becomes [1, 1], and finally perform the first type operation on the remaining elements, so that a becomes [1].
73 20 1 05 31 0 1 1 02 21 14 40 0 0 06 30 0 1 0 0 17 51 1 1 1 1 1 15 30 0 1 0 0
YES YES YES NO YES YES YES
1 second
256 megabytes
['constructive algorithms', 'greedy', '*800']
F. MEX vs MEDtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_1, p_2, \ldots, p_n of length n of numbers 0, \ldots, n - 1. Count the number of subsegments 1 \leq l \leq r \leq n of this permutation such that mex(p_l, p_{l+1}, \ldots, p_r) > med(p_l, p_{l+1}, \ldots, p_r).mex of S is the smallest non-negative integer that does not occur in S. For example: mex({0, 1, 2, 3}) = 4 mex({0, 4, 1, 3}) = 2 mex({5, 4, 0, 1, 2}) = 3med of the set S is the median of the set, i.e. the element that, after sorting the elements in non-decreasing order, will be at position number \left \lfloor{ \frac{|S| + 1}{2} } \right \rfloor (array elements are numbered starting from 1 and here \left \lfloor{v} \right \rfloor denotes rounding v down.). For example: med({0, 1, 2, 3}) = 1 med({0, 4, 1, 3}) = 1 med({5, 4, 0, 1, 2}) = 2A sequence of n numbers is called a permutation if it contains all the numbers from 0 to n - 1 exactly once.InputThe first line of the input contains a single integer t (1 \leq t \leq 10^4), the number of test cases.The descriptions of the test cases follow.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5), the length of the permutation p.The second line of each test case contains exactly n integers: p_1, p_2, \ldots, p_n (0 \leq p_i \leq n - 1), elements of permutation p.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 answer in a single line: the number of subsegments 1 \leq l \leq r \leq n of this permutation such that mex(p_l, p_{l+1}, \ldots, p_r) > med(p_l, p_{l+1}, \ldots, p_r).ExampleInput 81021 031 0 240 2 1 353 1 0 2 462 0 4 1 3 583 7 2 6 0 1 5 442 0 1 3Output 1 2 4 4 8 8 15 6 NoteThe first test case contains exactly one subsegment and mex({0}) = 1 > med({0}) = 0 on it.In the third test case, on the following subsegments: [1, 0], [0], [1, 0, 2] and [0, 2], mex is greater than med.In the fourth test case, on the following subsegments: [0, 2], [0], [0, 2, 1] and [0, 2, 1, 3], mex greater than med.
81021 031 0 240 2 1 353 1 0 2 462 0 4 1 3 583 7 2 6 0 1 5 442 0 1 3
1 2 4 4 8 8 15 6
1 second
256 megabytes
['math', 'two pointers', '*2000']
E2. Divisible Numbers (hard version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an hard version of the problem. The only difference between an easy and a hard version is the constraints on a, b, c and d.You are given 4 positive integers a, b, c, d with a < c and b < d. Find any pair of numbers x and y that satisfies the following conditions: a < x \leq c, b < y \leq d, x \cdot y is divisible by a \cdot b.Note that required x and y may not exist.InputThe first line of the input contains a single integer t (1 \leq t \leq 10), the number of test cases.The descriptions of the test cases follow.The only line of each test case contains four integers a, b, c and d (1 \leq a < c \leq 10^9, 1 \leq b < d \leq 10^9).OutputFor each test case print a pair of numbers a < x \leq c and b < y \leq d such that x \cdot y is divisible by a \cdot b. If there are multiple answers, print any of them. If there is no such pair of numbers, then print -1 -1.ExampleInput 101 1 2 23 4 5 78 9 15 1812 21 14 2436 60 48 661024 729 373248 7301024 729 373247 7305040 40320 40319 1000000000999999999 999999999 1000000000 1000000000268435456 268435456 1000000000 1000000000Output 2 2 4 6 12 12 -1 -1 -1 -1 373248 730 -1 -1 15120 53760 -1 -1 536870912 536870912
101 1 2 23 4 5 78 9 15 1812 21 14 2436 60 48 661024 729 373248 7301024 729 373247 7305040 40320 40319 1000000000999999999 999999999 1000000000 1000000000268435456 268435456 1000000000 1000000000
2 2 4 6 12 12 -1 -1 -1 -1 373248 730 -1 -1 15120 53760 -1 -1 536870912 536870912
4 seconds
256 megabytes
['brute force', 'math', 'number theory', '*1900']
E1. Divisible Numbers (easy version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The only difference between an easy and a hard version is the constraints on a, b, c and d.You are given 4 positive integers a, b, c, d with a < c and b < d. Find any pair of numbers x and y that satisfies the following conditions: a < x \leq c, b < y \leq d, x \cdot y is divisible by a \cdot b.Note that required x and y may not exist.InputThe first line of the input contains a single integer t (1 \leq t \leq 10), the number of test cases.The descriptions of the test cases follow.The only line of each test case contains four integers a, b, c and d (1 \leq a < c \leq 10^5, 1 \leq b < d \leq 10^5).OutputFor each test case print a pair of numbers a < x \leq c and b < y \leq d such that x \cdot y is divisible by a \cdot b. If there are multiple answers, print any of them. If there is no such pair of numbers, then print -1 -1.ExampleInput 51 1 2 23 4 5 78 9 15 1812 21 14 2436 60 48 66Output 2 2 4 6 12 12 -1 -1 -1 -1
51 1 2 23 4 5 78 9 15 1812 21 14 2436 60 48 66
2 2 4 6 12 12 -1 -1 -1 -1
4 seconds
256 megabytes
['brute force', 'math', 'number theory', '*1500']
D. Divisibility by 2^ntime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of positive integers a_1, a_2, \ldots, a_n.Make the product of all the numbers in the array (that is, a_1 \cdot a_2 \cdot \ldots \cdot a_n) divisible by 2^n.You can perform the following operation as many times as you like: select an arbitrary index i (1 \leq i \leq n) and replace the value a_i with a_i=a_i \cdot i. You cannot apply the operation repeatedly to a single index. In other words, all selected values of i must be different.Find the smallest number of operations you need to perform to make the product of all the elements in the array divisible by 2^n. Note that such a set of operations does not always exist.InputThe first line of the input contains a single integer t (1 \leq t \leq 10^4) — the number test cases.Then the descriptions of the input data sets follow.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the length of array a.The second line of each test case contains exactly n integers: a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9).It is guaranteed that the sum of n values over all test cases in a test does not exceed 2 \cdot 10^5.OutputFor each test case, print the least number of operations to make the product of all numbers in the array divisible by 2^n. If the answer does not exist, print -1.ExampleInput 61223 2310 6 11413 17 1 151 1 12 1 1620 7 14 18 3 5Output 0 1 1 -1 2 1 NoteIn the first test case, the product of all elements is initially 2, so no operations needed.In the second test case, the product of elements initially equals 6. We can apply the operation for i = 2, and then a_2 becomes 2\cdot2=4, and the product of numbers becomes 3\cdot4=12, and this product of numbers is divided by 2^n=2^2=4. In the fourth test case, even if we apply all possible operations, we still cannot make the product of numbers divisible by 2^n  — it will be (13\cdot1)\cdot(17\cdot2)\cdot(1\cdot3)\cdot(1\cdot4)=5304, which does not divide by 2^n=2^4=16.In the fifth test case, we can apply operations for i = 2 and i = 4.
61223 2310 6 11413 17 1 151 1 12 1 1620 7 14 18 3 5
0 1 1 -1 2 1
2 seconds
256 megabytes
['greedy', 'math', 'sortings', '*1200']
C. Traffic Lighttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every n seconds and at the i-th second the color s_i is on.That way, the order of the colors is described by a string. For example, if s="rggry", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.More formally, you are given a string s_1, s_2, \ldots, s_n of length n. At the first second the color s_1 is on, at the second — s_2, ..., at the n-th second the color s_n is on, at the n + 1-st second the color s_1 is on and so on.You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.You can assume that you cross the road immediately. For example, with s="rggry" and the current color r there are two options: either the green color will be on after 1 second, or after 3. That way, the answer is equal to 3 — that is the number of seconds that we are guaranteed to cross the road, if the current color is r.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.Then the description of the test cases follows.The first line of each test case contains an integer n and a symbol c (1 \leq n \leq 2 \cdot 10^5, c is one of allowed traffic light colors r, y or g)— the length of the string s and the current color of the traffic light. The second line of each test case contains a string s of the length n, consisting of the letters r, y and g.It is guaranteed that the symbol g is in the string s and the symbol c is in the string s. It is guaranteed, that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case output the minimal number of second in which you are guaranteed to cross the road.ExampleInput 65 rrggry1 gg3 rrrg5 yyrrgy7 rrgrgyrg9 yrrrgyyygyOutput 3 0 2 4 1 4 NoteThe first test case is explained in the statement.In the second test case the green color is on so you can cross the road immediately. In the third test case, if the red color was on at the second second, then we would wait for the green color for one second, and if the red light was on at the first second, then we would wait for the green light for two seconds.In the fourth test case the longest we would wait for the green color is if we wait for it starting from the fifth second.
65 rrggry1 gg3 rrrg5 yyrrgy7 rrgrgyrg9 yrrrgyyygy
3 0 2 4 1 4
1 second
256 megabytes
['binary search', 'implementation', 'two pointers', '*1000']
B. Even-Odd Increments time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n of integers a_1, a_2, \ldots, a_n. Process q queries of two types: query of the form "0 x_j": add the value x_j to all even elements of the array a, query of the form "1 x_j": add the value x_j to all odd elements of the array a.Note that when processing the query, we look specifically at the odd/even value of a_i, not its index.After processing each query, print the sum of the elements of the array a.Please note that the answer 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 (like long long for C++).InputThe first line of the input contains an integer t (1 \leq t \leq 10^4) — the number of test cases.The descriptions of the test cases follow.The first line of each test case contains two integers n and q (1 \leq n, q \leq 10^5) — the length of array a and the number of queries.The second line of each test case contains exactly n integers: a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — elements of the array a.The following q lines contain queries as two integers type_j and x_j (0 \leq type_j \leq 1, 1 \leq x_j \leq 10^4).It is guaranteed that the sum of values n over all test cases in a test does not exceed 10^5. Similarly, the sum of values q over all test cases does not exceed 10^5.OutputFor each test case, print q numbers: the sum of the elements of the array a after processing a query.ExampleInput 41 111 13 31 2 40 21 30 56 71 3 2 4 10 481 60 50 40 51 30 120 16 71000000000 1000000000 1000000000 11 15 170 171 100001 510 920 531 160 1Output 2 11 14 29 80 100 100 100 118 190 196 3000000094 3000060094 3000060400 3000060952 3000061270 3000061366 3000061366 NoteIn the first test case, the array a = [2] after the first query.In the third test case, the array a is modified as follows: [1, 3, 2, 4, 10, 48] \rightarrow [7, 9, 2, 4, 10, 48] \rightarrow [7, 9, 7, 9, 15, 53] \rightarrow [7, 9, 7, 9, 15, 53] \rightarrow [10, 12, 10, 12, 18, 56] \rightarrow [22, 24, 22, 24, 30, 68] \rightarrow [23, 25, 23, 25, 31, 69].
41 111 13 31 2 40 21 30 56 71 3 2 4 10 481 60 50 40 51 30 120 16 71000000000 1000000000 1000000000 11 15 170 171 100001 510 920 531 160 1
2 11 14 29 80 100 100 100 118 190 196 3000000094 3000060094 3000060400 3000060952 3000061270 3000061366 3000061366
2 seconds
256 megabytes
['implementation', 'math', '*800']
A. Number Replacementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn integer array a_1, a_2, \ldots, a_n is being transformed into an array of lowercase English letters using the following prodecure:While there is at least one number in the array: Choose any number x from the array a, and any letter of the English alphabet y. Replace all occurrences of number x with the letter y. For example, if we initially had an array a = [2, 3, 2, 4, 1], then we could transform it the following way: Choose the number 2 and the letter c. After that a = [c, 3, c, 4, 1]. Choose the number 3 and the letter a. After that a = [c, a, c, 4, 1]. Choose the number 4 and the letter t. After that a = [c, a, c, t, 1]. Choose the number 1 and the letter a. After that a = [c, a, c, t, a]. After the transformation all letters are united into a string, in our example we get the string "cacta".Having the array a and the string s determine if the string s could be got from the array a after the described transformation?InputThe first line contains a single integer t (1 \leq t \leq 10^3) — the number of test cases.Then the description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 50) — the length of the array a and the string s.The second line of each test case contains exactly n integers: a_1, a_2, \ldots, a_n (1 \leq a_i \leq 50) — the elements of the array a.The third line of each test case contains a string s of length n, consisting of lowercase English letters. OutputFor each test case, output "YES", if we can get the string s from the array a, and "NO" otherwise. You can output each letter in any case.ExampleInput 752 3 2 4 1cacta150a211 22ab41 2 2 1aaab51 2 3 2 1aaaaa61 10 2 9 3 8azzfdb71 2 3 4 1 1 2abababbOutput YES YES YES NO YES YES NO NoteThe first test case corresponds to the sample described in the statement.In the second test case we can choose the number 50 and the letter a.In the third test case we can choose the number 11 and the letter a, after that a = [a, 22]. Then we choose the number 22 and the letter b and get a = [a, b].In the fifth test case we can change all numbers one by one to the letter a.
752 3 2 4 1cacta150a211 22ab41 2 2 1aaab51 2 3 2 1aaaaa61 10 2 9 3 8azzfdb71 2 3 4 1 1 2abababb
YES YES YES NO YES YES NO
2 seconds
256 megabytes
['greedy', 'implementation', '*800']
G. Antifibonacci Cuttime limit per test12 secondsmemory limit per test4 megabytesinputstandard inputoutputstandard outputNote that the memory limit is unusual.Let's define the sequence of Fibonacci strings as follows: f_0 is 0, f_1 is 1, f_i is f_{i-1} + f_{i-2} for i>1 (+ denotes the concatenation of two strings). So, for example, f_2 is 10, f_3 is 101, f_4 is 10110.For a given string s, let's define g(s) as the number of ways to cut it into several (any number, possibly even just one) strings such that none of these strings are Fibonacci strings. For example, if s is 10110101, g(s) = 3 since there are three ways to cut it: 101101 + 01; 1011 + 0101; 1011 + 01 + 01. You are given a sequence of strings s_1, s_2, \dots, s_n. Calculate g(s_1), g(s_1 + s_2), \dots, g(s_1 + s_2 + \ldots + s_n). Since these values can be huge, print them modulo 998244353.InputThe first line of the input contains one integer n (1 \le n \le 3 \cdot 10^3).Then, n lines follow. The i-th line contains the string s_i (1 \le |s_i| \le 10^3), consisting of characters 0 and/or 1.OutputPrint n integers, where the i-th integer is g(s_1 + s_2 + \ldots + s_i) \bmod 998244353.ExamplesInput 1 10110101 Output 3 Input 3 1111 1 0 Output 2 3 3 Input 6 10110101 100100001110 0000001100010001 1111 1001010100101010101001 000100000010101111 Output 3 561 1466229 9887505 972227653 52128355
1 10110101
3
12 seconds
4 megabytes
['bitmasks', 'combinatorics', 'constructive algorithms', 'data structures', 'dp', 'hashing', 'math', '*3000']
F. Intersection and Uniontime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given n segments on the coordinate axis. The i-th segment is [l_i, r_i]. Let's denote the set of all integer points belonging to the i-th segment as S_i.Let A \cup B be the union of two sets A and B, A \cap B be the intersection of two sets A and B, and A \oplus B be the symmetric difference of A and B (a set which contains all elements of A and all elements of B, except for the ones that belong to both sets).Let [\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}] be an array where each element is either \cup, \oplus, or \cap. Over all 3^{n-1} ways to choose this array, calculate the sum of the following values:|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|In this expression, |S| denotes the size of the set S.InputThe first line contains one integer n (2 \le n \le 3 \cdot 10^5).Then, n lines follow. The i-th of them contains two integers l_i and r_i (0 \le l_i \le r_i \le 3 \cdot 10^5).OutputPrint one integer — the sum of |(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n| over all possible ways to choose [\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}]. Since the answer can be huge, print it modulo 998244353.ExamplesInput 4 3 5 4 8 2 2 1 9 Output 162 Input 4 1 9 3 5 4 8 2 2 Output 102
4 3 5 4 8 2 2 1 9
162
5 seconds
512 megabytes
['data structures', 'dp', 'matrices', 'probabilities', '*2300']
E. FTLtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp is playing a video game. In the game, he controls a spaceship and has to destroy an enemy spaceship.Monocarp has two lasers installed on his spaceship. Both lasers 1 and 2 have two values: p_i — the power of the laser; t_i — the reload time of the laser. When a laser is fully charged, Monocarp can either shoot it or wait for the other laser to charge and shoot both of them at the same time.An enemy spaceship has h durability and s shield capacity. When Monocarp shoots an enemy spaceship, it receives (P - s) damage (i. e. (P - s) gets subtracted from its durability), where P is the total power of the lasers that Monocarp shoots (i. e. p_i if he only shoots laser i and p_1 + p_2 if he shoots both lasers at the same time). An enemy spaceship is considered destroyed when its durability becomes 0 or lower.Initially, both lasers are zero charged.What's the lowest amount of time it can take Monocarp to destroy an enemy spaceship?InputThe first line contains two integers p_1 and t_1 (2 \le p_1 \le 5000; 1 \le t_1 \le 10^{12}) — the power and the reload time of the first laser.The second line contains two integers p_2 and t_2 (2 \le p_2 \le 5000; 1 \le t_2 \le 10^{12}) — the power and the reload time of the second laser.The third line contains two integers h and s (1 \le h \le 5000; 1 \le s < \min(p_1, p_2)) — the durability and the shield capacity of an enemy spaceship. Note that the last constraint implies that Monocarp will always be able to destroy an enemy spaceship.OutputPrint a single integer — the lowest amount of time it can take Monocarp to destroy an enemy spaceship.ExamplesInput 5 10 4 9 16 1 Output 20 Input 10 1 5000 100000 25 9 Output 25 NoteIn the first example, Monocarp waits for both lasers to charge, then shoots both lasers at 10, they deal (5 + 4 - 1) = 8 damage. Then he waits again and shoots lasers at 20, dealing 8 more damage.In the second example, Monocarp doesn't wait for the second laser to charge. He just shoots the first laser 25 times, dealing (10 - 9) = 1 damage each time.
5 10 4 9 16 1
20
4 seconds
512 megabytes
['binary search', 'dp', '*2400']
D. Problem with Random Teststime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of n characters. Each character of s is either 0 or 1.A substring of s is a contiguous subsequence of its characters.You have to choose two substrings of s (possibly intersecting, possibly the same, possibly non-intersecting — just any two substrings). After choosing them, you calculate the value of the chosen pair of substrings as follows: let s_1 be the first substring, s_2 be the second chosen substring, and f(s_i) be the integer such that s_i is its binary representation (for example, if s_i is 11010, f(s_i) = 26); the value is the bitwise OR of f(s_1) and f(s_2). Calculate the maximum possible value you can get, and print it in binary representation without leading zeroes.InputThe first line contains one integer n — the number of characters in s.The second line contains s itself, consisting of exactly n characters 0 and/or 1.All non-example tests in this problem are generated randomly: every character of s is chosen independently of other characters; for each character, the probability of it being 1 is exactly \frac{1}{2}.This problem has exactly 40 tests. Tests from 1 to 3 are the examples; tests from 4 to 40 are generated randomly. In tests from 4 to 10, n = 5; in tests from 11 to 20, n = 1000; in tests from 21 to 40, n = 10^6. Hacks are forbidden in this problem.OutputPrint the maximum possible value you can get in binary representation without leading zeroes.ExamplesInput 5 11010 Output 11111 Input 7 1110010 Output 1111110 Input 4 0000 Output 0 NoteIn the first example, you can choose the substrings 11010 and 101. f(s_1) = 26, f(s_2) = 5, their bitwise OR is 31, and the binary representation of 31 is 11111.In the second example, you can choose the substrings 1110010 and 11100.
5 11010
11111
4 seconds
512 megabytes
['brute force', 'dp', 'greedy', 'probabilities', '*1700']
C. Save the Magazinestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp has been collecting rare magazines for quite a while, and now he has decided to sell them. He distributed the magazines between n boxes, arranged in a row. The i-th box contains a_i magazines. Some of the boxes are covered with lids, others are not. Suddenly it started to rain, and now Monocarp has to save as many magazines from the rain as possible. To do this, he can move the lids between boxes as follows: if the i-th box was covered with a lid initially, he can either move the lid from the i-th box to the box (i-1) (if it exists), or keep the lid on the i-th box. You may assume that Monocarp can move the lids instantly at the same moment, and no lid can be moved more than once. If a box will be covered with a lid after Monocarp moves the lids, the magazines in it will be safe from the rain; otherwise they will soak.You have to calculate the maximum number of magazines Monocarp can save from the rain.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of the testcases.The first line of each testcase contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of boxes.The second line contains a string of n characters 0 and/or 1. If the i-th character is 1, the i-th box is initially covered with a lid. If the i-th character is 0, the i-th box is initially not covered.The third line contains a sequence of integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^4), where a_i is the number of magazines in the i-th box.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print one integer — the maximum number of magazines Monocarp can save from the rain.ExampleInput 450111010 5 8 9 6601101120 10 9 30 20 1940000100 100 100 100401115 4 5 1Output 27 80 0 14 NoteIn the first testcase of the example, Monocarp can move the lid from the second box to the first box, so the boxes 1, 3 and 4 are covered, and 10 + 8 + 9 = 27 magazines are saved.In the second testcase, Monocarp can move the lid from the second box to the first box, then from the third box to the second box, then from the fifth box to the fourth box, and then from the sixth box to the fifth box. The boxes 1, 2, 4 and 5 will be covered, so 20 + 10 + 30 + 20 = 80 magazines can be saved.There are no lids in the third testcase, so it's impossible to save even a single magazine.
450111010 5 8 9 6601101120 10 9 30 20 1940000100 100 100 100401115 4 5 1
27 80 0 14
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*1100']
B. Permutation Valuetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an integer n. You have to construct a permutation of size n.A permutation is an array where each integer from 1 to s (where s is the size of permutation) occurs exactly once. For example, [2, 1, 4, 3] is a permutation of size 4; [1, 2, 4, 5, 3] is a permutation of size 5; [1, 4, 3] is not a permutation (the integer 2 is absent), [2, 1, 3, 1] is not a permutation (the integer 1 appears twice).A subsegment of a permutation is a contiguous subsequence of that permutation. For example, the permutation [2, 1, 4, 3] has 10 subsegments: [2], [2, 1], [2, 1, 4], [2, 1, 4, 3], [1], [1, 4], [1, 4, 3], [4], [4, 3] and [3].The value of the permutation is the number of its subsegments which are also permutations. For example, the value of [2, 1, 4, 3] is 3 since the subsegments [2, 1], [1] and [2, 1, 4, 3] are permutations.You have to construct a permutation of size n with minimum possible value among all permutations of size n.InputThe first line contains one integer t (1 \le t \le 48) — the number of test cases.Then, t lines follow. The i-th of them contains one integer n (3 \le n \le 50) representing the i-th test case.OutputFor each test case, print n integers — the permutation of size n with minimum possible value. If there are multiple such permutations, print any of them.ExampleInput 256Output 1 4 3 5 2 4 1 6 2 5 3 NoteIn the first example, the permutation [1, 4, 3, 5, 2] is one of the possible answers; its value is 2.In the second example, the permutation [4, 1, 6, 2, 5, 3] is one of the possible answers; its value is 2.
256
1 4 3 5 2 4 1 6 2 5 3
2 seconds
512 megabytes
['constructive algorithms', 'greedy', '*800']
A. Passwordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp has forgotten the password to his mobile phone. The password consists of 4 digits from 0 to 9 (note that it can start with the digit 0).Monocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers some digits which were definitely not used in the password.You have to calculate the number of different sequences of 4 digits that could be the password for Monocarp's mobile phone (i. e. these sequences should meet all constraints on Monocarp's password).InputThe first line contains a single integer t (1 \le t \le 200) — the number of testcases.The first line of each testcase contains a single integer n (1 \le n \le 8) — the number of digits for which Monocarp remembers that they were not used in the password.The second line contains n different integers a_1, a_2, \dots a_n (0 \le a_i \le 9) representing the digits that were not used in the password. Note that the digits a_1, a_2, \dots, a_n are given in ascending order.OutputFor each testcase, print one integer — the number of different 4-digit sequences that meet the constraints.ExampleInput 280 1 2 4 5 6 8 918Output 6 216 NoteIn the first example, all possible passwords are: "3377", "3737", "3773", "7337", "7373", "7733".
280 1 2 4 5 6 8 918
6 216
2 seconds
256 megabytes
['brute force', 'combinatorics', 'implementation', 'math', '*800']
G. Orraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n nonnegative integers. Let's define the prefix OR array b as the array b_i = a_1~\mathsf{OR}~a_2~\mathsf{OR}~\dots~\mathsf{OR}~a_i, where \mathsf{OR} represents the bitwise OR operation. In other words, the array b is formed by computing the \mathsf{OR} of every prefix of a.You are asked to rearrange the elements of the array a in such a way that its prefix OR array is lexicographically maximum.An array x is lexicographically greater than an array y if in the first position where x and y differ, x_i > y_i.InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the array a.The second line of each test case contains n nonnegative integers a_1, \ldots, a_n (0 \leq a_i \leq 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print n integers — any rearrangement of the array a that obtains the lexicographically maximum prefix OR array.ExampleInput 541 2 4 875 1 2 3 4 5 521 10162 3 4 2 3 481 4 2 3 4 5 7 1Output 8 4 2 1 5 2 1 3 4 5 5 101 1 4 3 2 2 3 4 7 1 4 2 3 4 5 1
541 2 4 875 1 2 3 4 5 521 10162 3 4 2 3 481 4 2 3 4 5 7 1
8 4 2 1 5 2 1 3 4 5 5 101 1 4 3 2 2 3 4 7 1 4 2 3 4 5 1
2 seconds
256 megabytes
['bitmasks', 'brute force', 'greedy', 'math', 'sortings', '*1500']
F. Smallertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlperen has two strings, s and t which are both initially equal to "a". He will perform q operations of two types on the given strings: 1 \;\; k \;\; x — Append the string x exactly k times at the end of string s. In other words, s := s + \underbrace{x + \dots + x}_{k \text{ times}}. 2 \;\; k \;\; x — Append the string x exactly k times at the end of string t. In other words, t := t + \underbrace{x + \dots + x}_{k \text{ times}}. After each operation, determine if it is possible to rearrange the characters of s and t such that s is lexicographically smaller^{\dagger} than t.Note that the strings change after performing each operation and don't go back to their initial states.^{\dagger} Simply speaking, the lexicographical order is the order in which words are listed in a dictionary. A formal definition is as follows: string p is lexicographically smaller than string q if there exists a position i such that p_i < q_i, and for all j < i, p_j = q_j. If no such i exists, then p is lexicographically smaller than q if the length of p is less than the length of q. For example, \texttt{abdc} < \texttt{abe} and \texttt{abc} < \texttt{abcd}, where we write p < q if p is lexicographically smaller than q.InputThe first line of the input contains an integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains an integer q (1 \leq q \leq 10^5) — the number of operations Alperen will perform.Then q lines follow, each containing two positive integers d and k (1 \leq d \leq 2; 1 \leq k \leq 10^5) and a non-empty string x consisting of lowercase English letters — the type of the operation, the number of times we will append string x and the string we need to append respectively.It is guaranteed that the sum of q over all test cases doesn't exceed 10^5 and that the sum of lengths of all strings x in the input doesn't exceed 5 \cdot 10^5.OutputFor each operation, output "YES", if it is possible to arrange the elements in both strings in such a way that s is lexicographically smaller than t and "NO" otherwise.ExampleInput 352 1 aa1 2 a2 3 a1 2 b2 3 abca21 5 mihai2 2 buiucani31 5 b2 3 a2 4 paiuOutput YES NO YES NO YES NO YES NO NO YES NoteIn the first test case, the strings are initially s = "a" and t = "a". After the first operation the string t becomes "aaa". Since "a" is already lexicographically smaller than "aaa", the answer for this operation should be "YES".After the second operation string s becomes "aaa", and since t is also equal to "aaa", we can't arrange s in any way such that it is lexicographically smaller than t, so the answer is "NO".After the third operation string t becomes "aaaaaa" and s is already lexicographically smaller than it so the answer is "YES".After the fourth operation s becomes "aaabb" and there is no way to make it lexicographically smaller than "aaaaaa" so the answer is "NO".After the fifth operation the string t becomes "aaaaaaabcaabcaabca", and we can rearrange the strings to: "bbaaa" and "caaaaaabcaabcaabaa" so that s is lexicographically smaller than t, so we should answer "YES".
352 1 aa1 2 a2 3 a1 2 b2 3 abca21 5 mihai2 2 buiucani31 5 b2 3 a2 4 paiu
YES NO YES NO YES NO YES NO NO YES
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'strings', '*1500']
E. Scuzatime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTimur has a stairway with n steps. The i-th step is a_i meters higher than its predecessor. The first step is a_1 meters higher than the ground, and the ground starts at 0 meters. The stairs for the first test case. Timur has q questions, each denoted by an integer k_1, \dots, k_q. For each question k_i, you have to print the maximum possible height Timur can achieve by climbing the steps if his legs are of length k_i. Timur can only climb the j-th step if his legs are of length at least a_j. In other words, k_i \geq a_j for each step j climbed.Note that you should answer each question independently.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains two integers n, q (1 \leq n, q \leq 2\cdot10^5) — the number of steps and the number of questions, respectively.The second line of each test case contains n integers (1 \leq a_i \leq 10^9) — the height of the steps.The third line of each test case contains q integers (0 \leq k_i \leq 10^9) — the numbers for each question.It is guaranteed that the sum of n does not exceed 2\cdot10^5, and the sum of q does not exceed 2\cdot10^5.OutputFor each test case, output a single line containing q integers, the answer for each question.Please note, that the answer for some questions won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).ExampleInput 34 51 2 1 51 2 4 9 102 21 10 13 11000000000 1000000000 10000000001000000000Output 1 4 4 9 9 0 2 3000000000 NoteConsider the first test case, pictured in the statement. If Timur's legs have length 1, then he can only climb stair 1, so the highest he can reach is 1 meter. If Timur's legs have length 2 or 4, then he can only climb stairs 1, 2, and 3, so the highest he can reach is 1+2+1=4 meters. If Timur's legs have length 9 or 10, then he can climb the whole staircase, so the highest he can reach is 1+2+1+5=9 meters. In the first question of the second test case, Timur has no legs, so he cannot go up even a single step. :(
34 51 2 1 51 2 4 9 102 21 10 13 11000000000 1000000000 10000000001000000000
1 4 4 9 9 0 2 3000000000
3 seconds
256 megabytes
['binary search', 'greedy', 'math', '*1200']
D. Coprimetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array of n positive integers a_1, a_2, \dots, a_n (1 \le a_i \le 1000). Find the maximum value of i + j such that a_i and a_j are coprime,^{\dagger} or -1 if no such i, j exist.For example consider the array [1, 3, 5, 2, 4, 7, 7]. The maximum value of i + j that can be obtained is 5 + 7, since a_5 = 4 and a_7 = 7 are coprime.^{\dagger} Two integers p and q are coprime if the only positive integer that is a divisor of both of them is 1 (that is, their greatest common divisor is 1).InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 10) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (2 \leq n \leq 2\cdot10^5) — the length of the array.The following line contains n space-separated positive integers a_1, a_2,..., a_n (1 \leq a_i \leq 1000) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case, output a single integer  — the maximum value of i + j such that i and j satisfy the condition that a_i and a_j are coprime, or output -1 in case no i, j satisfy the condition.ExampleInput 633 2 171 3 5 2 4 7 751 2 3 4 532 2 465 4 3 15 12 1651 2 2 3 6Output 6 12 9 -1 10 7 NoteFor the first test case, we can choose i = j = 3, with sum of indices equal to 6, since 1 and 1 are coprime.For the second test case, we can choose i = 7 and j = 5, with sum of indices equal to 7 + 5 = 12, since 7 and 4 are coprime.
633 2 171 3 5 2 4 7 751 2 3 4 532 2 465 4 3 15 12 1651 2 2 3 6
6 12 9 -1 10 7
3 seconds
256 megabytes
['brute force', 'greedy', 'number theory', '*1100']
C. Stripestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn an 8 \times 8 grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R. InputThe first line of the input contains a single integer t (1 \leq t \leq 4000) — the number of test cases. The description of test cases follows. There is an empty line before each test case.Each test case consists of 8 lines, each containing 8 characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively.It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns.At least one stripe is painted.OutputFor each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).ExampleInput 4....B.......B.......B...RRRRRRRR....B.......B.......B.......B...RRRRRRRBB......BB......BB......BB......BB......BB......BRRRRRRRBRRRRRRBB.B.B..BBRRRRRRBB.B.B..BB.B.B..BBRRRRRRBB.B.B..BB.B.B..BB........................RRRRRRRR................................Output R B B R NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
4....B.......B.......B...RRRRRRRR....B.......B.......B.......B...RRRRRRRBB......BB......BB......BB......BB......BB......BRRRRRRRBRRRRRRBB.B.B..BBRRRRRRBB.B.B..BB.B.B..BBRRRRRRBB.B.B..BB.B.B..BB........................RRRRRRRR................................
R B B R
1 second
256 megabytes
['implementation', '*900']
B. Increasingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that a_1 < a_2 < \dots < a_n holds.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 100) — the length of the array.The second line of each test case contains n integers a_i (1 \leq a_i \leq 10^9) — the elements of the array.OutputFor each test case, output "YES" (without quotes) if the array satisfies the condition, and "NO" (without quotes) otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput 341 1 1 158 7 1 3 415Output NO YES YES NoteIn the first test case any rearrangement will keep the array [1,1,1,1], which is not strictly increasing.In the second test case, you can make the array [1,3,4,7,8].
341 1 1 158 7 1 3 415
NO YES YES
1 second
256 megabytes
['greedy', 'implementation', 'sortings', '*800']
A. Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a, b, and c. Determine if one of them is the sum of the other two.InputThe first line contains a single integer t (1 \leq t \leq 9261) — the number of test cases.The description of each test case consists of three integers a, b, c (0 \leq a, b, c \leq 20).OutputFor each test case, output "YES" if one of the numbers is the sum of the other two, and "NO" otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput 71 4 32 5 89 11 200 0 020 20 204 12 315 7 8Output YES NO YES YES NO NO YES NoteIn the first test case, 1 + 3 = 4.In the second test case, none of the numbers is the sum of the other two.In the third test case, 9 + 11 = 20.
71 4 32 5 89 11 200 0 020 20 204 12 315 7 8
YES NO YES YES NO NO YES
1 second
256 megabytes
['implementation', '*800']
G. Kirill and Companytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKirill lives on a connected undirected graph of n vertices and m edges at vertex 1. One fine evening he gathered f friends, the i-th friend lives at the vertex h_i. So all friends are now in the vertex 1, the i-th friend must get to his home to the vertex h_i.The evening is about to end and it is time to leave. It turned out that k (k \le 6) of his friends have no cars, and they would have to walk if no one gives them a ride. One friend with a car can give a ride to any number of friends without cars, but only if he can give them a ride by driving along one of the shortest paths to his house.For example, in the graph below, a friend from vertex h_i=5 can give a ride to friends from the following sets of vertices: [2, 3], [2, 4], [2], [3], [4], but can't give a ride to friend from vertex 6 or a set [3, 4]. The vertices where friends without cars live are highlighted in green, and with cars — in red. Kirill wants as few friends as possible to have to walk. Help him find the minimum possible number.InputThe first line of input data contains an integer t (1 \le t \le 10^3) — the number of test cases in the test.The first line of the test case contains two integers n and m (2 \le n \le 10^4, n-1 \le m \le min (10^4, \frac{n \cdot (n - 1)}{2} )) — the number of vertices and edges, respectively.The next m lines of the test case contain a description of the edges, two integers each u and v (1 \le u, v \le n, u \ne v) — indexes of vertices connected by an edge. It is guaranteed that there is at most one edge between any pair of vertices (i.e. no multiple edges in the graph).Then follows line containing the number f (1 \le f \le 10^4) — the number of Kirill's friends.The next line of the test case contains f integers: h_1, h_2, \dots, h_f (2 \le h_i \le n) — the vertices in which they live. Some vertices may be repeated.The next line of the set contains the number k (1 \le k \le min(6, f)) — the number of friends without cars.The last line of each test case contains k integers: p_1, p_2, \dots, p_k (1 \le p_i \le f, p_i < p_{i+1}) — indexes of friends without cars.It is guaranteed that the sum of n over all cases does not exceed 10^4, as well as the sums of m and f.OutputOutput t lines, each of which contains the answer to the corresponding test case. As an answer, output a single integer — the minimum possible number of friends who will have to walk.ExamplesInput 36 71 22 32 43 54 53 66 552 3 4 5 641 2 3 56 71 22 32 43 54 53 66 562 3 4 5 6 541 2 3 54 41 21 32 33 433 4 221 3Output 2 1 1 Input 32 11 232 2 231 2 33 31 21 32 342 2 2 331 2 44 43 13 21 42 453 2 2 4 231 3 4Output 3 1 0 NoteThe first test case of the first example is explained in the statement.In the second test case of the first example, two friends with cars live at vertex 5, one can give a ride to friends from vertices 2 and 3, and the second from vertex 4, only a friend from vertex 6 will have to walk.
36 71 22 32 43 54 53 66 552 3 4 5 641 2 3 56 71 22 32 43 54 53 66 562 3 4 5 6 541 2 3 54 41 21 32 33 433 4 221 3
2 1 1
3 seconds
256 megabytes
['bitmasks', 'brute force', 'dfs and similar', 'dp', 'flows', 'graphs', 'shortest paths', '*2200']
F. Multi-Colored Segmentstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDmitry has n segments of different colors on the coordinate axis Ox. Each segment is characterized by three integers l_i, r_i and c_i (1 \le l_i \le r_i \le 10^9, 1 \le c_i \le n), where l_i and r_i are are the coordinates of the ends of the i-th segment, and c_i is its color.Dmitry likes to find the minimum distances between segments. However, he considers pairs of segments of the same color uninteresting. Therefore, he wants to know for each segment the distance from this segment to the nearest differently colored segment.The distance between two segments is the minimum of the distances between a point of the first segment and a point of the second segment. In particular, if the segments intersect, then the distance between them is equal to 0.For example, Dmitry has 5 segments: The first segment intersects with the second (and these are segments of different colors), so the answers for them are equal to 0. For the 3-rd segment, the nearest segment of a different color is the 2-nd segment, the distance to which is equal to 2. For the 4-th segment, the nearest segment of a different color is the 5-th segment, the distance to which is equal to 1. The 5-th segment lies inside the 2-nd segment (and these are segments of different colors), so the answers for them are equal to 0. InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the test.The descriptions of the test cases follow.The first line of description of each test case contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of segments.The next n lines contain descriptions of the segments. Each segment is described by three integers l_i, r_i and c_i (1 \le l_i \le r_i \le 10^9, 1 \le c_i \le n) — coordinates of the left and right ends of i-th segment, as well as the color of this segment. It is guaranteed that there are at least 2 segments of different colors.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, on a separate line print n integers, where the i-th number is equal to the distance from the i-th segment to the nearest segment of a different color.ExamplesInput 931 2 13 4 15 6 22100000000 200000000 1900000000 1000000000 251 2 12 3 23 4 34 5 45 6 551 5 14 9 21 2 18 9 25 7 321 100 210 90 131 1 110 10 21000000000 1000000000 333 4 12 5 11 6 265 6 211 12 37 8 23 4 21 2 19 10 221 3 12 3 2Output 3 1 1 700000000 700000000 0 0 0 0 0 0 0 2 1 0 0 0 9 9 999999990 0 0 0 3 1 3 1 1 1 0 0 Input 4811 16 712 15 72 5 817 22 51 8 819 23 816 16 66 7 591 4 35 11 18 11 31 10 12 11 11 10 43 11 15 7 11 11 1925 25 126 26 124 24 213 14 212 16 217 18 119 19 124 27 224 27 1915 18 120 22 213 22 213 22 23 13 26 10 23 6 219 24 222 24 2Output 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 1 1 3 0 0 0 2 0 0 2 5 9 1 4 NoteIn the first test case of the first sample there is only one segment of color 2, and all other segments have color 1. Therefore, for segments of color 1, the answer is equal to the distance to the 3rd segment, and for 3rd one, the answer is equal to the minimum of the distances to segments of color 1.In the second test case of the first sample there are only 2 segments, and for both of them the answer is equal to the distance between them.In the third test case of the first sample, each segment intersects at least one of its ends with a segment of a different color, so all answers are equal to 0.The fourth test case of the first sample is described in the problem statement.In the fifth test case of the first sample, one segment lies completely inside the other, and for both of them the answer is 0.In the sixth test case of the first sample, all segments are points of different colors.
931 2 13 4 15 6 22100000000 200000000 1900000000 1000000000 251 2 12 3 23 4 34 5 45 6 551 5 14 9 21 2 18 9 25 7 321 100 210 90 131 1 110 10 21000000000 1000000000 333 4 12 5 11 6 265 6 211 12 37 8 23 4 21 2 19 10 221 3 12 3 2
3 1 1 700000000 700000000 0 0 0 0 0 0 0 2 1 0 0 0 9 9 999999990 0 0 0 3 1 3 1 1 1 0 0
3 seconds
256 megabytes
['binary search', 'data structures', 'math', 'sortings', '*2000']
E. Sending a Sequence Over the Networktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe sequence a is sent over the network as follows: sequence a is split into segments (each element of the sequence belongs to exactly one segment, each segment is a group of consecutive elements of sequence); for each segment, its length is written next to it, either to the left of it or to the right of it; the resulting sequence b is sent over the network. For example, we needed to send the sequence a = [1, 2, 3, 1, 2, 3]. Suppose it was split into segments as follows: [\color{red}{1}] + [\color{blue}{2, 3, 1}] + [\color{green}{2, 3}]. Then we could have the following sequences: b = [1, \color{red}{1}, 3, \color{blue}{2, 3, 1}, \color{green}{2, 3}, 2], b = [\color{red}{1}, 1, 3, \color{blue}{2, 3, 1}, 2, \color{green}{2, 3}], b = [\color{red}{1}, 1, \color{blue}{2, 3, 1}, 3, 2, \color{green}{2, 3}], b = [\color{red}{1}, 1,\color{blue}{2, 3, 1}, 3, \color{green}{2, 3}, 2]. If a different segmentation had been used, the sent sequence might have been different.The sequence b is given. Could the sequence b be sent over the network? In other words, is there such a sequence a that converting a to send it over the network could result in a sequence b?InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of two lines.The first line of the test case contains an integer n (1 \le n \le 2 \cdot 10^5) — the size of the sequence b.The second line of test case contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^9) — the sequence b itself.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print on a separate line: YES if sequence b could be sent over the network, that is, if sequence b could be obtained from some sequence a to send a over the network. NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as positive response).ExampleInput 791 1 2 3 1 3 2 2 3512 1 2 7 565 7 8 9 10 344 8 6 223 1104 6 2 1 9 4 9 3 4 211Output YES YES YES NO YES YES NO NoteIn the first case, the sequence b could be obtained from the sequence a = [1, 2, 3, 1, 2, 3] with the following partition: [\color{red}{1}] + [\color{blue}{2, 3, 1}] + [\color{green}{2, 3}]. The sequence b: [\color{red}{1}, 1, \color{blue}{2, 3, 1}, 3, 2, \color{green}{2, 3}].In the second case, the sequence b could be obtained from the sequence a = [12, 7, 5] with the following partition: [\color{red}{12}] + [\color{green}{7, 5}]. The sequence b: [\color{red}{12}, 1, 2, \color{green}{7, 5}].In the third case, the sequence b could be obtained from the sequence a = [7, 8, 9, 10, 3] with the following partition: [\color{red}{7, 8, 9, 10, 3}]. The sequence b: [5, \color{red}{7, 8, 9, 10, 3}].In the fourth case, there is no sequence a such that changing a for transmission over the network could produce a sequence b.
791 1 2 3 1 3 2 2 3512 1 2 7 565 7 8 9 10 344 8 6 223 1104 6 2 1 9 4 9 3 4 211
YES YES YES NO YES YES NO
1 second
256 megabytes
['dp', '*1600']
D. Masha and a Beautiful Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe girl named Masha was walking in the forest and found a complete binary tree of height n and a permutation p of length m=2^n.A complete binary tree of height n is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is n. The picture below shows the complete binary tree for n=2.A permutation is an array consisting of n different integers from 1 to n. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not (2 occurs twice), and [1,3,4] is also not a permutation (n=3, but there is 4 in the array).Let's enumerate m leaves of this tree from left to right. The leaf with the number i contains the value p_i (1 \le i \le m).For example, if n = 2, p = [3, 1, 4, 2], the tree will look like this: Masha considers a tree beautiful if the values in its leaves are ordered from left to right in increasing order.In one operation, Masha can choose any non-leaf vertex of the tree and swap its left and right sons (along with their subtrees).For example, if Masha applies this operation to the root of the tree discussed above, it will take the following form: Help Masha understand if she can make a tree beautiful in a certain number of operations. If she can, then output the minimum number of operations to make the tree beautiful.InputThe first line contains single integer t (1 \le t \le 10^4) — number of test cases.In each test case, the first line contains an integer m (1 \le m \le 262144), which is a power of two  — the size of the permutation p.The second line contains m integers: p_1, p_2, \dots, p_m (1 \le p_i \le m) — the permutation p.It is guaranteed that the sum of m over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case in a separate line, print the minimum possible number of operations for which Masha will be able to make the tree beautiful or -1, if this is not possible.ExampleInput 486 5 7 8 4 3 1 243 1 4 21187 8 4 3 1 2 6 5Output 4 -1 0 -1 NoteConsider the first test.In the first test case, you can act like this (the vertex to which the operation is applied at the current step is highlighted in purple): It can be shown that it is impossible to make a tree beautiful in fewer operations.In the second test case, it can be shown that it is impossible to make a tree beautiful.In the third test case, the tree is already beautiful.
486 5 7 8 4 3 1 243 1 4 21187 8 4 3 1 2 6 5
4 -1 0 -1
2 seconds
256 megabytes
['dfs and similar', 'divide and conquer', 'graphs', 'sortings', 'trees', '*1300']
C. Minimize the Thicknesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a=[a_1,a_2,\dots,a_n] consisting of n positive integers.Let's call a group of consecutive elements a segment. Each segment is characterized by two indices: the index of its left end and the index of its right end. Denote by a[l,r] a segment of the sequence a with the left end in l and the right end in r, i.e. a[l,r]=[a_l, a_{l+1}, \dots, a_r].For example, if a=[31,4,15,92,6,5], then a[2,5]=[4,15,92,6], a[5,5]=[6], a[1,6]=[31,4,15,92,6,5] are segments.We split the given sequence a into segments so that: each element is in exactly one segment; the sums of elements for all segments are equal. For example, if a = [55,45,30,30,40,100], then such a sequence can be split into three segments: a[1,2]=[55,45], a[3,5]=[30, 30, 40], a[6,6]=[100]. Each element belongs to exactly segment, the sum of the elements of each segment is 100.Let's define thickness of split as the length of the longest segment. For example, the thickness of the split from the example above is 3.Find the minimum thickness among all possible splits of the given sequence of a into segments in the required way.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.Each test case is described by two lines.The first line of each test case contains a single integer n (1 \le n \le 2000) — the length of the sequence a.The second line of each test case contains exactly n integers: a_1, a_2, \dots, a_n (1 \le a_i \le 10^6) — elements of the sequence a.It is guaranteed that the sum of n for all test cases does not exceed 2000.OutputFor each test case, output one integer — the minimum possible thickness of a split of the sequence a into segments.Note that there always exist a split, you can always consider whole sequence as one segment.ExampleInput 4655 45 30 30 40 100410 23 7 13510 55 35 30 6564 1 1 1 1 4Output 3 4 2 3 NoteThe split in the first test case is explained in the statement, it can be shown that it is optimal.In the second test case, it is possible to split into segments only by leaving a single segment. Then the thickness of this split is equal to the length of the entire sequence, that is, 4.In the third test case, the optimal split will be [10, 55], [35, 30], [65]. The thickness of the split equals to 2.In the fourth test case possible splits are: [4] + [1, 1, 1, 1] + [4]; [4, 1, 1] + [1, 1, 4].
4655 45 30 30 40 100410 23 7 13510 55 35 30 6564 1 1 1 1 4
3 4 2 3
2 seconds
256 megabytes
['brute force', 'greedy', 'math', 'two pointers', '*1100']
B. Funny Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of n numbers is called permutation if it contains all numbers from 1 to n exactly once. For example, the sequences [3, 1, 4, 2], [1] and [2,1] are permutations, but [1,2,1], [0,1] and [1,3,4] are not.For a given number n you need to make a permutation p such that two requirements are satisfied at the same time: For each element p_i, at least one of its neighbors has a value that differs from the value of p_i by one. That is, for each element p_i (1 \le i \le n), at least one of its neighboring elements (standing to the left or right of p_i) must be p_i + 1, or p_i - 1. the permutation must have no fixed points. That is, for every i (1 \le i \le n), p_i \neq i must be satisfied. Let's call the permutation that satisfies these requirements funny.For example, let n = 4. Then [4, 3, 1, 2] is a funny permutation, since: to the right of p_1=4 is p_2=p_1-1=4-1=3; to the left of p_2=3 is p_1=p_2+1=3+1=4; to the right of p_3=1 is p_4=p_3+1=1+1=2; to the left of p_4=2 is p_3=p_4-1=2-1=1. for all i is p_i \ne i. For a given positive integer n, output any funny permutation of length n, or output -1 if funny permutation of length n does not exist.InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases.The description of the test cases follows.Each test case consists of f single line containing one integer n (2 \le n \le 2 \cdot 10^5).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print on a separate line: any funny permutation p of length n; or the number -1 if the permutation you are looking for does not exist. ExampleInput 543752Output 3 4 2 1 -1 6 7 4 5 3 2 1 5 4 1 2 3 2 1NoteThe first test case is explained in the problem statement.In the second test case, it is not possible to make the required permutation: permutations [1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1] have fixed points, and in [2, 3, 1] and [3, 1, 2] the first condition is met not for all positions.
543752
3 4 2 1 -1 6 7 4 5 3 2 1 5 4 1 2 3 2 1
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
A. Compare T-Shirt Sizestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo T-shirt sizes are given: a and b. The T-shirt size is either a string M or a string consisting of several (possibly zero) characters X and one of the characters S or L.For example, strings M, XXL, S, XXXXXXXS could be the size of some T-shirts. And the strings XM, LL, SX are not sizes.The letter M stands for medium, S for small, L for large. The letter X refers to the degree of size (from eXtra). For example, XXL is extra-extra-large (bigger than XL, and smaller than XXXL).You need to compare two given sizes of T-shirts a and b.The T-shirts are compared as follows: any small size (no matter how many letters X) is smaller than the medium size and any large size; any large size (regardless of the number of letters X) is larger than the medium size and any small size; the more letters X before S, the smaller the size; the more letters X in front of L, the larger the size. For example: XXXS < XS XXXL > XL XL > M XXL = XXL XXXXXS < M XL > XXXS InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of one line, in which a and b T-shirt sizes are written. The lengths of the strings corresponding to the T-shirt sizes do not exceed 50. It is guaranteed that all sizes are correct.OutputFor each test case, print on a separate line the result of comparing a and b T-shirt sizes (lines "<", ">" or "=" without quotes).ExampleInput 6XXXS XSXXXL XLXL MXXL XXLXXXXXS ML MOutput < > > = < >
6XXXS XSXXXL XLXL MXXL XXLXXXXXS ML M
< > > = < >
1 second
256 megabytes
['implementation', 'implementation', 'strings', '*800']
I. Arranging Crystal Ballstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn the world of Compfestnesia, Pak Chanek discovers a secret underground dungeon. Inside it, there is a treasure chest that is surrounded by n statues that are arranged in a circular manner. The statues are numbered from 0 to n-1 with statue i being to the left of statue i+1 and statue n-1 being to the left of statue 0.Pak Chanek observes that each statue is holding a crystal ball with an integer between 0 and m-1 inclusive. Let's say the integer in the crystal ball of statue i is a_i.The dungeon provides instructions that every integer in the crystal balls must be 0 in order to open the treasure chest. To achieve that, Pak Chanek is given an integer k, and he can do zero or more operations. In a single operation, Pak Chanek does the following: Choose exactly k consecutive statues. In other words, choose the statues p, (p+1) \bmod n, (p+2) \bmod n, (p+3) \bmod n, \ldots, (p+k-1) \bmod n for some chosen index p. Do one of the following: For all chosen statues, change their values of a_i into (a_i+1) \bmod m. For all chosen statues, change their values of a_i into (a_i-1) \bmod m. Help Pak Chanek find the minimum possible number of operations to open the treasure chest.InputThe first line contains three integers n, m, and k (2 \leq n,m \leq 10^6, nm \leq 2 \cdot 10^6, 1 \leq k < n) — the number of statues, the bound of the integers in the crystal balls, and the number of statues that can be operated in a single operation.The second line contains n integers a_0,a_1,\ldots,a_{n-1} (0 \leq a_i < m) — the integers in the crystal balls.OutputIf it is possible to perform zero or more operations so that a_0=a_1=\ldots=a_{n-1}=0, output the minimum number of operations required. Otherwise, output -1.ExamplesInput 5 9 3 8 1 4 5 0 Output 7 Input 4 4 2 1 0 0 0 Output -1 Input 5 5 2 1 0 0 0 0 Output 10 NoteIn the first example, Pak Chanek can do the following operations: Do the a_i := (a_i-1) \bmod m operation 3 times for statues 1, 2, and 3. Now a=[8,7,1,2,0]. Do the a_i := (a_i-1) \bmod m operation 1 time for statues 3, 4, and 0. Now a=[7,7,1,1,8]. Do the a_i := (a_i+1) \bmod m operation 2 times for statues 4, 0, and 1. Now a=[0,0,1,1,1]. Do the a_i := (a_i-1) \bmod m operation 1 time for statues 2, 3, and 4. Now a=[0,0,0,0,0].
5 9 3 8 1 4 5 0
7
4 seconds
512 megabytes
['data structures', 'divide and conquer', 'divide and conquer', 'dp', 'geometry', 'graphs', 'number theory', '*3500']
H. MEX Tree Manipulationtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGiven a rooted tree, define the value of vertex u in the tree recursively as the MEX^\dagger of the values of its children. Note that it is only the children, not all of its descendants. In particular, the value of a leaf is 0.Pak Chanek has a rooted tree that initially only contains a single vertex with index 1, which is the root. Pak Chanek is going to do q queries. In the i-th query, Pak Chanek is given an integer x_i. Pak Chanek needs to add a new vertex with index i+1 as the child of vertex x_i. After adding the new vertex, Pak Chanek needs to recalculate the values of all vertices and report the sum of the values of all vertices in the current tree.^\dagger The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For example, the MEX of [0,1,1,2,6,7] is 3 and the MEX of [6,9] is 0.InputThe first line contains a single integer q (1 \le q \le 3 \cdot 10^5) — the number of operations.Each of the next q lines contains a single integer x_i (1 \leq x_i \leq i) — the description of the i-th query.OutputFor each query, print a line containing an integer representing the sum of the new values of all vertices in the tree after adding the vertex.ExamplesInput 7 1 1 3 2 5 2 1 Output 1 1 3 2 4 4 7 Input 8 1 1 1 1 5 6 7 8 Output 1 1 1 1 3 2 4 3 NoteIn the first example, the tree after the 6-th query will look like this. Vertex 7 is a leaf, so its value is 0. Vertex 6 is a leaf, so its value is 0. Vertex 5 only has a child with value 0, so its value is 1. Vertex 4 is a leaf, so its value is 0. Vertex 3 only has a child with value 0, so its value is 1. Vertex 2 has children with values 0 and 1, so its value is 2. Vertex 1 has children with values 1 and 2, so its value is 0. The sum of the values of all vertices is 0+0+1+0+1+2+0=4.
7 1 1 3 2 5 2 1
1 1 3 2 4 4 7
5 seconds
512 megabytes
['data structures', 'trees', '*3300']
G. Dangerous Laser Powertime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPak Chanek has an n \times m grid of portals. The portal on the i-th row and j-th column is denoted as portal (i,j). The portals (1,1) and (n,m) are on the north-west and south-east corner of the grid respectively.The portal (i,j) has two settings: Type t_{i,j}, which is either 0 or 1. Strength s_{i,j}, which is an integer between 1 and 10^9 inclusive. Each portal has 4 faces labelled with integers 0,1,2,3, which correspond to the north, east, south, and west direction respectively. When a laser enters face k of portal (i, j) with speed x_\text{in}, it leaves the portal going out of face (k+2+t_{i,j}) \bmod 4 with speed x_\text{out} = \max(x_\text{in},s_{i,j}). The portal also has to consume x_\text{out} - x_\text{in} units of energy. Pak Chanek is very bored today. He will shoot 4nm lasers with an initial speed of 1, one into each face of each portal. Each laser will travel throughout this grid of portals until it moves outside the grid or it has passed through 10^{100} portals.At the end, Pak Chanek thinks that a portal is good if and only if the total energy consumed by that portal modulo 2 is equal to its type. Given the strength settings of all portals, find a way to assign the type settings of each portal such that the number of good portals is maximised.InputThe first line contains two integers n and m (1 \le n, m \le 1000) — the number of rows and columns in the grid.The i-th of the next n lines contains m integers, with the j-th integer being s_{i,j} (1 \leq s_{i,j} \leq 10^9) — the strength of portal (i, j).OutputPrint n lines with each line containing a string of length m consisting of characters 0 or 1 representing the type settings. The j-th character in the i-th string is the type setting of portal (i, j).If there are multiple solutions, you can output any of them. ExamplesInput 2 3 8 8 2 6 5 7 Output 110 100 Input 1 2 420 69 Output 10 NoteIn the first example, let's consider the laser Pak Chanek shoots into face 1 of portal (2, 2). The laser travels as follows: The laser enters face 1 of portal (2, 2) with speed 1. It leaves the portal going out of face 3 with speed 5. Portal (2, 2) consumes 4 units of energy. The laser enters face 1 of portal (2, 1) with speed 5. It leaves the portal going out of face 0 with speed 6. Portal (2, 1) consumes 1 units of energy. The laser enters face 2 of portal (1, 1) with speed 6. It leaves the portal going out of face 1 with speed 8. Portal (1, 1) consumes 2 units of energy. The laser enters face 3 of portal (1, 2) with speed 8. It leaves the portal going out of face 2 with speed 8. Portal (1, 2) consumes 0 units of energy. The laser enters face 0 of portal (2, 2) with speed 8. It leaves the portal going out of face 2 with speed 8. Portal (2, 2) consumes 0 units of energy. The illustration of the travel of the laser above is as follows. As an example, consider portal (2, 3). We can calculate that the total energy consumed by that portal in the end will be 32. Since 32 \bmod 2 = 0 and t_{2,3} = 0, then it is a good portal.
2 3 8 8 2 6 5 7
110 100
4 seconds
512 megabytes
['constructive algorithms', 'dsu', 'sortings', '*3100']
F. Conditional Mixtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPak Chanek is given an array a of n integers. For each i (1 \leq i \leq n), Pak Chanek will write the one-element set \{a_i\} on a whiteboard.After that, in one operation, Pak Chanek may do the following: Choose two different sets S and T on the whiteboard such that S \cap T = \varnothing (S and T do not have any common elements). Erase S and T from the whiteboard and write S \cup T (the union of S and T) onto the whiteboard. After performing zero or more operations, Pak Chanek will construct a multiset M containing the sizes of all sets written on the whiteboard. In other words, each element in M corresponds to the size of a set after the operations.How many distinct^\dagger multisets M can be created by this process? Since the answer may be large, output it modulo 998\,244\,353.^\dagger Multisets B and C are different if and only if there exists a value k such that the number of elements with value k in B is different than the number of elements with value k in C.InputThe first line contains a single integer n (1 \le n \le 2000).The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n).OutputOutput the number of distinct multisets M modulo 998\,244\,353.ExamplesInput 6 1 1 2 1 4 3 Output 7 Input 7 3 5 4 3 7 4 5 Output 11 NoteIn the first example, the possible multisets M are \{1,1,1,1,1,1\}, \{1,1,1,1,2\}, \{1,1,1,3\}, \{1,1,2,2\}, \{1,1,4\}, \{1,2,3\}, and \{2,2,2\}.As an example, let's consider a possible sequence of operations. In the beginning, the sets are \{1\}, \{1\}, \{2\}, \{1\}, \{4\}, and \{3\}. Do an operation on sets \{1\} and \{3\}. Now, the sets are \{1\}, \{1\}, \{2\}, \{4\}, and \{1,3\}. Do an operation on sets \{2\} and \{4\}. Now, the sets are \{1\}, \{1\}, \{1,3\}, and \{2,4\}. Do an operation on sets \{1,3\} and \{2,4\}. Now, the sets are \{1\}, \{1\}, and \{1,2,3,4\}. The multiset M that is constructed is \{1,1,4\}.
6 1 1 2 1 4 3
7
2 seconds
512 megabytes
['combinatorics', 'dp', 'math', '*2600']
E. Hanging Heartstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek has n blank heart-shaped cards. Card 1 is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card i (i > 1) is hanging onto card p_i (p_i < i).In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation a of [1, 2, \dots, n]. Then, the number written on card i is a_i.After that, Pak Chanek must do the following operation n times while maintaining a sequence s (which is initially empty): Choose a card x such that no other cards are hanging onto it. Append the number written on card x to the end of s. If x \neq 1 and the number on card p_x is larger than the number on card x, replace the number on card p_x with the number on card x. Remove card x. After that, Pak Chanek will have a sequence s with n elements. What is the maximum length of the longest non-decreasing subsequence^\dagger of s at the end if Pak Chanek does all the steps optimally?^\dagger A sequence b is a subsequence of a sequence c if b can be obtained from c by deletion of several (possibly, zero or all) elements. For example, [3,1] is a subsequence of [3,2,1], [4,3,1] and [3,1], but not [1,3,3,7] and [3,10,4].InputThe first line contains a single integer n (2 \le n \le 10^5) — the number of heart-shaped cards.The second line contains n - 1 integers p_2, p_3, \dots, p_n (1 \le p_i < i) describing which card that each card hangs onto.OutputPrint a single integer — the maximum length of the longest non-decreasing subsequence of s at the end if Pak Chanek does all the steps optimally.ExamplesInput 6 1 2 1 4 2 Output 4 Input 2 1 Output 2 NoteThe following is the structure of the cards in the first example.Pak Chanek can choose the permutation a = [1, 5, 4, 3, 2, 6].Let w_i be the number written on card i. Initially, w_i = a_i. Pak Chanek can do the following operations in order: Select card 5. Append w_5 = 2 to the end of s. As w_4 > w_5, the value of w_4 becomes 2. Remove card 5. After this operation, s = [2]. Select card 6. Append w_6 = 6 to the end of s. As w_2 \leq w_6, the value of w_2 is left unchanged. Remove card 6. After this operation, s = [2, 6]. Select card 4. Append w_4 = 2 to the end of s. As w_1 \leq w_4, the value of w_1 is left unchanged. Remove card 4. After this operation, s = [2, 6, 2]. Select card 3. Append w_3 = 4 to the end of s. As w_2 > w_3, the value of w_2 becomes 4. Remove card 3. After this operation, s = [2, 6, 2, 4]. Select card 2. Append w_2 = 4 to the end of s. As w_1 \leq w_2, the value of w_1 is left unchanged. Remove card 2. After this operation, s = [2, 6, 2, 4, 4]. Select card 1. Append w_1 = 1 to the end of s. Remove card 1. After this operation, s = [2, 6, 2, 4, 4, 1]. One of the longest non-decreasing subsequences of s = [2, 6, 2, 4, 4, 1] is [2, 2, 4, 4]. Thus, the length of the longest non-decreasing subsequence of s is 4. It can be proven that this is indeed the maximum possible length.
6 1 2 1 4 2
4
1 second
256 megabytes
['constructive algorithms', 'data structures', 'dfs and similar', 'dp', 'greedy', 'trees', '*1800']
D. Knowledge Cardstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek, a renowned scholar, invented a card puzzle using his knowledge. In the puzzle, you are given a board with n rows and m columns. Let (r, c) represent the cell in the r-th row and the c-th column.Initially, there are k cards stacked in cell (1, 1). Each card has an integer from 1 to k written on it. More specifically, the i-th card from the top of the stack in cell (1, 1) has the number a_i written on it. It is known that no two cards have the same number written on them. In other words, the numbers written on the cards are a permutation of integers from 1 to k. All other cells are empty.You need to move the k cards to cell (n, m) to create another stack of cards. Let b_i be the number written on the i-th card from the top of the stack in cell (n, m). You should create the stack in cell (n, m) in such a way so that b_i = i for all 1 \leq i \leq k.In one move, you can remove the top card from a cell and place it onto an adjacent cell (a cell that shares a common side). If the target cell already contains one or more cards, you place your card on the top of the stack. You must do each operation while satisfying the following restrictions: Each cell other than (1,1) and (n,m) must not have more than one card on it. You cannot move a card onto cell (1,1). You cannot move a card from cell (n,m). Given the values of n, m, k and the array a, determine if the puzzle is solvable.InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 2 \cdot 10^4) — the number of test cases. The following lines contain the description of each test case.The first line of each test case contains three integers n, m, and k (3 \leq n, m \leq 10^6, nm \leq 10^6, 1 \leq k \leq 10^5) — the size of the board and the number of cards.The second line of the test case contains k integers a_1, a_2, \ldots, a_k — the array a, representing the numbers written on the cards. The values of a are a permutation of integers from 1 to k.It is guaranteed that the sum of nm and k over all test cases do not exceed 10^6 and 10^5 respectively.OutputFor each test case, output "YA" (without quotes) if it is possible and "TIDAK" (without quotes) otherwise, which mean yes and no in Indonesian respectively.You can output "YA" and "TIDAK" in any case (for example, strings "tiDAk", "tidak", and "Tidak" will be recognised as a negative response).ExampleInput 43 3 63 6 4 1 2 53 3 101 2 3 4 5 6 7 8 9 105 4 42 1 3 43 4 1010 4 9 3 5 6 8 2 7 1Output YA TIDAK YA YA NoteIn the first test case, the following is one way the puzzle can be done: Move the card with 3 written on it from cell (1, 1) to cell (1, 2), then cell (1, 3). Move the card with 6 written on it from cell (1, 1) to cell (2, 1), then cell (3, 1), then cell (3, 2), then cell (3, 3). Move the card with 4 written on it from cell (1, 1) to cell (1, 2). Move the card with 1 written on it from cell (1, 1) to cell (2, 1), then cell (2, 2), then cell (2, 3). Move the card with 2 written on it from cell (1, 1) to cell (2, 1), then cell (2, 2). Move the card with 5 written on it from cell (1, 1) to cell (2, 1), then cell (3, 1), then cell (3, 2), then cell (3, 3). Move the card with 2 written on it from cell (2, 2) to cell (2, 1). Move the card with 4 written on it from cell (1, 2) to cell (2, 2), then cell (3, 2), then cell (3, 3). Move the card with 3 written on it from cell (1, 3) to cell (1, 2), then cell (2, 2), then cell (3, 2), then cell (3, 3). Move the card with 2 written on it from cell (2, 1) to cell (3, 1), then cell (3, 2), then cell (3, 3). Move the card with 1 written on it from cell (2, 3) to cell (3, 3). An animated illustration regarding the process mentioned above is as follows:
43 3 63 6 4 1 2 53 3 101 2 3 4 5 6 7 8 9 105 4 42 1 3 43 4 1010 4 9 3 5 6 8 2 7 1
YA TIDAK YA YA
1 second
256 megabytes
['constructive algorithms', 'data structures', '*1500']
C. Bricks and Bagstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n bricks numbered from 1 to n. Brick i has a weight of a_i.Pak Chanek has 3 bags numbered from 1 to 3 that are initially empty. For each brick, Pak Chanek must put it into one of the bags. After this, each bag must contain at least one brick.After Pak Chanek distributes the bricks, Bu Dengklek will take exactly one brick from each bag. Let w_j be the weight of the brick Bu Dengklek takes from bag j. The score is calculated as |w_1 - w_2| + |w_2 - w_3|, where |x| denotes the absolute value of x.It is known that Bu Dengklek will take the bricks in such a way that minimises the score. What is the maximum possible final score if Pak Chanek distributes the bricks optimally?InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 2 \cdot 10^4) — the number of test cases. The following lines contain the description of each test case.The first line of each test case contains an integer n (3 \leq n \leq 2 \cdot 10^5) — the number of bricks.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the weights of the bricks.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a line containing an integer representing the maximum possible final score if Pak Chanek distributes the bricks optimally.ExampleInput 353 1 5 2 3417 8 19 458265 265 265 265 265 265 265 265Output 6 63 0 NoteIn the first test case, one way of achieving a final score of 6 is to do the following: Put bricks 1, 4, and 5 into bag 1. Put brick 3 into bag 2. Put brick 2 into bag 3. If Pak Chanek distributes the bricks that way, a way Bu Dengklek can take the bricks is: Take brick 5 from bag 1. Take brick 3 from bag 2. Take brick 2 from bag 3. The score is |a_5 - a_3| + |a_3 - a_2| = |3 - 5| + |5 - 1| = 6. It can be shown that Bu Dengklek cannot get a smaller score from this distribution.It can be shown that there is no other distribution that results in a final score bigger than 6.
353 1 5 2 3417 8 19 458265 265 265 265 265 265 265 265
6 63 0
1 second
256 megabytes
['constructive algorithms', 'games', 'greedy', 'sortings', '*1400']
B. Jumbo Extra Cheese 2time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek has n two-dimensional slices of cheese. The i-th slice of cheese can be represented as a rectangle of dimensions a_i \times b_i. We want to arrange them on the two-dimensional plane such that: Each edge of each cheese is parallel to either the x-axis or the y-axis. The bottom edge of each cheese is a segment of the x-axis. No two slices of cheese overlap, but their sides can touch. They form one connected shape. Note that we can arrange them in any order (the leftmost slice of cheese is not necessarily the first slice of cheese). Also note that we can rotate each slice of cheese in any way as long as all conditions still hold.Find the minimum possible perimeter of the constructed shape.InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 2 \cdot 10^4) — the number of test cases. The following lines contain the description of each test case.The first line of each test case contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the number of slices of cheese Pak Chanek has.The i-th of the next n lines of each test case contains two integers a_i and b_i (1 \leq a_i,b_i \leq 10^9) — the dimensions of the i-th slice of cheese.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a line containing an integer representing the minimum possible perimeter of the constructed shape.ExampleInput 344 14 51 12 332 42 62 312 65Output 26 24 134 NoteIn the first test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is 2+5+1+1+1+1+3+1+5+1+2+3=26. It can be shown that we cannot get a smaller perimeter.Consider the following invalid arrangement.Even though the perimeter of the shape above is 24, it does not satisfy all conditions of the problem. The bottom edge of the 1 \times 1 slice of cheese is not a segment of the x-axis.In the second test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is 2+2+2+3+2+3+2+2+2+4=24. It can be shown that we cannot get a smaller perimeter.
344 14 51 12 332 42 62 312 65
26 24 134
1 second
256 megabytes
['geometry', 'greedy', 'sortings', '*800']
A. Factorise N+Mtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek has a prime number^\dagger n. Find a prime number m such that n + m is not prime.^\dagger A prime number is a number with exactly 2 factors. The first few prime numbers are 2,3,5,7,11,13,\ldots. In particular, 1 is not a prime number.InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases. The following lines contain the description of each test case.The only line of each test case contains a prime number n (2 \leq n \leq 10^5).OutputFor each test case, output a line containing a prime number m (2 \leq m \leq 10^5) such that n + m is not prime. It can be proven that under the constraints of the problem, such m always exists.If there are multiple solutions, you can output any of them. ExampleInput 37275619Output 2 7 47837 NoteIn the first test case, m = 2, which is prime, and n + m = 7 + 2 = 9, which is not prime.In the second test case, m = 7, which is prime, and n + m = 2 + 7 = 9, which is not prime.In the third test case, m = 47837, which is prime, and n + m = 75619 + 47837 = 123456, which is not prime.
37275619
2 7 47837
1 second
256 megabytes
['constructive algorithms', 'number theory', '*800']
F. Keyboard Designtime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputMonocarp has a dictionary of n words, consisting of 12 first letters of the Latin alphabet. The words are numbered from 1 to n. In every pair of adjacent characters in each word, the characters are different. For every word i, Monocarp also has an integer c_i denoting how often he uses this word.Monocarp wants to design a keyboard that would allow him to type some of the words easily. A keyboard can be denoted as a sequence of 12 first letters of the Latin alphabet, where each letter from a to l appears exactly once.A word can be typed with the keyboard easily if, for every pair of adjacent characters in the word, these characters are adjacent in the keyboard as well. The optimality of the keyboard is the sum of c_i over all words i that can be typed easily with it.Help Monocarp to design a keyboard with the maximum possible optimality.InputThe first line contains one integer n (1 \le n \le 1000) — the number of words.Then, n lines follow. The i-th of them contains an integer c_i (1 \le c_i \le 10^5) and a string s_i (2 \le |s_i| \le 2000) denoting the i-th word. Each character of s_i is one of 12 first letters of Latin alphabet, in lowercase. For every j \in [1, |s_i| - 1], the j-th character of s_i is different from the (j+1)-th one.Additional constraint on the input: \sum \limits_{i=1}^{n} |s_i| \le 2000.OutputPrint a sequence of 12 first letters of the Latin alphabet, where each letter from a to l appears exactly once, denoting the optimal keyboard. If there are multiple answers, you may print any of them.ExamplesInput 3 7 abacaba 10 cba 4 db Output hjkildbacefg Input 1 100 abca Output abcdefghijkl
3 7 abacaba 10 cba 4 db
hjkildbacefg
4 seconds
1024 megabytes
['bitmasks', 'data structures', 'dp', 'string suffix structures', 'strings', '*2600']
E. Cleaning Robottime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a hallway, which can be represented as the matrix with 2 rows and n columns. Let's denote the cell on the intersection of the i-th row and the j-th column as (i, j). The distance between the cells (i_1, j_1) and (i_2, j_2) is |i_1 - i_2| + |j_1 - j_2|.There is a cleaning robot in the cell (1, 1). Some cells of the hallway are clean, other cells are dirty (the cell with the robot is clean). You want to clean the hallway, so you are going to launch the robot to do this.After the robot is launched, it works as follows. While at least one cell is dirty, the robot chooses the closest (to its current cell) cell among those which are dirty, moves there and cleans it (so the cell is no longer dirty). After cleaning a cell, the robot again finds the closest dirty cell to its current cell, and so on. This process repeats until the whole hallway is clean.However, there is a critical bug in the robot's program. If at some moment, there are multiple closest (to the robot's current position) dirty cells, the robot malfunctions.You want to clean the hallway in such a way that the robot doesn't malfunction. Before launching the robot, you can clean some (possibly zero) of the dirty cells yourself. However, you don't want to do too much dirty work yourself while you have this nice, smart (yet buggy) robot to do this. Note that you cannot make a clean cell dirty.Calculate the maximum possible number of cells you can leave dirty before launching the robot, so that it doesn't malfunction.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of columns in the hallway.Then two lines follow, denoting the 1-st and the 2-nd row of the hallway. These lines contain n characters each, where 0 denotes a clean cell and 1 denotes a dirty cell. The starting cell of the robot (1, 1) is clean.OutputPrint one integer — the maximum possible number of cells you can leave dirty before launching the robot, so that it doesn't malfunction.ExamplesInput 2 01 11 Output 2 Input 2 01 01 Output 2 Input 4 0101 1011 Output 4 Input 4 0000 0000 Output 0 Input 5 00011 10101 Output 4 Input 6 011111 111111 Output 8 Input 10 0101001010 1010100110 Output 6 NoteIn the first example, you can clean the cell (1, 2), so the path of the robot is (1, 1) \rightarrow (2, 1) \rightarrow (2, 2).In the second example, you can leave the hallway as it is, so the path of the robot is (1, 1) \rightarrow (1, 2) \rightarrow (2, 2).In the third example, you can clean the cell (1, 2), so the path of the robot is (1, 1) \rightarrow (2, 1) \rightarrow (2, 3) \rightarrow (2, 4) \rightarrow (1, 4).In the fourth example, the hallway is already clean. Maybe you have launched the robot earlier?
2 01 11
2
3 seconds
512 megabytes
['bitmasks', 'dp', '*2400']
D. Reset K Edgestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree, consisting of n vertices. The vertices are numbered from 1 to n, the root is the vertex 1.You can perform the following operation at most k times: choose an edge (v, u) of the tree such that v is a parent of u; remove the edge (v, u); add an edge (1, u) (i. e. make u with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all its children is 1.What's the smallest height of the tree that can be achieved?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains two integers n and k (2 \le n \le 2 \cdot 10^5; 0 \le k \le n - 1) — the number of vertices in the tree and the maximum number of operations you can perform.The second line contains n-1 integers p_2, p_3, \dots, p_n (1 \le p_i < i) — the parent of the i-th vertex. Vertex 1 is the root.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most k operations.ExampleInput 55 11 1 2 25 21 1 2 26 01 2 3 4 56 11 2 3 4 54 31 1 1Output 2 1 5 3 1
55 11 1 2 25 21 1 2 26 01 2 3 4 56 11 2 3 4 54 31 1 1
2 1 5 3 1
4 seconds
256 megabytes
['binary search', 'data structures', 'dfs and similar', 'graphs', 'greedy', 'trees', '*1900']
C. Card Gametime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a game with n cards (n is even). Each card has a number written on it, between 1 and n. All numbers on the cards are different. We say that a card with number x is stronger than a card with number y if x > y.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly \frac{n}{2} cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose n = 4, Alex receives the cards [2, 3], and Boris receives the cards [1, 4]. Then the game may go as follows: if Alex plays the card 2, then Boris has to respond with the card 4. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is 1; he plays it, and Alex responds with the card 3. So, the game ends in a draw; if Alex plays the card 3, then Boris has to respond with the card 4. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is 1; he plays it, and Alex responds with the card 2. So, the game ends in a draw. So, in this case, the game ends in a draw.InputThe first line contains one integer t (1 \le t \le 30) — the number of test cases.Then, t lines follow. The i-th line contains one even integer n (2 \le n \le 60).OutputFor each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo 998244353.ExampleInput 5246860Output 1 0 1 3 2 1 12 7 1 42 27 1 341102826 248150916 1 NoteIn the first test case, Alex wins if he receives the card 2 (he plays it, and Boris cannot respond). If Alex receives the card 1, the game ends in a draw.In the second test case: Alex wins if he receives the cards [3, 4], [2, 4] or [1, 4]; Boris wins if Alex receives the cards [1, 2] or [1, 3]; the game ends in a draw if Alex receives the cards [2, 3].
5246860
1 0 1 3 2 1 12 7 1 42 27 1 341102826 248150916 1
2 seconds
512 megabytes
['combinatorics', 'constructive algorithms', 'dp', 'games', '*1500']
B. Array Recoverytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor an array of non-negative integers a of size n, we construct another array d as follows: d_1 = a_1, d_i = |a_i - a_{i - 1}| for 2 \le i \le n.Your task is to restore the array a from a given array d, or to report that there are multiple possible arrays. InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains one integer n (1 \le n \le 100) — the size of the arrays a and d.The second line contains n integers d_1, d_2, \dots, d_n (0 \le d_i \le 100) — the elements of the array d.It can be shown that there always exists at least one suitable array a under these constraints.OutputFor each test case, print the elements of the array a, if there is only one possible array a. Otherwise, print -1.ExampleInput 341 0 2 532 6 350 0 0 0 0Output 1 1 3 8 -1 0 0 0 0 0 NoteIn the second example, there are two suitable arrays: [2, 8, 5] and [2, 8, 11].
341 0 2 532 6 350 0 0 0 0
1 1 3 8 -1 0 0 0 0 0
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1100']
A. Immobile Knighttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a chess board of size n \times m. The rows are numbered from 1 to n, the columns are numbered from 1 to m.Let's call a cell isolated if a knight placed in that cell can't move to any other cell on the board. Recall that a chess knight moves two cells in one direction and one cell in a perpendicular direction: Find any isolated cell on the board. If there are no such cells, print any cell on the board.InputThe first line contains a single integer t (1 \le t \le 64) — the number of testcases.The only line of each testcase contains two integers n and m (1 \le n, m \le 8) — the number of rows and columns of the board.OutputFor each testcase, print two integers — the row and the column of any isolated cell on the board. If there are no such cells, print any cell on the board.ExampleInput 31 78 83 3Output 1 7 7 2 2 2 NoteIn the first testcase, all cells are isolated. A knight can't move from any cell of the board to any other one. Thus, any cell on board is a correct answer.In the second testcase, there are no isolated cells. On a normal chess board, a knight has at least two moves from any cell. Thus, again, any cell is a correct answer.In the third testcase, only the middle cell of the board is isolated. The knight can move freely around the border of the board, but can't escape the middle.
31 78 83 3
1 7 7 2 2 2
2 seconds
256 megabytes
['implementation', '*800']
H. Palindrome Addictstime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYour task is to maintain a queue consisting of lowercase English letters as follows: "push c": insert a letter c at the back of the queue; "pop": delete a letter from the front of the queue. Initially, the queue is empty. After each operation, you are asked to count the number of distinct palindromic substrings in the string that are obtained by concatenating the letters from the front to the back of the queue.Especially, the number of distinct palindromic substrings of the empty string is 0. A string s[1..n] of length n is palindromic if s[i] = s[n-i+1] for every 1 \leq i \leq n. The string s[l..r] is a substring of string s[1..n] for every 1 \leq l \leq r \leq n. Two strings s[1..n] and t[1..m] are distinct, if at least one of the following holds. n \neq m; s[i] \neq t[i] for some 1 \leq i \leq \min\{n,m\}. InputThe first line is an integer q (1 \leq q \leq 10^6), indicating the number of operations.Then q lines follow. Each of the following lines contains one of the operations as follows. "push c": insert a letter c at the back of the queue, where c is a lowercase English letter; "pop": delete a letter from the front of the queue. It is guaranteed that no "pop" operation will be performed when the queue is empty.OutputAfter each operation, print the number of distinct palindromic substrings in the string presented in the queue. ExampleInput 12 push a pop push a push a push b push b push a push a pop pop pop push b Output 1 0 1 2 3 4 5 6 5 4 3 4 NoteLet s_k be the string presented in the queue after the k-th operation, and let c_k be the number of distinct palindromic substrings of s_k. The following table shows the details of the example. ks_kc_k1a12\textsf{empty}03a14aa25aab36aabb47aabba58aabbaa69abbaa510bbaa411baa312baab4 It is worth pointing out that After the 2-nd operation, the string is empty and thus has no substrings. So the answer is 0; After the 8-th operation, the string is "aabbaa". The 6 distinct palindromic substrings are "a", "aa", "aabbaa", "abba", "b", and "bb".
12 push a pop push a push a push b push b push a push a pop pop pop push b
1 0 1 2 3 4 5 6 5 4 3 4
2 seconds
1024 megabytes
['data structures', 'strings', '*3300']
G. Anti-Increasing Addictstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an n \times n grid. We write (i, j) to denote the cell in the i-th row and j-th column. For each cell, you are told whether yon can delete it or not. Given an integer k, you are asked to delete exactly (n-k+1)^2 cells from the grid such that the following condition holds. You cannot find k not deleted cells (x_1, y_1), (x_2, y_2), \dots, (x_k, y_k) that are strictly increasing, i.e., x_i < x_{i+1} and y_i < y_{i+1} for all 1 \leq i < k. Your task is to find a solution, or report that it is impossible. InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 10^5) — the number of test cases. The following lines contain the description of each test case.The first line of each test case contains two integers n and k (2 \leq k \leq n \leq 1000). Then n lines follow. The i-th line contains a binary string s_i of length n. The j-th character of s_i is 1 if you can delete cell (i, j), and 0 otherwise.It's guaranteed that the sum of n^2 over all test cases does not exceed 10^6.OutputFor each test case, if there is no way to delete exactly (n-k+1)^2 cells to meet the condition, output "NO" (without quotes).Otherwise, output "YES" (without quotes). Then, output n lines. The i-th line should contain a binary string t_i of length n. The j-th character of t_i is 0 if cell (i, j) is deleted, and 1 otherwise.If there are multiple solutions, you can output any of them.You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).ExampleInput 42 210014 311100101101001115 501111101111101111101111105 21000001111011110111101111Output YES 01 11 YES 0011 1111 1111 1100 NO YES 01111 11000 10000 10000 10000 NoteFor the first test case, you only have to delete cell (1, 1).For the second test case, you could choose to delete cells (1,1), (1,2), (4,3) and (4,4).For the third test case, it is no solution because the cells in the diagonal will always form a strictly increasing sequence of length 5.
42 210014 311100101101001115 501111101111101111101111105 21000001111011110111101111
YES 01 11 YES 0011 1111 1111 1100 NO YES 01111 11000 10000 10000 10000
2 seconds
512 megabytes
['constructive algorithms', 'dp', 'greedy', 'math', '*2900']
F. Connectivity Addictstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Given a simple undirected graph with n vertices numbered from 1 to n, your task is to color all the vertices such that for every color c, the following conditions hold: The set of vertices with color c is connected; s_c \leq n_c^2, where n_c is the number of vertices with color c, and s_c is the sum of degrees of vertices with color c. It can be shown that there always exists a way to color all the vertices such that the above conditions hold. Initially, you are only given the number n of vertices and the degree of each vertex. In each query, you can choose a vertex u. As a response, you will be given the k-th edge incident to u, if this is the k-th query on vertex u. You are allowed to make at most n queries.An undirected graph is simple if it does not contain multiple edges or self-loops.The degree of a vertex is the number of edges incident to it. A set S of vertices is connected if for every two different vertices u, v \in S, there is a path, which only passes through vertices in S, that connects u and v. That is, there is a sequence of edges (u_1, v_1), (u_2, v_2), \dots, (u_k, v_k) with k \geq 1 such that u_1 = u, v_k = v, and v_i = u_{i+1} for every 1 \leq i < k; and u_k \in S and v_k \in S for every 1 \leq i \leq k. Especially, a set containing only one vertex is connected. InteractionEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — the number of test cases. The following lines contain the description and the interactive section of each test case.For each test case, you begin the interaction by reading an integer n (1\le n \le 1000) in the first line, indicating the number of vertices in the graph.The second line contains n integers d_1, d_2, \dots, d_n (0 \leq d_i \leq n - 1), where d_i is the degree of vertex i. To make a query on vertex u (1 \leq u \leq n), you should output "? u" in a separate line. If this is the k-th query on vertex u, vertex e_{u, k} will be given in the next separate line, where \left(u, e_{u, k}\right) is the k-th edge incident to vertex u. In case of k > d_u, define e_{u, k} = -1. You should make no more than n "?" queries.To give the answer, you should output "! c_1 c_2 \dots c_n" in a separate line, where c_i (1 \leq c_i \leq n) is the color of vertex i. After that, your program should continue to the next test case, or terminate if this is the last test case. It is guaranteed that the graph is a simple undirected graph.It is guaranteed that the sum of n over all test cases does not exceed 1000.In case your query format is invalid, or you have made more than n "?" 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 contains an integer t (1 \leq t \leq 1000), indicating the number of test cases. The following lines contain the description of each test case.The first line of each test case contains an integer n (1 \leq n \leq 1000), indicating the number of vertices in the graph. Then n lines follow. The i-th line contains an integer d_i (0 \leq d_i \leq n - 1), indicating the degree of vertex i, and then d_i distinct integers e_{i,1}, e_{i,2}, \dots, e_{i,d_i} (1 \leq e_{i, j} \leq n and e_{i,j} \neq i), where \left(i, e_{i,j}\right) is the j-th edge incident to vertex i.It should be guaranteed that the graph is a simple undirected graph.It should be guaranteed that the sum of n over all test cases does not exceed 1000.ExampleInput 1 5 2 2 2 2 0 2 4 2 4 Output ? 1 ? 1 ? 3 ? 3 ! 1 1 2 2 3 NoteIn the example, there is only one test case. In the test case, there are n = 5 vertices with vertices 1, 2, 3, 4 of degree 2 and vertex 5 of degree 0. It is obvious that vertex 5 is isolated, i.e., it does not connect to any other vertices. A possible interaction is shown in the sample input and output, where 4 "?" queries are made on vertex 1 twice and vertex 3 twice. According to the responses to these queries, we know that each of vertex 1 and vertex 3 connects to two vertices 2 and 4. A possible solution is shown in the sample output, where vertex 1 and vertex 2 are colored by 1, vertex 3 and vertex 4 are colored by 2, and vertex 5 is colored by 3. It can be seen that this solution satisfies the required conditions as follows. For color c = 1, vertex 1 and vertex 2 are connected. Moreover, n_1 = 2 and s_1 = d_1 + d_2 = 2 + 2 = 4 \leq n_1^2 = 2^2 = 4; For color c = 2, vertex 3 and vertex 4 are connected. Moreover, n_2 = 2 and s_2 = d_3 + d_4 = 2 + 2 = 4 \leq n_2^2 = 2^2 = 4; For color c = 3, there is only one vertex (vertex 5) colored by 3. Moreover, n_3 = 1 and s_3 = d_5 = 0 \leq n_3^2 = 1^2 = 1.
1 5 2 2 2 2 0 2 4 2 4
? 1 ? 1 ? 3 ? 3 ! 1 1 2 2 3
2 seconds
512 megabytes
['constructive algorithms', 'dsu', 'graphs', 'greedy', 'interactive', 'shortest paths', 'trees', '*2400']
E. Balance Addictstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGiven an integer sequence a_1, a_2, \dots, a_n of length n, your task is to compute the number, modulo 998244353, of ways to partition it into several non-empty continuous subsequences such that the sums of elements in the subsequences form a balanced sequence.A sequence s_1, s_2, \dots, s_k of length k is said to be balanced, if s_{i} = s_{k-i+1} for every 1 \leq i \leq k. For example, [1, 2, 3, 2, 1] and [1,3,3,1] are balanced, but [1,5,15] is not. Formally, every partition can be described by a sequence of indexes i_1, i_2, \dots, i_k of length k with 1 = i_1 < i_2 < \dots < i_k \leq n such that k is the number of non-empty continuous subsequences in the partition; For every 1 \leq j \leq k, the j-th continuous subsequence starts with a_{i_j}, and ends exactly before a_{i_{j+1}}, where i_{k+1} = n + 1. That is, the j-th subsequence is a_{i_j}, a_{i_j+1}, \dots, a_{i_{j+1}-1}. There are 2^{n-1} different partitions in total. Let s_1, s_2, \dots, s_k denote the sums of elements in the subsequences with respect to the partition i_1, i_2, \dots, i_k. Formally, for every 1 \leq j \leq k, s_j = \sum_{i=i_{j}}^{i_{j+1}-1} a_i = a_{i_j} + a_{i_j+1} + \dots + a_{i_{j+1}-1}. For example, the partition [1\,|\,2,3\,|\,4,5,6] of sequence [1,2,3,4,5,6] is described by the sequence [1,2,4] of indexes, and the sums of elements in the subsequences with respect to the partition is [1,5,15].Two partitions i_1, i_2, \dots, i_k and i'_1, i'_2, \dots, i'_{k'} (described by sequences of indexes) are considered to be different, if at least one of the following holds. k \neq k', i_j \neq i'_j for some 1 \leq j \leq \min\left\{ k, k' \right\}. InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 10^5) — the number of test cases. The following lines contain the description of each test case.The first line of each test case contains an integer n (1 \leq n \leq 10^5), indicating the length of the sequence a.The second line of each test case contains n integers a_1, a_2, \dots, a_n (0 \leq a_i \leq 10^9), indicating the elements of the sequence a.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output the number of partitions with respect to which the sum of elements in each subsequence is balanced, modulo 998244353.ExampleInput 61100000000021 140 0 1 051 2 3 2 151 3 5 7 9320 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0Output 1 2 3 4 2 150994942 NoteFor the first test case, there is only one way to partition a sequence of length 1, which is itself and is, of course, balanced. For the second test case, there are 2 ways to partition it: The sequence [1, 1] itself, then s = [2] is balanced; Partition into two subsequences [1\,|\,1], then s = [1, 1] is balanced. For the third test case, there are 3 ways to partition it: The sequence [0, 0, 1, 0] itself, then s = [1] is balanced; [0 \,|\, 0, 1 \,|\, 0], then s = [0, 1, 0] is balanced; [0, 0 \,|\, 1 \,|\, 0], then s = [0, 1, 0] is balanced. For the fourth test case, there are 4 ways to partition it: The sequence [1, 2, 3, 2, 1] itself, then s = [9] is balanced; [1, 2 \,|\, 3 \,|\, 2, 1], then s = [3, 3, 3] is balanced; [1 \,|\, 2, 3, 2 \,|\, 1], then s = [1, 7, 1] is balanced; [1 \,|\, 2 \,|\, 3 \,|\, 2 \,|\, 1], then s = [1, 2, 3, 2, 1] is balanced. For the fifth test case, there are 2 ways to partition it: The sequence [1, 3, 5, 7, 9] itself, then s = [25] is balanced; [1, 3, 5 \,|\, 7 \,|\, 9], then s = [9, 7, 9] is balanced. For the sixth test case, every possible partition should be counted. So the answer is 2^{32-1} \equiv 150994942 \pmod {998244353}.
61100000000021 140 0 1 051 2 3 2 151 3 5 7 9320 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 2 3 4 2 150994942
2 seconds
512 megabytes
['combinatorics', 'dp', 'math', 'two pointers', '*2300']
D. Permutation Addictstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGiven a permutation a_1, a_2, \dots, a_n of integers from 1 to n, and a threshold k with 0 \leq k \leq n, you compute a sequence b_1, b_2, \dots, b_n as follows. For every 1 \leq i \leq n in increasing order, let x = a_i. If x \leq k, set b_{x} to the last element a_j (1 \leq j < i) that a_j > k. If no such element a_j exists, set b_{x} = n+1. If x > k, set b_{x} to the last element a_j (1 \leq j < i) that a_j \leq k. If no such element a_j exists, set b_{x} = 0. Unfortunately, after the sequence b_1, b_2, \dots, b_n has been completely computed, the permutation a_1, a_2, \dots, a_n and the threshold k are discarded. Now you only have the sequence b_1, b_2, \dots, b_n. Your task is to find any possible permutation a_1, a_2, \dots, a_n and threshold k that produce the sequence b_1, b_2, \dots, b_n. It is guaranteed that there exists at least one pair of permutation a_1, a_2, \dots, a_n and threshold k that produce the sequence b_1, b_2, \dots, b_n.A permutation of integers from 1 to n is a sequence of length n which contains all integers from 1 to n exactly once. InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 10^5) — the number of test cases. The following lines contain the description of each test case.The first line of each test case contains an integer n (1 \leq n \leq 10^5), indicating the length of the permutation a.The second line of each test case contains n integers b_1, b_2, \dots, b_n (0 \leq b_i \leq n+1), indicating the elements of the sequence b.It is guaranteed that there exists at least one pair of permutation a_1, a_2, \dots, a_n and threshold k that produce the sequence b_1, b_2, \dots, b_n.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output the threshold k (0 \leq k \leq n) in the first line, and then output the permutation a_1, a_2, \dots, a_n (1 \leq a_i \leq n) in the second line such that the permutation a_1, a_2, \dots, a_n and threshold k produce the sequence b_1, b_2, \dots, b_n. If there are multiple solutions, you can output any of them.ExampleInput 345 3 1 267 7 7 3 3 364 4 4 0 0 0Output 2 1 3 2 4 3 1 2 3 4 5 6 3 6 5 4 3 2 1 NoteFor the first test case, permutation a = [1,3,2,4] and threshold k = 2 will produce sequence b as follows. When i = 1, x = a_i = 1 \leq k, there is no a_j (1 \leq j < i) that a_j > k. Therefore, b_1 = n + 1 = 5. When i = 2, x = a_i = 3 > k, the last element a_j that a_j \leq k is a_1. Therefore, b_3 = a_1 = 1. When i = 3, x = a_i = 2 \leq k, the last element a_j that a_j > k is a_2. Therefore, b_2 = a_2 = 3. When i = 4, x = a_i = 4 > k, the last element a_j that a_j \leq k is a_3. Therefore, b_4 = a_3 = 2. Finally, we obtain sequence b = [5,3,1,2]. For the second test case, permutation a = [1,2,3,4,5,6] and threshold k = 3 will produce sequence b as follows. When i = 1, 2, 3, a_i \leq k, there is no a_j (1 \leq j < i) that a_j > k. Therefore, b_1 = b_2 = b_3 = n + 1 = 7. When i = 4, 5, 6, a_i > k, the last element a_j that a_j \leq k is a_3. Therefore, b_4 = b_5 = b_6 = a_3 = 3. Finally, we obtain sequence b = [7,7,7,3,3,3]. For the third test case, permutation a = [6,5,4,3,2,1] and threshold k = 3 will produce sequence b as follows. When i = 1, 2, 3, a_i > k, there is no a_j (1 \leq j < i) that a_j \leq k. Therefore, b_4 = b_5 = b_6 = 0. When i = 4, 5, 6, a_i \leq k, the last element a_j that a_j > k is a_3. Therefore, b_1 = b_2 = b_3 = a_3 = 4. Finally, we obtain sequence b = [4,4,4,0,0,0].
345 3 1 267 7 7 3 3 364 4 4 0 0 0
2 1 3 2 4 3 1 2 3 4 5 6 3 6 5 4 3 2 1
2 seconds
512 megabytes
['constructive algorithms', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'trees', '*1900']
C. Even Number Addictstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game on a sequence a_1, a_2, \dots, a_n of length n. They move in turns and Alice moves first.In the turn of each player, he or she should select an integer and remove it from the sequence. The game ends when there is no integer left in the sequence. Alice wins if the sum of her selected integers is even; otherwise, Bob wins. Your task is to determine who will win the game, if both players play optimally.InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The following lines contain the description of each test case.The first line of each test case contains an integer n (1 \leq n \leq 100), indicating the length of the sequence.The second line of each test case contains n integers a_1, a_2, \dots, a_n (-10^9 \leq a_i \leq 10^9), indicating the elements of the sequence.OutputFor each test case, output "Alice" (without quotes) if Alice wins and "Bob" (without quotes) otherwise.ExampleInput 431 3 541 3 5 741 2 3 4410 20 30 40Output Alice Alice Bob Alice NoteIn the first and second test cases, Alice always selects two odd numbers, so the sum of her selected numbers is always even. Therefore, Alice always wins.In the third test case, Bob has a winning strategy that he always selects a number with the same parity as Alice selects in her last turn. Therefore, Bob always wins.In the fourth test case, Alice always selects two even numbers, so the sum of her selected numbers is always even. Therefore, Alice always wins.
431 3 541 3 5 741 2 3 4410 20 30 40
Alice Alice Bob Alice
2 seconds
512 megabytes
['dp', 'games', 'greedy', 'math', '*1500']
B. Prefix Sum Addictstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSuppose a_1, a_2, \dots, a_n is a sorted integer sequence of length n such that a_1 \leq a_2 \leq \dots \leq a_n. For every 1 \leq i \leq n, the prefix sum s_i of the first i terms a_1, a_2, \dots, a_i is defined by s_i = \sum_{k=1}^i a_k = a_1 + a_2 + \dots + a_i. Now you are given the last k terms of the prefix sums, which are s_{n-k+1}, \dots, s_{n-1}, s_{n}. Your task is to determine whether this is possible. Formally, given k integers s_{n-k+1}, \dots, s_{n-1}, s_{n}, the task is to check whether there is a sequence a_1, a_2, \dots, a_n such that a_1 \leq a_2 \leq \dots \leq a_n, and s_i = a_1 + a_2 + \dots + a_i for all n-k+1 \leq i \leq n. InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 10^5) — the number of test cases. The following lines contain the description of each test case.The first line of each test case contains two integers n (1 \leq n \leq 10^5) and k (1 \leq k \leq n), indicating the length of the sequence a and the number of terms of prefix sums, respectively.The second line of each test case contains k integers s_{n-k+1}, \dots, s_{n-1}, s_{n} (-10^9 \leq s_i \leq 10^9 for every n-k+1 \leq i \leq n).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output "YES" (without quotes) if it is possible and "NO" (without quotes) otherwise.You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).ExampleInput 45 51 2 3 4 57 4-6 -5 -3 03 32 3 43 23 4Output Yes Yes No No NoteIn the first test case, we have the only sequence a = [1, 1, 1, 1, 1].In the second test case, we can choose, for example, a = [-3, -2, -1, 0, 1, 2, 3].In the third test case, the prefix sums define the only sequence a = [2, 1, 1], but it is not sorted. In the fourth test case, it can be shown that there is no sequence with the given prefix sums.
45 51 2 3 4 57 4-6 -5 -3 03 32 3 43 23 4
Yes Yes No No
2 seconds
512 megabytes
['constructive algorithms', 'greedy', 'math', 'sortings', '*1200']
A. Glory Addictstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe hero is addicted to glory, and is fighting against a monster. The hero has n skills. The i-th skill is of type a_i (either fire or frost) and has initial damage b_i. The hero can perform all of the n skills in any order (with each skill performed exactly once). When performing each skill, the hero can play a magic as follows: If the current skill immediately follows another skill of a different type, then its damage is doubled. In other words, If a skill of type fire and with initial damage c is performed immediately after a skill of type fire, then it will deal c damage; If a skill of type fire and with initial damage c is performed immediately after a skill of type frost, then it will deal 2c damage; If a skill of type frost and with initial damage c is performed immediately after a skill of type fire, then it will deal 2c damage; If a skill of type frost and with initial damage c is performed immediately after a skill of type frost , then it will deal c damage. Your task is to find the maximum damage the hero can deal. InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 10^5) — the number of test cases. The following lines contain the description of each test case.The first line of each test case contains an integer n (1 \leq n \leq 10^5), indicating the number of skills. The second line of each test case contains n integers a_1, a_2, \dots, a_n (0 \leq a_i \leq 1), where a_i indicates the type of the i-th skill. Specifically, the i-th skill is of type fire if a_i = 0, and of type frost if a_i = 1. The third line of each test case contains n integers b_1, b_2, \dots, b_n (1 \leq b_i \leq 10^9), where b_i indicates the initial damage of the i-th skill. It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output the maximum damage the hero can deal.ExampleInput 440 1 1 11 10 100 100060 0 0 1 1 13 4 5 6 7 831 1 11000000000 1000000000 1000000000111Output 2112 63 3000000000 1 NoteIn the first test case, we can order the skills by [3, 1, 4, 2], and the total damage is 100 + 2 \times 1 + 2 \times 1000 + 10 = 2112.In the second test case, we can order the skills by [1, 4, 2, 5, 3, 6], and the total damage is 3 + 2 \times 6 + 2 \times 4 + 2 \times 7 + 2 \times 5 + 2 \times 8 = 63.In the third test case, we can order the skills by [1, 2, 3], and the total damage is 1000000000 + 1000000000 + 1000000000 = 3000000000.In the fourth test case, there is only one skill with initial damage 1, so the total damage is 1.
440 1 1 11 10 100 100060 0 0 1 1 13 4 5 6 7 831 1 11000000000 1000000000 1000000000111
2112 63 3000000000 1
2 seconds
512 megabytes
['greedy', 'implementation', 'sortings', '*800']
G. Ela Takes Dancing Classtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDTL engineers love partying in the weekend. Ela does, too! Unfortunately, she didn't know how to dance yet. Therefore, she decided to take a dancing class.There are n students in the dancing class, including Ela. In the final project, n students will participate in a choreography described below.n students are positioned on the positive side of the Ox-axis. The i-th dancer is located at a_i > 0. Some dancers will change positions during the dance (we'll call them movable dancers), and others will stay in the same place during a choreography (we'll call them immovable dancers). We distinguish the dancers using a binary string s of length n: if s_i equals '1', then the i-th dancer is movable, otherwise the i-th dancer is immovable.Let's call the "positive energy value" of the choreography d > 0. The dancers will perform "movements" based on this value.Each minute after the dance begins, the movable dancer with the smallest x-coordinate will start moving to the right and initiate a "movement". At the beginning of the movement, the dancer's energy level will be initiated equally to the positive energy value of the choreography, which is d. Each time they move from some y to y+1, the energy level will be decreased by 1. At some point, the dancer might meet other fellow dancers in the same coordinates. If it happens, then the energy level of the dancer will be increased by 1. A dancer will stop moving to the right when his energy level reaches 0, and he doesn't share a position with another dancer.The dancers are very well-trained, and each "movement" will end before the next minute begins.To show her understanding of this choreography, Ela has to answer q queries, each consisting of two integers k and m. The answer to this query is the coordinate of the m-th dancer of both types from the left at k-th minute after the choreography begins. In other words, denote x_{k, 1}, x_{k, 2}, \dots, x_{k, n} as the sorted coordinates of the dancers at k-th minute from the beginning, you need to print x_{k, m}.InputThe first line contains three integers n, d and q (1 \le n \le 10^5; 1 \le d \le 10^9; 1 \le q \le 10^5) — the number of dancers, the positive energy value of the choreography, and the number of queries.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_1 < a_2 < \dots < a_n \le 10^9) — the coordinates of each dancer.The third line contains a binary string s of length n — the movability of each dancer. Each character is either '0' or '1'. It is guaranteed that s contains at least one character '1'.Then q lines follow, the i-th of them contains two integers k_i and m_i (1 \le k_i \le 10^9, 1 \le m_i \le n) — the content of each query.OutputOutput q lines, each contains a single integer — the answer for the corresponding query.ExamplesInput 4 3 8 1 3 6 7 1011 1 1 1 2 1 3 1 4 2 1 2 2 2 3 2 4 Output 3 5 6 7 3 6 7 10 Input 1 1 5 2 1 1 1 2 1 3 1 4 1 5 1 Output 3 4 5 6 7 NoteLet's consider the first example test case.In the first minute, 1 is the lowest coordinate between movable dancers. The energy level is initiated with 3. Then the following happens: The dancer moves from 1 to 2. The energy level decreased to 2. The dancer moves from 2 to 3. The energy level decreased to 1, then increased to 2 when she met another dancer at 3. The dancer moves from 3 to 4. The energy level decreased to 1. The dancer moves from 4 to 5. The energy level decreased to 0. At the end of the first minute, the sorted coordinates of the dancers become [3, 5, 6, 7], and their respective movability is '0111'.In the second minute, 5 is the lowest coordinate between movable dancers. The energy level is initiated with 3. Then the following happens: The dancer moves from 5 to 6. The energy level decreased to 2, then increased to 3 when she met another dancer at 6. The dancer moves from 6 to 7. The energy level decreased to 2, then increased to 3 when she met another dancer at 7. The dancer moves from 7 to 8. The energy level decreased to 2. The dancer moves from 8 to 9. The energy level decreased to 1. The dancer moves from 9 to 10. The energy level decreased to 0. At the end of the second minute, the sorted coordinates of the dancers become [3, 6, 7, 10], and their respective movability is '0111'.
4 3 8 1 3 6 7 1011 1 1 1 2 1 3 1 4 2 1 2 2 2 3 2 4
3 5 6 7 3 6 7 10
4 seconds
256 megabytes
['binary search', 'data structures', '*3500']
F. Ela and Prime GCDtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long, tough, but fruitful day at DTL, Ela goes home happily. She entertains herself by solving Competitive Programming problems. She prefers short statements, because she already read too many long papers and documentation at work. The problem of the day reads:You are given an integer c. Suppose that c has n divisors. You have to find a sequence with n - 1 integers [a_1, a_2, ... a_{n - 1}], which satisfies the following conditions: Each element is strictly greater than 1. Each element is a divisor of c. All elements are distinct. For all 1 \le i < n - 1, \gcd(a_i, a_{i + 1}) is a prime number. In this problem, because c can be too big, the result of prime factorization of c is given instead. Note that \gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y and a prime number is a positive integer which has exactly 2 divisors.InputThe first line contains one integer t (1 \le t \le 10^4) - the number of test cases.The first line of each test case contains one integer m (1 \le m \le 16) - the number of prime factor of c.The second line of each test case contains m integers b_1, b_2, \ldots, b_m (1 \le b_i < 2^{20}) — exponents of corresponding prime factors of c, so that c = p_1^{b_1} \cdot p_2^{b_2} \cdot \ldots \cdot p_m^{b_m} and n = (b_1 + 1)(b_2 + 1) \ldots (b_m + 1) hold. p_i is the i-th smallest prime number.It is guaranteed that the sum of n \cdot m over all test cases does not exceed 2^{20}.OutputPrint the answer for each test case, one per line. If there is no sequence for the given c, print -1.Otherwise, print n - 1 lines. In i-th line, print m space-separated integers. The j-th integer of i-th line is equal to the exponent of j-th prime number from a_i.If there are multiple answers, print any of them.ExampleInput 521 11131 1 11422 1Output 0 1 1 1 1 0 1 0 1 1 0 0 1 1 0 1 1 1 0 0 1 0 1 1 1 1 0 0 -1 2 0 1 1 0 1 2 1 1 0 NoteIn each test case, the values of c are 6, 2, 30, 16, and 12 in that order.In the first test case, 1, 2, 3, 6 are divisors of 6. Here, sequences [2, 6, 3] and [3, 6, 2] can be answer. Permutation [3, 2, 6] is invalid because \gcd(a_1, a_2) = 1 is not a prime number.In the forth test case, 1, 2, 4, 8, 16 are divisors of 16. Among the permutation of sequence [2, 4, 8, 16], no valid answer exist.
521 11131 1 11422 1
0 1 1 1 1 0 1 0 1 1 0 0 1 1 0 1 1 1 0 0 1 0 1 1 1 1 0 0 -1 2 0 1 1 0 1 2 1 1 0
2 seconds
256 megabytes
['constructive algorithms', 'math', 'number theory', '*3300']
E. Ela Goes Hikingtime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEla likes to go hiking a lot. She loves nature and exploring the various creatures it offers. One day, she saw a strange type of ant, with a cannibalistic feature. More specifically, an ant would eat any ants that it sees which is smaller than it.Curious about this feature from a new creature, Ela ain't furious. She conducts a long, non-dubious, sentimental experiment.She puts n cannibalistic ants in a line on a long wooden stick. Initially, the ants have the same weight of 1. The distance between any two consecutive ants is the same. The distance between the first ant in the line to the left end and the last ant in the line to the right end is also the same as the distance between the ants. Each ant starts moving towards the left-end or the right-end randomly and equiprobably, at the same constant pace throughout the experiment. Two ants will crash if they are standing next to each other in the line and moving in opposite directions, and ants will change direction immediately when they reach the end of the stick. Ela can't determine the moving direction of each ant, but she understands very well their behavior when crashes happen. If a crash happens between two ants of different weights, the heavier one will eat the lighter one, and gain the weight of the lighter one. After that, the heavier and will continue walking in the same direction. In other words, if the heavier one has weight x and walking to the right, the lighter one has weight y and walking to the left (x > y), then after the crash, the lighter one will diminish, and the heavier one will have weight x + y and continue walking to the right. If a crash happens between two ants with the same weight, the one walking to the left end of the stick will eat the one walking to the right, and then continue walking in the same direction. In other words, if one ant of weight x walking to the left, crashes with another ant of weight x walking to the right, the one walking to the right will disappear, and the one walking to the left will have to weight 2x and continue walking to the left. Please, check the example in the "Note" section, which will demonstrate the ants' behavior as above.We can prove that after a definite amount of time, there will be only one last ant standing. Initially, each ant can randomly and equiprobably move to the left or the right, which generates 2^n different cases of initial movements for the whole pack. For each position in the line, calculate the probability that the ant begins in that position and survives. Output it modulo 10^9 + 7.Formally, let M = 10^9 + 7. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^3). The description of the test cases follows.The only line of each test contains an integer n (1 \le n \le 10^6) — the number of ants in the experiment.It is guaranteed that the sum of n in all tests will not exceed 10^6.OutputFor each test, print n lines. i-th line contains a single number that denotes the survival probability of the i-th ant in the line modulo 10^9 + 7.ExampleInput 3452Output 0 250000002 250000002 500000004 0 250000002 250000002 250000002 250000002 0 1 NoteHere is the example of 6 ants moving on the branch. An ant's movement will be denoted by either a character L or R. Initially, the pack of ants on the branch will move as RLRRLR. Here's how the behavior of the pack demonstrated: Initially, the ants are positioned as above. After a while, the ant with index 2 (walking to the left) will crash with the ant with index 1 (walking to the right). The two ants have the same weight, therefore, ant 2 will eat ant 1 and gain its weight to 2. The same thing happens with ant 5 and ant 4.The ant 6 will walk to the end of the stick, therefore changing its direction. After that, the ant with index 5 will crash with the ant with index 3. Since ant 5 is more heavy (weight=2) than ant 3 (weight=1), ant 5 will eat ant 3 and gain its weight to 3.Ant 2 will walk to the end of the stick, therefore changing its direction. After that, the ant with index 5 will crash with the ant with index 2. Since ant 5 is more heavy (weight=3) than ant 2 (weight=2), ant 5 will eat ant 2 and gain its weight to 5. Lastly, after ant 5 walk to the end of the branch and changes its direction, ant 5 will eat ant 6 and be the last ant standing.
3452
0 250000002 250000002 500000004 0 250000002 250000002 250000002 250000002 0 1
2.5 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'probabilities', '*2500']
D. Ela and the Wiring Wizardtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Ela needs to send a large package from machine 1 to machine n through a network of machines. Currently, with the network condition, she complains that the network is too slow and the package can't arrive in time. Luckily, a Wiring Wizard offered her a helping hand.The network can be represented as an undirected connected graph with n nodes, each node representing a machine. m wires are used to connect them. Wire i is used to connect machines u_i and v_i, and has a weight w_i. The aforementioned large package, if going through wire i, will move from machine u_i to machine v_i (or vice versa) in exactly w_i microseconds. The Wiring Wizard can use his spell an arbitrary number of times. For each spell, he will choose the wire of index i, connecting machine u_i and v_i, and rewire it following these steps: Choose one machine that is connected by this wire. Without loss of generality, let's choose v_i. Choose a machine that is currently connecting to v_i (including u_i), call it t_i. Disconnect the wire indexed i from v_i, then using it to connect u_i and t_i. The rewiring of wire i will takes w_i microseconds, and the weight of the wire will not change after this operation. After a rewiring, a machine might have some wire connect it with itself. Also, the Wiring Wizard has warned Ela that rewiring might cause temporary disconnections between some machines, but Ela just ignores it anyway. Her mission is to send the large package from machine 1 to machine n as fast as possible. Note that the Wizard can use his spell on a wire zero, one, or many times. To make sure the network works seamlessly while transferring the large package, once the package starts transferring from machine 1, the Wiring Wizard cannot use his spell to move wires around anymore.Ela wonders, with the help of the Wiring Wizard, what is the least amount of time needed to transfer the large package from machine 1 to n.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). The description of the test cases follows.The first line contains n and m (2 \le n \le 500, n - 1 \le m \le 250 000), the number of nodes and number of wires, respectively.For the next m lines, i-th line will contains u_i, v_i and w_i (1 \le u_i, v_i \le n, 1 \le w_i \le 10^9) - the indices 2 machines that are connected by the i-th edge and the weight of it.It is guaranteed that the sum of n over all test cases does not exceed 500 and the sum of m over all test cases does not exceed 250 000. The graph in each test case is guaranteed to be connected, no self-loops, but it can contain multiple edges.OutputFor each test case, output one integer denotes the least amount of time needed to transfer the large package from machine 1 to n.ExampleInput 38 91 2 36 4 53 5 66 1 37 4 43 8 42 3 37 8 54 5 24 51 2 12 4 13 4 13 1 11 3 28 84 6 927 1 656 5 436 7 964 3 744 8 547 4 992 5 22Output 9 2 154 NoteHere is the graph in the first test case in the sample input: Ela can ask the Wiring Wizard to use his spell on wire with the index of 7, which is connecting machines 2 and 3. Then, since the machine 8 is connected to machine 3, the Wiring Wizard can disconnect wire 7 from machine 3 and connect it to machine 8 in 3 microseconds (weight of wire 3).After that, the package can be sent from machine 1 to machine 8 in 6 microseconds. Therefore, the answer is 3 + 6 = 9 microseconds.Here is the graph in the third test case in the sample input:
38 91 2 36 4 53 5 66 1 37 4 43 8 42 3 37 8 54 5 24 51 2 12 4 13 4 13 1 11 3 28 84 6 927 1 656 5 436 7 964 3 744 8 547 4 992 5 22
9 2 154
4 seconds
256 megabytes
['brute force', 'dp', 'graphs', 'greedy', 'implementation', 'shortest paths', '*2200']