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
A. Berland Pokertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k).At the beginning of the game, each player takes \frac{n}{k} cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to x - y, where x is the number of jokers in the winner's hand, and y is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get 0 points.Here are some examples: n = 8, m = 3, k = 2. If one player gets 3 jokers and 1 plain card, and another player gets 0 jokers and 4 plain cards, then the first player is the winner and gets 3 - 0 = 3 points; n = 4, m = 2, k = 4. Two players get plain cards, and the other two players get jokers, so both of them are winners and get 0 points; n = 9, m = 6, k = 3. If the first player gets 3 jokers, the second player gets 1 joker and 2 plain cards, and the third player gets 2 jokers and 1 plain card, then the first player is the winner, and he gets 3 - 2 = 1 point; n = 42, m = 0, k = 7. Since there are no jokers, everyone gets 0 jokers, everyone is a winner, and everyone gets 0 points. Given n, m and k, calculate the maximum number of points a player can get for winning the game.InputThe first line of the input contains one integer t (1 \le t \le 500) — the number of test cases.Then the test cases follow. Each test case contains three integers n, m and k (2 \le n \le 50, 0 \le m \le n, 2 \le k \le n, k is a divisors of n).OutputFor each test case, print one integer — the maximum number of points a player can get for winning the game.ExampleInput 4 8 3 2 4 2 4 9 6 3 42 0 7 Output 3 0 1 0 NoteTest cases of the example are described in the statement.
4 8 3 2 4 2 4 9 6 3 42 0 7
3 0 1 0
2 seconds
256 megabytes
['brute force', 'greedy', 'math', '*1000']
F. Tasty Cookietime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOh, no!The coronavirus has caught you, and now you're sitting in a dark cellar, with tied legs (but not hands). You have a delicious cookie, a laptop in front of you, and your ideal development environment is open. The coronavirus convinces you to solve the following problem.You are given two arrays A and B of size n. You can do operations of two types with array A: Reverse array A. That is the array [A_1,\ A_2,\ \ldots,\ A_n] transformes into [A_n,\ A_{n-1},\ \ldots,\ A_1]. Replace A with an array of its prefix sums. That is, the array [A_1,\ A_2,\ \ldots,\ A_n] goes to [A_1,\ (A_1+A_2),\ \ldots,\ (A_1+A_2+\ldots+A_n)]. You need to understand if you can get an array B from the array A. If it is possible, you will have to restore the order of these operations by minimizing the number of operations of the second type. Fortunately, the coronavirus is good today, so he has allowed you not to restore actions if the minimum number of second type operations is more than 2\cdot 10^5. But coronavirus resents you, so if you restore the answer, the total number of operations should not exceed 5\cdot 10^5.Solve this problem and get the cookie, or the coronavirus will extend the quarantine for five years and make the whole economy collapse! InputThe first line contains a single integer n (1\le n \le 2\cdot 10^5).The second line contains n integers A_1, A_2, \ldots, A_n (1 \le A_i \le 10 ^ {12}).The third line contains n integers B_1, B_2, \ldots, B_n (1 \le B_i \le 10 ^ {12}).OutputIf you cannot get B from the A array, print "IMPOSSIBLE" (without quotes) on a single line.If the minimum number of operations of the second type exceeds 2\cdot 10^5, print "BIG" (without quotes). In the second line print the number of operations of the second type, that needs to be applied to get array B from A.Otherwise, in the first line print "SMALL" (without quotes). In the second line print the total number of operations of the first and second types m \le 5\cdot 10^5 (it is guaranteed that in this case there is such a sequence of actions). In the third line print a line of length m, consisting of characters 'R"and 'P' (without quotes).The i-th character should be 'R', if the i-th action is of the first type, and should be 'P', otherwise.If there are several such sequences, you can print any of them.You can print each character in the uppercase or in the lowercase.ExamplesInput 2 5 7 5 7 Output SMALL 0 Input 2 1 1 300000 1 Output BIG 299999 Input 2 10 1 13 14 Output SMALL 6 RPPPRP Input 3 1 2 1 2 1 2 Output IMPOSSIBLE NoteIn the first example, the arrays A and B already equal, so the number of required operations =0.In the second example, we need to replace A with the prefix sums 299999 times and then reverse the array. Since 299999>2\cdot 10^5, there is no need to restore the answer.In the fourth example, you cannot get B from the A.
2 5 7 5 7
SMALL 0
3 seconds
256 megabytes
['binary search', 'constructive algorithms', 'greedy', 'implementation', '*2700']
E. Are You Fired?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLevian works as an accountant in a large company. Levian knows how much the company has earned in each of the n consecutive months — in the i-th month the company had income equal to a_i (positive income means profit, negative income means loss, zero income means no change). Because of the general self-isolation, the first \lceil \tfrac{n}{2} \rceil months income might have been completely unstable, but then everything stabilized and for the last \lfloor \tfrac{n}{2} \rfloor months the income was the same.Levian decided to tell the directors n-k+1 numbers — the total income of the company for each k consecutive months. In other words, for each i between 1 and n-k+1 he will say the value a_i + a_{i+1} + \ldots + a_{i + k - 1}. For example, if a=[-1, 0, 1, 2, 2] and k=3 he will say the numbers 0, 3, 5.Unfortunately, if at least one total income reported by Levian is not a profit (income \le 0), the directors will get angry and fire the failed accountant.Save Levian's career: find any such k, that for each k months in a row the company had made a profit, or report that it is impossible.InputThe first line contains a single integer n (2 \le n \le 5\cdot 10^5) — the number of months for which Levian must account.The second line contains \lceil{\frac{n}{2}}\rceil integers a_1, a_2, \ldots, a_{\lceil{\frac{n}{2}}\rceil}, where a_i (-10^9 \le a_i \le 10^9) — the income of the company in the i-th month.Third line contains a single integer x (-10^9 \le x \le 10^9) — income in every month from \lceil{\frac{n}{2}}\rceil + 1 to n.OutputIn a single line, print the appropriate integer k or -1, if it does not exist.If there are multiple possible answers, you can print any.ExamplesInput 3 2 -1 2 Output 2Input 5 2 2 -8 2 Output -1Input 6 -2 -2 6 -1 Output 4NoteIn the first example, k=2 and k=3 satisfy: in the first case, Levian will report the numbers 1, 1, and in the second case — one number 3.In the second example, there is no such k.In the third example, the only answer is k=4: he will report the numbers 1,2,3.
3 2 -1 2
2
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'implementation', '*2400']
D. The Best Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha. You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly x days and that's the exact number of days you will spend visiting your friend. You will spend exactly x consecutive (successive) days visiting Coronavirus-chan.They use a very unusual calendar in Naha: there are n months in a year, i-th month lasts exactly d_i days. Days in the i-th month are numbered from 1 to d_i. There are no leap years in Naha.The mood of Coronavirus-chan (and, accordingly, her desire to hug you) depends on the number of the day in a month. In particular, you get j hugs if you visit Coronavirus-chan on the j-th day of the month.You know about this feature of your friend and want to plan your trip to get as many hugs as possible (and then maybe you can win the heart of Coronavirus-chan). Please note that your trip should not necessarily begin and end in the same year.InputThe first line of input contains two integers n and x (1 \le n \le 2 \cdot 10^5) — the number of months in the year and the number of days you can spend with your friend.The second line contains n integers d_1, d_2, \ldots, d_n, d_i is the number of days in the i-th month (1 \le d_i \le 10^6).It is guaranteed that 1 \le x \le d_1 + d_2 + \ldots + d_n.OutputPrint one integer — the maximum number of hugs that you can get from Coronavirus-chan during the best vacation in your life.ExamplesInput 3 2 1 3 1 Output 5Input 3 6 3 3 3 Output 12Input 5 6 4 2 3 1 3 Output 15NoteIn the first test case, the numbers of the days in a year are (indices of days in a corresponding month) \{1,1,2,3,1\}. Coronavirus-chan will hug you the most if you come on the third day of the year: 2+3=5 hugs.In the second test case, the numbers of the days are \{1,2,3,1,2,3,1,2,3\}. You will get the most hugs if you arrive on the third day of the year: 3+1+2+3+1+2=12 hugs.In the third test case, the numbers of the days are \{1,2,3,4,1,2, 1,2,3, 1, 1,2,3\}. You will get the most hugs if you come on the twelfth day of the year: your friend will hug you 2+3+1+2+3+4=15 times.
3 2 1 3 1
5
2 seconds
256 megabytes
['binary search', 'brute force', 'greedy', 'implementation', 'two pointers', '*1900']
C. Celex Updatetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: The cell with coordinates (x, y) is at the intersection of x-th row and y-th column. Upper left cell (1,1) contains an integer 1.The developers of the SUM function don't sleep either. Because of the boredom, they teamed up with the developers of the RAND function, so they added the ability to calculate the sum on an arbitrary path from one cell to another, moving down or right. Formally, from the cell (x,y) in one step you can move to the cell (x+1, y) or (x, y+1). After another Dinwows update, Levian started to study "Celex-2021" (because he wants to be an accountant!). After filling in the table with the GAZ-GIZ function, he asked you to calculate the quantity of possible different amounts on the path from a given cell (x_1, y_1) to another given cell (x_2, y_2), if you can only move one cell down or right.Formally, consider all the paths from the cell (x_1, y_1) to cell (x_2, y_2) such that each next cell in the path is located either to the down or to the right of the previous one. Calculate the number of different sums of elements for all such paths.InputThe first line contains one integer t (1 \le t \le 57179) — the number of test cases.Each of the following t lines contains four natural numbers x_1, y_1, x_2, y_2 (1 \le x_1 \le x_2 \le 10^9, 1 \le y_1 \le y_2 \le 10^9) — coordinates of the start and the end cells. OutputFor each test case, in a separate line, print the number of possible different sums on the way from the start cell to the end cell.ExampleInput 4 1 1 2 2 1 2 2 4 179 1 179 100000 5 7 5 7 Output 2 3 1 1 NoteIn the first test case there are two possible sums: 1+2+5=8 and 1+3+5=9.
4 1 1 2 2 1 2 2 4 179 1 179 100000 5 7 5 7
2 3 1 1
2 seconds
256 megabytes
['math', '*1600']
B. Maria Breaks the Self-isolationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMaria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least a_i other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny i agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to a_i.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is 1). All the remaining n grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least a_i other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the i-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than a_i other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if n=6 and a=[1,5,4,5,1,9], then: at the first step Maria can call grannies with numbers 1 and 5, each of them will see two grannies at the moment of going out into the yard (note that a_1=1 \le 2 and a_5=1 \le 2); at the second step, Maria can call grannies with numbers 2, 3 and 4, each of them will see five grannies at the moment of going out into the yard (note that a_2=5 \le 5, a_3=4 \le 5 and a_4=5 \le 5); the 6-th granny cannot be called into the yard  — therefore, the answer is 6 (Maria herself and another 5 grannies). InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases in the input. Then test cases follow.The first line of a test case contains a single integer n (1 \le n \le 10^5) — the number of grannies (Maria is not included in this number).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 2\cdot10^5).It is guaranteed that the sum of the values n over all test cases of the input does not exceed 10^5.OutputFor each test case, print a single integer k (1 \le k \le n + 1) — the maximum possible number of grannies in the courtyard.ExampleInput 4 5 1 1 2 2 1 6 2 3 4 5 6 7 6 1 5 4 5 1 9 5 1 2 3 5 6 Output 6 1 6 4 NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers 1, 2 and 3. If on the second step Maria calls 4 or 5 (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the 4-th granny or the 5-th granny separately (one of them). If she calls both: 4 and 5, then when they appear, they will see 4+1=5 grannies. Despite the fact that it is enough for the 4-th granny, the 5-th granny is not satisfied. So, Maria cannot call both the 4-th granny and the 5-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
4 5 1 1 2 2 1 6 2 3 4 5 6 7 6 1 5 4 5 1 9 5 1 2 3 5 6
6 1 6 4
2 seconds
256 megabytes
['greedy', 'sortings', '*1000']
A. Park Lightingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDue to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.The park is a rectangular table with n rows and m columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length 1. For example, park with n=m=2 has 12 streets.You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park). The park sizes are: n=4, m=5. The lighted squares are marked yellow. Please note that all streets have length 1. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit. Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.Each test case is a line containing two integers n, m (1 \le n, m \le 10^4) — park sizes.OutputPrint t answers to the test cases. Each answer must be a single integer — the minimum number of lanterns that are required to light all the squares.ExampleInput 5 1 1 1 3 2 2 3 3 5 3 Output 1 2 2 5 8 NotePossible optimal arrangement of the lanterns for the 2-nd test case of input data example: Possible optimal arrangement of the lanterns for the 3-rd test case of input data example:
5 1 1 1 3 2 2 3 3 5 3
1 2 2 5 8
2 seconds
256 megabytes
['greedy', 'math', '*800']
F. Guess Divisors Counttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.We have hidden an integer 1 \le X \le 10^{9}. You don't have to guess this number. You have to find the number of divisors of this number, and you don't even have to find the exact number: your answer will be considered correct if its absolute error is not greater than 7 or its relative error is not greater than 0.5. More formally, let your answer be ans and the number of divisors of X be d, then your answer will be considered correct if at least one of the two following conditions is true: | ans - d | \le 7; \frac{1}{2} \le \frac{ans}{d} \le 2.You can make at most 22 queries. One query consists of one integer 1 \le Q \le 10^{18}. In response, you will get gcd(X, Q) — the greatest common divisor of X and Q.The number X is fixed before all queries. In other words, interactor is not adaptive.Let's call the process of guessing the number of divisors of number X a game. In one test you will have to play T independent games, that is, guess the number of divisors T times for T independent values of X.InputThe first line of input contains one integer T (1 \le T \le 100) — the number of games.InteractionTo make a query print a line "? Q" (1 \le Q \le 10^{18}). After that read one integer gcd(X, Q). You can make no more than 22 such queries during one game.If you are confident that you have figured out the number of divisors of X with enough precision, you can print your answer in "! ans" format. ans have to be an integer. If this was the last game, you have to terminate the program, otherwise you have to start the next game immediately. Note that the interactor doesn't print anything in response to you printing answer.After printing a query do not forget to output end of line and flush the output. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.HacksTo hack, use the following format:The first line contains one integer T (1 \le T \le 100) — the number of games.Each of the next T lines contains one integer X (1 \le X \le 10^{9}) — the hidden number.So the example has the form 29982443534194304ExampleInput 2 1 1 1 1024 1048576 4194304 Output ? 982306799268821872 ? 230856864650023977 ? 134690134760714371 ! 5 ? 1024 ? 1048576 ? 1073741824 ! 42 NoteWhy the limitation for number of queries is 22 exactly? Maybe the problem author is a Taylor Swift fan.Let's look at the example.In the first game X = 998\,244\,353 is hidden. Would be hard to guess this, right? This number is prime, so the number of its divisors is 2. The solution has made several random queries, and all the responses turned out to be 1 (strange things, not even one of three random numbers is divisible by 998\,244\,353). It's fare to assume that the hidden number doesn't have many divisors, so the solution has answered 5. Why not. This answer will be considered correct since | 5 - 2 | = 3 \le 7.In the second game X = 4\,194\,304 = 2^{22} is hidden, it has 23 divisors. The solution has made queries 1024 = 2^{10}, 1\,048\,576 =2^{20}, 1\,073\,741\,824 = 2^{30} and got responses 1024 = 2^{10}, 1\,048\,576 =2^{20}, 4\,194\,304 = 2^{22}, respectively. Then the solution got completely confused and answered the answer to The Ultimate Question of Life, the Universe, and Everything. This answer will be considered correct since \frac{1}{2} \le \frac{42}{23} \le 2.
2 1 1 1 1024 1048576 4194304
? 982306799268821872 ? 230856864650023977 ? 134690134760714371 ! 5 ? 1024 ? 1048576 ? 1073741824 ! 42
2 seconds
256 megabytes
['constructive algorithms', 'interactive', 'number theory', '*2600']
E. Restorer Distancetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is A; remove a brick from the top of one non-empty pillar, the cost of this operation is R; move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?InputThe first line of input contains four integers N, A, R, M (1 \le N \le 10^{5}, 0 \le A, R, M \le 10^{4}) — the number of pillars and the costs of operations.The second line contains N integers h_{i} (0 \le h_{i} \le 10^{9}) — initial heights of pillars.OutputPrint one integer — the minimal cost of restoration.ExamplesInput 3 1 100 100 1 3 8 Output 12 Input 3 100 1 100 1 3 8 Output 9 Input 3 100 100 1 1 3 8 Output 4 Input 5 1 2 4 5 5 3 6 5 Output 4 Input 5 1 2 2 5 5 3 6 5 Output 3
3 1 100 100 1 3 8
12
1 second
256 megabytes
['binary search', 'greedy', 'math', 'sortings', 'ternary search', '*2100']
D. Game With Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and Vasya are competing with each other in a new interesting game as they always do.At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 \leq K \leq S.In order to win, Vasya has to find a non-empty subarray in Petya's array such that the sum of all selected elements equals to either K or S - K. Otherwise Vasya loses.You are given integers N and S. You should determine if Petya can win, considering Vasya plays optimally. If Petya can win, help him to do that.InputThe first line contains two integers N and S (1 \leq N \leq S \leq 10^{6}) — the required length of the array and the required sum of its elements.OutputIf Petya can win, print "YES" (without quotes) in the first line. Then print Petya's array in the second line. The array should contain N positive integers with sum equal to S. In the third line print K. If there are many correct answers, you can print any of them.If Petya can't win, print "NO" (without quotes).You can print each letter in any register (lowercase or uppercase).ExamplesInput 1 4 Output YES 4 2Input 3 4 Output NOInput 3 8 Output YES 2 1 5 4
1 4
YES 4 2
1 second
256 megabytes
['constructive algorithms', 'math', '*1400']
C. Count Trianglestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLike any unknown mathematician, Yuri has favourite numbers: A, B, C, and D, where A \leq B \leq C \leq D. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides x, y, and z exist, such that A \leq x \leq B \leq y \leq C \leq z \leq D holds?Yuri is preparing problems for a new contest now, so he is very busy. That's why he asked you to calculate the number of triangles with described property.The triangle is called non-degenerate if and only if its vertices are not collinear.InputThe first line contains four integers: A, B, C and D (1 \leq A \leq B \leq C \leq D \leq 5 \cdot 10^5) — Yuri's favourite numbers.OutputPrint the number of non-degenerate triangles with integer sides x, y, and z such that the inequality A \leq x \leq B \leq y \leq C \leq z \leq D holds.ExamplesInput 1 2 3 4 Output 4 Input 1 2 2 5 Output 3 Input 500000 500000 500000 500000 Output 1 NoteIn the first example Yuri can make up triangles with sides (1, 3, 3), (2, 2, 3), (2, 3, 3) and (2, 3, 4).In the second example Yuri can make up triangles with sides (1, 2, 2), (2, 2, 2) and (2, 2, 3).In the third example Yuri can make up only one equilateral triangle with sides equal to 5 \cdot 10^5.
1 2 3 4
4
1 second
256 megabytes
['binary search', 'implementation', 'math', 'two pointers', '*1800']
B. Young Explorerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYoung wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...Most of the young explorers are inexperienced, and sending them alone would be a mistake. Even Russell himself became senior explorer not long ago. Each of young explorers has a positive integer parameter e_i — his inexperience. Russell decided that an explorer with inexperience e can only join the group of e or more people.Now Russell needs to figure out how many groups he can organize. It's not necessary to include every explorer in one of the groups: some can stay in the camp. Russell is worried about this expedition, so he asked you to help him.InputThe first line contains the number of independent test cases T(1 \leq T \leq 2 \cdot 10^5). Next 2T lines contain description of test cases.The first line of description of each test case contains the number of young explorers N (1 \leq N \leq 2 \cdot 10^5).The second line contains N integers e_1, e_2, \ldots, e_N (1 \leq e_i \leq N), where e_i is the inexperience of the i-th explorer.It's guaranteed that sum of all N doesn't exceed 3 \cdot 10^5.OutputPrint T numbers, each number on a separate line.In i-th line print the maximum number of groups Russell can form in i-th test case.ExampleInput 2 3 1 1 1 5 2 3 1 2 2 Output 3 2 NoteIn the first example we can organize three groups. There will be only one explorer in each group. It's correct because inexperience of each explorer equals to 1, so it's not less than the size of his group.In the second example we can organize two groups. Explorers with inexperience 1, 2 and 3 will form the first group, and the other two explorers with inexperience equal to 2 will form the second group.This solution is not unique. For example, we can form the first group using the three explorers with inexperience equal to 2, and the second group using only one explorer with inexperience equal to 1. In this case the young explorer with inexperience equal to 3 will not be included in any group.
2 3 1 1 1 5 2 3 1 2 2
3 2
2 seconds
256 megabytes
['dp', 'greedy', 'sortings', '*1200']
A. Sequence with Digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define the following recurrence: a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes.Your task is calculate a_{K} for given a_{1} and K.InputThe first line contains one integer t (1 \le t \le 1000) — the number of independent test cases.Each test case consists of a single line containing two integers a_{1} and K (1 \le a_{1} \le 10^{18}, 1 \le K \le 10^{16}) separated by a space.OutputFor each test case print one integer a_{K} on a separate line.ExampleInput 8 1 4 487 1 487 2 487 3 487 4 487 5 487 6 487 7 Output 42 487 519 528 544 564 588 628 Notea_{1} = 487 a_{2} = a_{1} + minDigit(a_{1}) \cdot maxDigit(a_{1}) = 487 + \min (4, 8, 7) \cdot \max (4, 8, 7) = 487 + 4 \cdot 8 = 519 a_{3} = a_{2} + minDigit(a_{2}) \cdot maxDigit(a_{2}) = 519 + \min (5, 1, 9) \cdot \max (5, 1, 9) = 519 + 1 \cdot 9 = 528 a_{4} = a_{3} + minDigit(a_{3}) \cdot maxDigit(a_{3}) = 528 + \min (5, 2, 8) \cdot \max (5, 2, 8) = 528 + 2 \cdot 8 = 544 a_{5} = a_{4} + minDigit(a_{4}) \cdot maxDigit(a_{4}) = 544 + \min (5, 4, 4) \cdot \max (5, 4, 4) = 544 + 4 \cdot 5 = 564 a_{6} = a_{5} + minDigit(a_{5}) \cdot maxDigit(a_{5}) = 564 + \min (5, 6, 4) \cdot \max (5, 6, 4) = 564 + 4 \cdot 6 = 588 a_{7} = a_{6} + minDigit(a_{6}) \cdot maxDigit(a_{6}) = 588 + \min (5, 8, 8) \cdot \max (5, 8, 8) = 588 + 5 \cdot 8 = 628
8 1 4 487 1 487 2 487 3 487 4 487 5 487 6 487 7
42 487 519 528 544 564 588 628
1 second
256 megabytes
['brute force', 'implementation', 'math', '*1200']
G. Find a Gifttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. Don't forget to flush output after printing queries using cout.flush() or fflush(stdout) in C++ or similar functions in other programming languages.There are n gift boxes in a row, numbered from 1 to n from left to right. It's known that exactly k of them contain valuable gifts — other boxes contain just lucky stones. All boxes look the same and differ only in weight. All boxes with stones have the same weight and are strictly heavier than boxes with valuable items. But valuable gifts may be different, so the boxes with valuable items may have different weights.You can ask no more than 50 queries (printing an answer doesn't count). By each query you can compare total weights of two non-intersecting subsets of boxes a_1, a_2, \dots, a_{k_a} and b_1, b_2, \dots, b_{k_b}. In return you'll get one of four results: FIRST, if subset a_1, a_2, \dots, a_{k_a} is strictly heavier; SECOND, if subset b_1, b_2, \dots, b_{k_b} is strictly heavier; EQUAL, if subsets have equal total weights; WASTED, if the query is incorrect or the limit of queries is exceeded. Using such queries (or, maybe, intuition) find the box with a valuable gift with the minimum index.InputThe input consists of several cases. In the beginning, you receive the integer T (1 \le T \le 500) — the number of test cases.At the beginning of each test case, you receive two integers n and k (2 \le n \le 1000, 1 \le k \le \frac{n}{2}) — the number of boxes in a row and the number of boxes with valuable gifts.It's guaranteed that the order of boxes is fixed beforehand and that the sum of n in one test doesn't exceed 1000.OutputFor each test case print the minimum index among all boxes with a valuable gift in the following format: "! x" where x (1 \le x \le n) — the index of the box.InteractionPrint each query in three lines. In the first line print the sizes of subset in the following format: "? k_a k_b" where k_a and k_b (1 \le k_a, k_b \le n; k_a + k_b \le n) — the corresponding sizes.In the second line print k_a integers a_1, a_2, \dots, a_{k_a} (1 \le a_i \le n; a_i \neq a_j if i \neq j) — indexes of boxes in the first subset.In the third line print k_b integers b_1, b_2, \dots, b_{k_b} (1 \le b_i \le n; b_i \neq b_j if i \neq j) — indexes of boxes in the second subset.The subsets shouldn't intersect, i. e. a_i \neq b_j for all i and j.You'll receive one of four responses described above. In the case of WASTED stop your program to avoid getting random verdict instead of Wrong Answer.ExampleInput 2 2 1 - - - FIRST - 5 2 - - - FIRST - - - SECOND - - - EQUAL -Output - - ? 1 1 1 2 - ! 2 - ? 1 1 1 2 - ? 2 3 4 2 1 3 5 - ? 1 1 4 5 - ! 1NoteAdditional separators "–" in the sample are used only to increase the readability of the sample. Don't print any unnecessary symbols or line breaks in your solution when you send it to the system.Hacks are forbidden in this task.
2 2 1 - - - FIRST - 5 2 - - - FIRST - - - SECOND - - - EQUAL -
- - ? 1 1 1 2 - ! 2 - ? 1 1 1 2 - ? 2 3 4 2 1 3 5 - ? 1 1 4 5 - ! 1
2 seconds
256 megabytes
['binary search', 'interactive', 'probabilities', '*2600']
F. Summoning Minionstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!InputThe first line contains one integer T (1 \le T \le 75) — the number of test cases.Each test case begins with a line containing two integers n and k (1 \le k \le n \le 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively.Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 \le a_i \le 10^5, 0 \le b_i \le 10^5) — the parameters of the i-th minion.OutputFor each test case print the optimal sequence of actions as follows:Firstly, print m — the number of actions which Polycarp has to perform (0 \le m \le 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action.If there are multiple optimal sequences, print any of them.ExampleInput 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 NoteConsider the example test.In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1
4 2 1 -1 5 1 2 5 5 4 3 2 1
6 seconds
512 megabytes
['constructive algorithms', 'dp', 'flows', 'graph matchings', 'greedy', 'sortings', '*2500']
E. Graph Coloringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to n_1; The total number of vertices with label 2 should be equal to n_2; The total number of vertices with label 3 should be equal to n_3; |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x. If there are multiple valid labelings, print any of them.InputThe first line contains two integers n and m (1 \le n \le 5000; 0 \le m \le 10^5) — the number of vertices and edges in the graph.The second line contains three integers n_1, n_2 and n_3 (0 \le n_1, n_2, n_3 \le n) — the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 \le u_i, v_i \le n; u_i \neq v_i) — the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.OutputIf valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.If there is no valid labeling, print "NO" (without quotes).ExamplesInput 6 3 2 2 2 3 1 5 4 2 5 Output YES 112323 Input 5 9 0 2 3 1 2 1 3 1 5 2 3 2 4 2 5 3 4 3 5 4 5 Output NO
6 3 2 2 2 3 1 5 4 2 5
YES 112323
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', '*2100']
D. Multisettime limit per test1.5 secondsmemory limit per test28 megabytesinputstandard inputoutputstandard outputNote that the memory limit is unusual.You are given a multiset consisting of n integers. You have to process queries of two types: add integer k into the multiset; find the k-th order statistics in the multiset and remove it. k-th order statistics in the multiset is the k-th element in the sorted list of all elements of the multiset. For example, if the multiset contains elements 1, 4, 2, 1, 4, 5, 7, and k = 3, then you have to find the 3-rd element in [1, 1, 2, 4, 4, 5, 7], which is 2. If you try to delete an element which occurs multiple times in the multiset, only one occurence is removed. After processing all queries, print any number belonging to the multiset, or say that it is empty.InputThe first line contains two integers n and q (1 \le n, q \le 10^6) — the number of elements in the initial multiset and the number of queries, respectively.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_1 \le a_2 \le \dots \le a_n \le n) — the elements of the multiset.The third line contains q integers k_1, k_2, ..., k_q, each representing a query: if 1 \le k_i \le n, then the i-th query is "insert k_i into the multiset"; if k_i < 0, then the i-th query is "remove the |k_i|-th order statistics from the multiset". For this query, it is guaranteed that |k_i| is not greater than the size of the multiset. OutputIf the multiset is empty after all queries, print 0.Otherwise, print any integer that belongs to the resulting multiset.ExamplesInput 5 5 1 2 3 4 5 -1 -1 -1 -1 -1 Output 0 Input 5 4 1 2 3 4 5 -5 -1 -3 -1 Output 3 Input 6 2 1 1 1 2 3 4 5 6 Output 6 NoteIn the first example, all elements of the multiset are deleted.In the second example, the elements 5, 1, 4, 2 are deleted (they are listed in chronological order of their removal).In the third example, 6 is not the only answer.
5 5 1 2 3 4 5 -1 -1 -1 -1 -1
0
1.5 seconds
28 megabytes
['binary search', 'data structures', '*1900']
C2. Not So Simple Polygon Embeddingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.You are given a regular polygon with 2 \cdot n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.You can rotate 2n-gon and/or the square.InputThe first line contains a single integer T (1 \le T \le 200) — the number of test cases.Next T lines contain descriptions of test cases — one per line. Each line contains single odd integer n (3 \le n \le 199). Don't forget you need to embed 2n-gon, not an n-gon.OutputPrint T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.ExampleInput 3 3 5 199 Output 1.931851653 3.196226611 126.687663595
3 3 5 199
1.931851653 3.196226611 126.687663595
2 seconds
256 megabytes
['binary search', 'brute force', 'geometry', 'math', '*2000']
C1. Simple Polygon Embeddingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.You are given a regular polygon with 2 \cdot n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.You can rotate 2n-gon and/or the square.InputThe first line contains a single integer T (1 \le T \le 200) — the number of test cases.Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 \le n \le 200). Don't forget you need to embed 2n-gon, not an n-gon.OutputPrint T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.ExampleInput 3 2 4 200 Output 1.000000000 2.414213562 127.321336469
3 2 4 200
1.000000000 2.414213562 127.321336469
2 seconds
256 megabytes
['binary search', 'geometry', 'math', 'ternary search', '*1400']
B. Ternary Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once.A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) characters from the beginning of s and some (possibly zero) characters from the end of s.InputThe first line contains one integer t (1 \le t \le 20000) — the number of test cases.Each test case consists of one line containing the string s (1 \le |s| \le 200000). It is guaranteed that each character of s is either 1, 2, or 3.The sum of lengths of all strings in all test cases does not exceed 200000.OutputFor each test case, print one integer — the length of the shortest contiguous substring of s containing all three types of characters at least once. If there is no such substring, print 0 instead.ExampleInput 7 123 12222133333332 112233 332211 12121212 333333 31121 Output 3 3 4 4 0 0 4 NoteConsider the example test:In the first test case, the substring 123 can be used.In the second test case, the substring 213 can be used.In the third test case, the substring 1223 can be used.In the fourth test case, the substring 3221 can be used.In the fifth test case, there is no character 3 in s.In the sixth test case, there is no character 1 in s.In the seventh test case, the substring 3112 can be used.
7 123 12222133333332 112233 332211 12121212 333333 31121
3 3 4 4 0 0 4
2 seconds
256 megabytes
['binary search', 'dp', 'implementation', 'two pointers', '*1200']
A. Alarm Clocktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed.Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes.Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than a minutes in total, then he sets his alarm to go off in c minutes after it is reset and spends d minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another c minutes and tries to fall asleep for d minutes again.You just want to find out when will Polycarp get out of his bed or report that it will never happen.Please check out the notes for some explanations of the example.InputThe first line contains one integer t (1 \le t \le 1000) — the number of testcases.The only line of each testcase contains four integers a, b, c, d (1 \le a, b, c, d \le 10^9) — the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.OutputFor each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.ExampleInput 7 10 3 6 4 11 3 6 4 5 9 4 10 6 5 2 3 1 1 1 1 3947465 47342 338129 123123 234123843 13 361451236 361451000 Output 27 27 9 -1 1 6471793 358578060125049 NoteIn the first testcase Polycarp wakes up after 3 minutes. He only rested for 3 minutes out of 10 minutes he needed. So after that he sets his alarm to go off in 6 minutes and spends 4 minutes falling asleep. Thus, he rests for 2 more minutes, totaling in 3+2=5 minutes of sleep. Then he repeats the procedure three more times and ends up with 11 minutes of sleep. Finally, he gets out of his bed. He spent 3 minutes before the first alarm and then reset his alarm four times. The answer is 3+4 \cdot 6 = 27.The second example is almost like the first one but Polycarp needs 11 minutes of sleep instead of 10. However, that changes nothing because he gets 11 minutes with these alarm parameters anyway.In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is b=9.In the fourth testcase Polycarp wakes up after 5 minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(
7 10 3 6 4 11 3 6 4 5 9 4 10 6 5 2 3 1 1 1 1 3947465 47342 338129 123123 234123843 13 361451236 361451000
27 27 9 -1 1 6471793 358578060125049
2 seconds
256 megabytes
['math', '*900']
F. Decreasing Heightstime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing one famous sandbox game with the three-dimensional world. The map of the world can be represented as a matrix of size n \times m, where the height of the cell (i, j) is a_{i, j}.You are in the cell (1, 1) right now and want to get in the cell (n, m). You can move only down (from the cell (i, j) to the cell (i + 1, j)) or right (from the cell (i, j) to the cell (i, j + 1)). There is an additional restriction: if the height of the current cell is x then you can move only to the cell with height x+1.Before the first move you can perform several operations. During one operation, you can decrease the height of any cell by one. I.e. you choose some cell (i, j) and assign (set) a_{i, j} := a_{i, j} - 1. Note that you can make heights less than or equal to zero. Also note that you can decrease the height of the cell (1, 1).Your task is to find the minimum number of operations you have to perform to obtain at least one suitable path from the cell (1, 1) to the cell (n, m). It is guaranteed that the answer exists.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and m (1 \le n, m \le 100) — the number of rows and the number of columns in the map of the world. The next n lines contain m integers each, where the j-th integer in the i-th line is a_{i, j} (1 \le a_{i, j} \le 10^{15}) — the height of the cell (i, j).It is guaranteed that the sum of n (as well as the sum of m) over all test cases does not exceed 100 (\sum n \le 100; \sum m \le 100).OutputFor each test case, print the answer — the minimum number of operations you have to perform to obtain at least one suitable path from the cell (1, 1) to the cell (n, m). It is guaranteed that the answer exists.ExampleInput 5 3 4 1 2 3 4 5 6 7 8 9 10 11 12 5 5 2 5 4 8 3 9 10 11 5 1 12 8 4 2 5 2 2 5 4 1 6 8 2 4 2 2 2 100 10 10 1 1 2 123456789876543 987654321234567 1 1 42 Output 9 49 111 864197531358023 0
5 3 4 1 2 3 4 5 6 7 8 9 10 11 12 5 5 2 5 4 8 3 9 10 11 5 1 12 8 4 2 5 2 2 5 4 1 6 8 2 4 2 2 2 100 10 10 1 1 2 123456789876543 987654321234567 1 1 42
9 49 111 864197531358023 0
2.5 seconds
256 megabytes
['brute force', 'dp', '*2200']
E. K-periodic Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a garland consisting of n lamps. States of the lamps are represented by the string s of length n. The i-th character of the string s_i equals '0' if the i-th lamp is turned off or '1' if the i-th lamp is turned on. You are also given a positive integer k.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called k-periodic if the distance between each pair of adjacent turned on lamps is exactly k. Consider the case k=3. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain k-periodic garland from the given one.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 25~ 000) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and k (1 \le n \le 10^6; 1 \le k \le n) — the length of s and the required period. The second line of the test case contains the string s consisting of n characters '0' and '1'.It is guaranteed that the sum of n over all test cases does not exceed 10^6 (\sum n \le 10^6).OutputFor each test case, print the answer — the minimum number of moves you need to make to obtain k-periodic garland from the given one.ExampleInput 6 9 2 010001010 9 3 111100000 7 4 1111111 10 3 1001110101 1 1 1 1 1 0 Output 1 2 5 4 0 0
6 9 2 010001010 9 3 111100000 7 4 1111111 10 3 1001110101 1 1 1 1 1 0
1 2 5 4 0 0
1 second
256 megabytes
['brute force', 'dp', 'greedy', '*1900']
D. Constructing the Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n consisting of zeros. You perform n actions with this array: during the i-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be [l; r]. If r-l+1 is odd (not divisible by 2) then assign (set) a[\frac{l+r}{2}] := i (where i is the number of the current action), otherwise (if r-l+1 is even) assign (set) a[\frac{l+r-1}{2}] := i. Consider the array a of length 5 (initially a=[0, 0, 0, 0, 0]). Then it changes as follows: Firstly, we choose the segment [1; 5] and assign a[3] := 1, so a becomes [0, 0, 1, 0, 0]; then we choose the segment [1; 2] and assign a[1] := 2, so a becomes [2, 0, 1, 0, 0]; then we choose the segment [4; 5] and assign a[4] := 3, so a becomes [2, 0, 1, 3, 0]; then we choose the segment [2; 2] and assign a[2] := 4, so a becomes [2, 4, 1, 3, 0]; and at last we choose the segment [5; 5] and assign a[5] := 5, so a becomes [2, 4, 1, 3, 5]. Your task is to find the array a of length n after performing all n actions. Note that the answer exists and unique.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of a.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the array a of length n after performing n actions described in the problem statement. Note that the answer exists and unique.ExampleInput 6 1 2 3 4 5 6 Output 1 1 2 2 1 3 3 1 2 4 2 4 1 3 5 3 4 1 5 2 6
6 1 2 3 4 5 6
1 1 2 2 1 3 3 1 2 4 2 4 1 3 5 3 4 1 5 2 6
1 second
256 megabytes
['constructive algorithms', 'data structures', 'sortings', '*1600']
C. Board Movestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a board of size n \times n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move the figure to cells: (i - 1, j - 1); (i - 1, j); (i - 1, j + 1); (i, j - 1); (i, j + 1); (i + 1, j - 1); (i + 1, j); (i + 1, j + 1); Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. n^2-1 cells should contain 0 figures and one cell should contain n^2 figures).You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 200) — the number of test cases. Then t test cases follow.The only line of the test case contains one integer n (1 \le n < 5 \cdot 10^5) — the size of the board. It is guaranteed that n is odd (not divisible by 2).It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^5 (\sum n \le 5 \cdot 10^5).OutputFor each test case print the answer — the minimum number of moves needed to get all the figures into one cell.ExampleInput 3 1 5 499993 Output 0 40 41664916690999888
3 1 5 499993
0 40 41664916690999888
1 second
256 megabytes
['math', '*1000']
B. Two Arrays And Swapstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.In one move, you can choose two indices i and j (1 \le i, j \le n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 with b_2 or swap a_3 and b_9 both are acceptable moves).Your task is to find the maximum possible sum you can obtain in the array a if you can do no more than (i.e. at most) k such moves (swaps).You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 200) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and k (1 \le n \le 30; 0 \le k \le n) — the number of elements in a and b and the maximum number of moves you can do. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 30), where a_i is the i-th element of a. The third line of the test case contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 30), where b_i is the i-th element of b.OutputFor each test case, print the answer — the maximum possible sum you can obtain in the array a if you can do no more than (i.e. at most) k swaps.ExampleInput 5 2 1 1 2 3 4 5 5 5 5 6 6 5 1 2 5 4 3 5 3 1 2 3 4 5 10 9 10 10 9 4 0 2 2 4 3 2 4 2 3 4 4 1 2 2 1 4 4 5 4 Output 6 27 39 11 17 NoteIn the first test case of the example, you can swap a_1 = 1 and b_2 = 4, so a=[4, 2] and b=[3, 1].In the second test case of the example, you don't need to swap anything.In the third test case of the example, you can swap a_1 = 1 and b_1 = 10, a_3 = 3 and b_3 = 10 and a_2 = 2 and b_4 = 10, so a=[10, 10, 10, 4, 5] and b=[1, 9, 3, 2, 9].In the fourth test case of the example, you cannot swap anything.In the fifth test case of the example, you can swap arrays a and b, so a=[4, 4, 5, 4] and b=[1, 2, 2, 1].
5 2 1 1 2 3 4 5 5 5 5 6 6 5 1 2 5 4 3 5 3 1 2 3 4 5 10 9 10 10 9 4 0 2 2 4 3 2 4 2 3 4 4 1 2 2 1 4 4 5 4
6 27 39 11 17
1 second
256 megabytes
['greedy', 'sortings', '*800']
A. Most Unstable Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value \sum\limits_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolute value of x.In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array a=[1, 3, 2, 5, 5, 0] then the value above for this array is |1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11. Note that this example doesn't show the optimal answer but it shows how the required value for some array is calculated.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains two integers n and m (1 \le n, m \le 10^9) — the length of the array and its sum correspondingly.OutputFor each test case, print the answer — the maximum possible value of \sum\limits_{i=1}^{n-1} |a_i - a_{i+1}| for the array a consisting of n non-negative integers with the sum m.ExampleInput 5 1 100 2 2 5 5 2 1000000000 1000000000 1000000000 Output 0 2 10 1000000000 2000000000 NoteIn the first test case of the example, the only possible array is [100] and the answer is obviously 0.In the second test case of the example, one of the possible arrays is [2, 0] and the answer is |2-0| = 2.In the third test case of the example, one of the possible arrays is [0, 2, 0, 3, 0] and the answer is |0-2| + |2-0| + |0-3| + |3-0| = 10.
5 1 100 2 2 5 5 2 1000000000 1000000000 1000000000
0 2 10 1000000000 2000000000
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*800']
G. Special Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of length n is an array p=[p_1,p_2,\dots,p_n], which contains every integer from 1 to n (inclusive) and, moreover, each number appears exactly once. For example, p=[3,1,4,2,5] is a permutation of length 5.For a given number n (n \ge 2), find a permutation p in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between 2 and 4, inclusive. Formally, find such permutation p that 2 \le |p_i - p_{i+1}| \le 4 for each i (1 \le i < n).Print any such permutation for the given integer n or determine that it does not exist.InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases in the input. Then t test cases follow.Each test case is described by a single line containing an integer n (2 \le n \le 1000).OutputPrint t lines. Print a permutation that meets the given requirements. If there are several such permutations, then print any of them. If no such permutation exists, print -1.ExampleInput 6 10 2 4 6 7 13 Output 9 6 10 8 4 7 3 1 5 2 -1 3 1 4 2 5 3 6 2 4 1 5 1 3 6 2 4 7 13 9 7 11 8 4 1 3 5 2 6 10 12
6 10 2 4 6 7 13
9 6 10 8 4 7 3 1 5 2 -1 3 1 4 2 5 3 6 2 4 1 5 1 3 6 2 4 7 13 9 7 11 8 4 1 3 5 2 6 10 12
2 seconds
256 megabytes
['constructive algorithms', '*1600']
F. Binary String Reconstructiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor some binary string s (i.e. each character s_i is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length 2 were written. For each pair (substring of length 2), the number of '1' (ones) in it was calculated.You are given three numbers: n_0 — the number of such pairs of consecutive characters (substrings) where the number of ones equals 0; n_1 — the number of such pairs of consecutive characters (substrings) where the number of ones equals 1; n_2 — the number of such pairs of consecutive characters (substrings) where the number of ones equals 2. For example, for the string s="1110011110", the following substrings would be written: "11", "11", "10", "00", "01", "11", "11", "11", "10". Thus, n_0=1, n_1=3, n_2=5.Your task is to restore any suitable binary string s from the given values n_0, n_1, n_2. It is guaranteed that at least one of the numbers n_0, n_1, n_2 is greater than 0. Also, it is guaranteed that a solution exists.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases in the input. Then test cases follow.Each test case consists of one line which contains three integers n_0, n_1, n_2 (0 \le n_0, n_1, n_2 \le 100; n_0 + n_1 + n_2 > 0). It is guaranteed that the answer for given n_0, n_1, n_2 exists.OutputPrint t lines. Each of the lines should contain a binary string corresponding to a test case. If there are several possible solutions, print any of them.ExampleInput 7 1 3 5 1 1 1 3 9 3 0 1 0 3 1 2 0 0 3 2 0 0 Output 1110011110 0011 0110001100101011 10 0000111 1111 000
7 1 3 5 1 1 1 3 9 3 0 1 0 3 1 2 0 0 3 2 0 0
1110011110 0011 0110001100101011 10 0000111 1111 000
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'math', '*1500']
E. Special Elementstime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputPay attention to the non-standard memory limit in this problem.In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.The array a=[a_1, a_2, \ldots, a_n] (1 \le a_i \le n) is given. Its element a_i is called special if there exists a pair of indices l and r (1 \le l < r \le n) such that a_i = a_l + a_{l+1} + \ldots + a_r. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).Print the number of special elements of the given array a.For example, if n=9 and a=[3,1,4,1,5,9,2,6,5], then the answer is 5: a_3=4 is a special element, since a_3=4=a_1+a_2=3+1; a_5=5 is a special element, since a_5=5=a_2+a_3=1+4; a_6=9 is a special element, since a_6=9=a_1+a_2+a_3+a_4=3+1+4+1; a_8=6 is a special element, since a_8=6=a_2+a_3+a_4=1+4+1; a_9=5 is a special element, since a_9=5=a_2+a_3=1+4. Please note that some of the elements of the array a may be equal — if several elements are equal and special, then all of them should be counted in the answer.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases in the input. Then t test cases follow.Each test case is given in two lines. The first line contains an integer n (1 \le n \le 8000) — the length of the array a. The second line contains integers a_1, a_2, \dots, a_n (1 \le a_i \le n).It is guaranteed that the sum of the values of n for all test cases in the input does not exceed 8000.OutputPrint t numbers — the number of special elements for each of the given arrays.ExampleInput 5 9 3 1 4 1 5 9 2 6 5 3 1 1 2 5 1 1 1 1 1 8 8 7 6 5 4 3 2 1 1 1 Output 5 1 0 4 0
5 9 3 1 4 1 5 9 2 6 5 3 1 1 2 5 1 1 1 1 1 8 8 7 6 5 4 3 2 1 1 1
5 1 0 4 0
1 second
64 megabytes
['brute force', 'implementation', 'two pointers', '*1500']
D. Alice, Bob and Candiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i.Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).Alice makes the first move. During the first move, she will eat 1 candy (its size is a_1). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.For example, if n=11 and a=[3,1,4,1,5,9,2,6,5,3,5], then: move 1: Alice eats one candy of size 3 and the sequence of candies becomes [1,4,1,5,9,2,6,5,3,5]. move 2: Alice ate 3 on the previous move, which means Bob must eat 4 or more. Bob eats one candy of size 5 and the sequence of candies becomes [1,4,1,5,9,2,6,5,3]. move 3: Bob ate 5 on the previous move, which means Alice must eat 6 or more. Alice eats three candies with the total size of 1+4+1=6 and the sequence of candies becomes [5,9,2,6,5,3]. move 4: Alice ate 6 on the previous move, which means Bob must eat 7 or more. Bob eats two candies with the total size of 3+5=8 and the sequence of candies becomes [5,9,2,6]. move 5: Bob ate 8 on the previous move, which means Alice must eat 9 or more. Alice eats two candies with the total size of 5+9=14 and the sequence of candies becomes [2,6]. move 6 (the last): Alice ate 14 on the previous move, which means Bob must eat 15 or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers: a — the total size of all sweets eaten by Alice during the game; b — the total size of all sweets eaten by Bob during the game. InputThe first line contains an integer t (1 \le t \le 5000) — the number of test cases in the input. The following are descriptions of the t test cases.Each test case consists of two lines. The first line contains an integer n (1 \le n \le 1000) — the number of candies. The second line contains a sequence of integers a_1, a_2, \dots, a_n (1 \le a_i \le 1000) — the sizes of candies in the order they are arranged from left to right.It is guaranteed that the sum of the values of n for all sets of input data in a test does not exceed 2\cdot10^5.OutputFor each set of input data print three integers — the number of moves in the game and the required values a and b.ExampleInput 7 11 3 1 4 1 5 9 2 6 5 3 5 1 1000 3 1 1 1 13 1 2 3 4 5 6 7 8 9 10 11 12 13 2 2 1 6 1 1 1 1 1 1 7 1 1 1 1 1 1 1 Output 6 23 21 1 1000 0 2 1 2 6 45 46 2 2 1 3 4 2 4 4 3
7 11 3 1 4 1 5 9 2 6 5 3 5 1 1000 3 1 1 1 13 1 2 3 4 5 6 7 8 9 10 11 12 13 2 2 1 6 1 1 1 1 1 1 7 1 1 1 1 1 1 1
6 23 21 1 1000 0 2 1 2 6 45 46 2 2 1 3 4 2 4 4 3
2 seconds
256 megabytes
['implementation', '*1300']
C. K-th Not Divisible by ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 \dots. The 7-th number among them is 10.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases in the input. Next, t test cases are given, one per line.Each test case is two positive integers n (2 \le n \le 10^9) and k (1 \le k \le 10^9).OutputFor each test case print the k-th positive integer that is not divisible by n.ExampleInput 6 3 7 4 12 2 1000000000 7 97 1000000000 1000000000 2 1 Output 10 15 1999999999 113 1000000001 1
6 3 7 4 12 2 1000000000 7 97 1000000000 1000000000 2 1
10 15 1999999999 113 1000000001 1
1 second
256 megabytes
['binary search', 'math', '*1200']
B. Same Parity Summandstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers n (1 \le n \le 10^9) and k (1 \le k \le 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).In other words, find a_1, a_2, \ldots, a_k such that all a_i>0, n = a_1 + a_2 + \ldots + a_k and either all a_i are even or all a_i are odd at the same time.If such a representation does not exist, then report it.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases in the input. Next, t test cases are given, one per line.Each test case is two positive integers n (1 \le n \le 10^9) and k (1 \le k \le 100).OutputFor each test case print: YES and the required values a_i, if the answer exists (if there are several answers, print any of them); NO if the answer does not exist. The letters in the words YES and NO can be printed in any case.ExampleInput 8 10 3 100 4 8 7 97 2 8 8 3 10 5 3 1000000000 9 Output YES 4 2 4 YES 55 5 5 35 NO NO YES 1 1 1 1 1 1 1 1 NO YES 3 1 1 YES 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
8 10 3 100 4 8 7 97 2 8 8 3 10 5 3 1000000000 9
YES 4 2 4 YES 55 5 5 35 NO NO YES 1 1 1 1 1 1 1 1 NO YES 3 1 1 YES 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
1 second
256 megabytes
['constructive algorithms', 'math', '*1200']
A. Sum of Round Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.For example, the following numbers are round: 4000, 1, 9, 800, 90. The following numbers are not round: 110, 707, 222, 1001.You are given a positive integer n (1 \le n \le 10^4). Represent the number n as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number n as a sum of the least number of terms, each of which is a round number.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.Each test case is a line containing an integer n (1 \le n \le 10^4).OutputPrint t answers to the test cases. Each answer must begin with an integer k — the minimum number of summands. Next, k terms must follow, each of which is a round number, and their sum is n. The terms can be printed in any order. If there are several answers, print any of them.ExampleInput 5 5009 7 9876 10000 10 Output 2 5000 9 1 7 4 800 70 6 9000 1 10000 1 10
5 5009 7 9876 10000 10
2 5000 9 1 7 4 800 70 6 9000 1 10000 1 10
1 second
256 megabytes
['implementation', 'math', '*800']
C. Skiertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSkier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to 1 meter movement in the south, north, west or east direction respectively).It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visited the first time), then the time of such movement is 5 seconds. If he rolls along previously visited segment of a path (i.e., this segment of the path has been covered by his path before), then it takes 1 second.Find the skier's time to roll all the path.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.Each set is given by one nonempty string of the characters 'S', 'N', 'W', 'E'. The length of the string does not exceed 10^5 characters.The sum of the lengths of t given lines over all test cases in the input does not exceed 10^5.OutputFor each test case, print the desired path time in seconds.ExampleInput 5 NNN NS WWEN WWEE NWNWS Output 15 6 16 12 25
5 NNN NS WWEN WWEE NWNWS
15 6 16 12 25
1 second
256 megabytes
['data structures', 'implementation', '*1400']
B. Square?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.Each test case is given in two lines.The first line contains two integers a_1 and b_1 (1 \le a_1, b_1 \le 100) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).The second line contains two integers a_2 and b_2 (1 \le a_2, b_2 \le 100) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).OutputPrint t answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).ExampleInput 3 2 3 3 1 3 2 1 3 3 3 1 3 Output Yes Yes No
3 2 3 3 1 3 2 1 3 3 3 1 3
Yes Yes No
1 second
256 megabytes
['brute force', 'implementation', 'math', '*900']
A. A+B (Trial Problem)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers a and b. Print a+b.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.Each test case is given as a line of two integers a and b (-1000 \le a, b \le 1000).OutputPrint t integers — the required numbers a+b.ExampleInput 4 1 5 314 15 -99 99 123 987 Output 6 329 0 1110
4 1 5 314 15 -99 99 123 987
6 329 0 1110
1 second
256 megabytes
['implementation', '*800']
B. Orac and Modelstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n models in the shop numbered from 1 to n, with sizes s_1, s_2, \ldots, s_n.Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices i_j and i_{j+1} (note that i_j < i_{j+1}, because Orac arranged them properly), i_{j+1} is divisible by i_j and s_{i_j} < s_{i_{j+1}}.For example, for 6 models with sizes \{3, 6, 7, 7, 7, 7\}, he can buy models with indices 1, 2, and 6, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.InputThe first line contains one integer t\ (1 \le t\le 100): the number of queries.Each query contains two lines. The first line contains one integer n\ (1\le n\le 100\,000): the number of models in the shop, and the second line contains n integers s_1,\dots,s_n\ (1\le s_i\le 10^9): the sizes of models.It is guaranteed that the total sum of n is at most 100\,000.OutputPrint t lines, the i-th of them should contain the maximum number of models that Orac can buy for the i-th query.ExampleInput 4 4 5 3 4 6 7 1 4 2 3 6 4 9 5 5 4 3 2 1 1 9 Output 2 3 1 1 NoteIn the first query, for example, Orac can buy models with indices 2 and 4, the arrangement will be beautiful because 4 is divisible by 2 and 6 is more than 3. By enumerating, we can easily find that there are no beautiful arrangements with more than two models. In the second query, Orac can buy models with indices 1, 3, and 6. By enumerating, we can easily find that there are no beautiful arrangements with more than three models. In the third query, there are no beautiful arrangements with more than one model.
4 4 5 3 4 6 7 1 4 2 3 6 4 9 5 5 4 3 2 1 1 9
2 3 1 1
3 seconds
256 megabytes
['dp', 'math', 'number theory', '*1400']
A. Orac and Factorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOrac is studying number theory, and he is interested in the properties of divisors.For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a\cdot c=b.For n \ge 2, we will denote as f(n) the smallest positive divisor of n, except 1.For example, f(7)=7,f(10)=2,f(35)=5.For the fixed integer n, Orac decided to add f(n) to n. For example, if he had an integer n=5, the new value of n will be equal to 10. And if he had an integer n=6, n will be changed to 8.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers n and k, Orac asked you to add f(n) to n exactly k times (note that n will change after each operation, so f(n) may change too) and tell him the final value of n.For example, if Orac gives you n=5 and k=2, at first you should add f(5)=5 to n=5, so your new value of n will be equal to n=10, after that, you should add f(10)=2 to 10, so your new (and the final!) value of n will be equal to 12.Orac may ask you these queries many times.InputThe first line of the input is a single integer t\ (1\le t\le 100): the number of times that Orac will ask you.Each of the next t lines contains two positive integers n,k\ (2\le n\le 10^6, 1\le k\le 10^9), corresponding to a query by Orac.It is guaranteed that the total sum of n is at most 10^6. OutputPrint t lines, the i-th of them should contain the final value of n in the i-th query by Orac.ExampleInput 3 5 1 8 2 3 4 Output 10 12 12 NoteIn the first query, n=5 and k=1. The divisors of 5 are 1 and 5, the smallest one except 1 is 5. Therefore, the only operation adds f(5)=5 to 5, and the result is 10.In the second query, n=8 and k=2. The divisors of 8 are 1,2,4,8, where the smallest one except 1 is 2, then after one operation 8 turns into 8+(f(8)=2)=10. The divisors of 10 are 1,2,5,10, where the smallest one except 1 is 2, therefore the answer is 10+(f(10)=2)=12.In the third query, n is changed as follows: 3 \to 6 \to 8 \to 10 \to 12.
3 5 1 8 2 3 4
10 12 12
2 seconds
256 megabytes
['math', '*900']
F2. Slime and Sequences (Hard Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote that the only differences between easy and hard versions are the constraints on n and the time limit. You can make hacks only if all versions are solved.Slime is interested in sequences. He defined good positive integer sequences p of length n as follows: For each k>1 that presents in p, there should be at least one pair of indices i,j, such that 1 \leq i < j \leq n, p_i = k - 1 and p_j = k.For the given integer n, the set of all good sequences of length n is s_n. For the fixed integer k and the sequence p, let f_p(k) be the number of times that k appears in p. For each k from 1 to n, Slime wants to know the following value:\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353InputThe first line contains one integer n\ (1\le n\le 100\,000).OutputPrint n integers, the i-th of them should be equal to \left(\sum_{p\in s_n} f_p(i)\right)\ \textrm{mod}\ 998\,244\,353.ExamplesInput 2 Output 3 1 Input 3 Output 10 7 1 Input 1 Output 1 NoteIn the first example, s=\{[1,1],[1,2]\}.In the second example, s=\{[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,2],[1,2,3]\}.In the third example, s=\{[1]\}.
2
3 1
3 seconds
256 megabytes
['dp', 'fft', 'math', '*3500']
F1. Slime and Sequences (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote that the only differences between easy and hard versions are the constraints on n and the time limit. You can make hacks only if all versions are solved.Slime is interested in sequences. He defined good positive integer sequences p of length n as follows: For each k>1 that presents in p, there should be at least one pair of indices i,j, such that 1 \leq i < j \leq n, p_i = k - 1 and p_j = k.For the given integer n, the set of all good sequences of length n is s_n. For the fixed integer k and the sequence p, let f_p(k) be the number of times that k appears in p. For each k from 1 to n, Slime wants to know the following value:\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353InputThe first line contains one integer n\ (1\le n\le 5000).OutputPrint n integers, the i-th of them should be equal to \left(\sum_{p\in s_n} f_p(i)\right)\ \textrm{mod}\ 998\,244\,353.ExamplesInput 2 Output 3 1 Input 3 Output 10 7 1 Input 1 Output 1 NoteIn the first example, s=\{[1,1],[1,2]\}.In the second example, s=\{[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,2],[1,2,3]\}.In the third example, s=\{[1]\}.
2
3 1
2 seconds
256 megabytes
['dp', 'fft', 'math', '*3100']
E. Slime and Hatstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSlime and Orac are holding a turn-based game. In a big room, there are n players sitting on the chairs, looking forward to a column and each of them is given a number: player 1 sits in the front of the column, player 2 sits directly behind him; player 3 sits directly behind player 2, and so on; player n sits directly behind player n-1. Each player wears a hat that is either black or white. As each player faces forward, player i knows the color of player j's hat if and only if i is larger than j.At the start of each turn, Orac will tell whether there exists a player wearing a black hat in the room.After Orac speaks, if the player can uniquely identify the color of his hat, he will put his hat on the chair, stand up and leave the room. All players are smart, so if it is possible to understand the color of their hat using the obtained information during this and previous rounds, they will understand it. In each turn, all players who know the color of their hats will leave at the same time in this turn, which means a player can only leave in the next turn if he gets to know the color of his hat only after someone left the room at this turn.Note that when the player needs to leave, he will put the hat on the chair before leaving, so the players ahead of him still cannot see his hat. The i-th player will know who exactly left the room among players 1,2,\ldots,i-1, and how many players among i+1,i+2,\ldots,n have left the room.Slime stands outdoor. He watches the players walking out and records the numbers of the players and the time they get out. Unfortunately, Slime is so careless that he has only recorded some of the data, and this given data is in the format "player x leaves in the y-th round".Slime asked you to tell him the color of each player's hat. If there are multiple solutions, you can find any of them.InputThe first line contains a integer n\ (1\le n\le 200\,000).The second line contains n integers t_1,t_2,\dots,t_n\ (0\le t_i\le 10^{15}). If t_i=0, then there are no data about player i; otherwise it means player i leaves in the t_i-th round.At least one solution exists for the given input. OutputPrint one binary string of n characters. The i-th character of the string should be '1' if player i wears a black hat and should be '0', otherwise. If there are multiple solutions, you can print any of them.ExamplesInput 5 0 1 1 0 0 Output 00000Input 5 0 2 2 0 0 Output 00001Input 5 0 0 0 0 0 Output 00000Input 5 4 4 0 4 4 Output 00100NoteIn the first example, for the given solution, all the players wear white hats. In the first turn, Orac tells all the players that there are no players wearing a black hat, so each player knows that he is wearing a white hat, and he will leave in the first turn.In the second example, for the given solution, the player 5 wears a black hat, other players wear white hats. Orac tells all the players that there exists a player wearing a black hat, and player 5 know that the other players are all wearing white hats, so he can infer that he is wearing a black hat; therefore he leaves in the first turn, other players leave in the second turn. Note that other players can infer that they are wearing white hats immediately after player 5 leaves, but they have to wait for the next turn to leave according to the rule.In the third example, there is no information about the game, so any output is correct.
5 0 1 1 0 0
00000
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*3500']
D. Slime and Biscuitstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSlime and his n friends are at a party. Slime has designed a game for his friends to play.At the beginning of the game, the i-th player has a_i biscuits. At each second, Slime will choose a biscuit randomly uniformly among all a_1 + a_2 + \ldots + a_n biscuits, and the owner of this biscuit will give it to a random uniform player among n-1 players except himself. The game stops when one person will have all the biscuits.As the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time.For convenience, as the answer can be represented as a rational number \frac{p}{q} for coprime p and q, you need to find the value of (p \cdot q^{-1})\mod 998\,244\,353. You can prove that q\mod 998\,244\,353 \neq 0.InputThe first line contains one integer n\ (2\le n\le 100\,000): the number of people playing the game.The second line contains n non-negative integers a_1,a_2,\dots,a_n\ (1\le a_1+a_2+\dots+a_n\le 300\,000), where a_i represents the number of biscuits the i-th person own at the beginning.OutputPrint one integer: the expected value of the time that the game will last, modulo 998\,244\,353.ExamplesInput 2 1 1 Output 1 Input 2 1 2 Output 3 Input 5 0 0 0 0 35 Output 0 Input 5 8 4 2 0 1 Output 801604029 NoteFor the first example, in the first second, the probability that player 1 will give the player 2 a biscuit is \frac{1}{2}, and the probability that player 2 will give the player 1 a biscuit is \frac{1}{2}. But anyway, the game will stop after exactly 1 second because only one player will occupy all biscuits after 1 second, so the answer is 1.
2 1 1
1
2 seconds
256 megabytes
['math', 'probabilities', '*3200']
C. Orac and Game of Lifetime limit per test2 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputPlease notice the unusual memory limit of this problem.Orac likes games. Recently he came up with the new game, "Game of Life".You should play this game on a black and white grid with n rows and m columns. Each cell is either black or white.For each iteration of the game (the initial iteration is 0), the color of each cell will change under the following rules: If there are no adjacent cells with the same color as this cell on the current iteration, the color of it on the next iteration will be the same. Otherwise, the color of the cell on the next iteration will be different.Two cells are adjacent if they have a mutual edge.Now Orac has set an initial situation, and he wants to know for the cell (i,j) (in i-th row and j-th column), what will be its color at the iteration p. He may ask you these questions several times. InputThe first line contains three integers n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000), representing the number of rows, columns, and the number of Orac queries.Each of the following n lines contains a binary string of length m, the j-th character in i-th line represents the initial color of cell (i,j). '0' stands for white, '1' stands for black.Each of the following t lines contains three integers i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18}), representing a query from Orac.OutputPrint t lines, in i-th line you should print the answer to the i-th query by Orac. If the color of this cell is black, you should print '1'; otherwise, you should write '0'.ExamplesInput 3 3 3 000 111 000 1 1 1 2 2 2 3 3 3 Output 1 1 1 Input 5 2 2 01 10 01 10 01 1 1 4 5 1 4 Output 0 0 Input 5 5 3 01011 10110 01101 11010 10101 1 1 4 1 2 3 5 5 3 Output 1 0 1 Input 1 1 3 0 1 1 1 1 1 2 1 1 3 Output 0 0 0 Note For the first example, the picture above shows the initial situation and the color of cells at the iteration 1, 2, and 3. We can see that the color of (1,1) at the iteration 1 is black, the color of (2,2) at the iteration 2 is black, and the color of (3,3) at the iteration 3 is also black.For the second example, you can prove that the cells will never change their colors.
3 3 3 000 111 000 1 1 1 2 2 2 3 3 3
1 1 1
2 seconds
128 megabytes
['dfs and similar', 'graphs', 'implementation', 'shortest paths', '*2000']
B. Orac and Medianstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSlime has a sequence of positive integers a_1, a_2, \ldots, a_n.In one operation Orac can choose an arbitrary subsegment [l \ldots r] of this sequence and replace all values a_l, a_{l + 1}, \ldots, a_r to the value of median of \{a_l, a_{l + 1}, \ldots, a_r\}.In this problem, for the integer multiset s, the median of s is equal to the \lfloor \frac{|s|+1}{2}\rfloor-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5.Slime wants Orac to make a_1 = a_2 = \ldots = a_n = k using these operations.Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.InputThe first line of the input is a single integer t: the number of queries.The first line of each query contains two integers n\ (1\le n\le 100\,000) and k\ (1\le k\le 10^9), the second line contains n positive integers a_1,a_2,\dots,a_n\ (1\le a_i\le 10^9)The total sum of n is at most 100\,000.OutputThe output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase.ExampleInput 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes NoteIn the first query, Orac can't turn all elements into 3.In the second query, a_1=6 is already satisfied.In the third query, Orac can select the complete array and turn all elements into 2.In the fourth query, Orac can't turn all elements into 3.In the fifth query, Orac can select [1,6] at first and then select [2,10].
5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10
no yes yes no yes
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', '*2000']
A. Orac and LCMtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor the multiset of positive integers s=\{s_1,s_2,\dots,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow: \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x. \textrm{lcm}(s) is the minimum positive integer x, that divisible on all integers from s.For example, \gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6 and \textrm{lcm}(\{4,6\})=12. Note that for any positive integer x, \gcd(\{x\})=\textrm{lcm}(\{x\})=x.Orac has a sequence a with length n. He come up with the multiset t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}, and asked you to find the value of \gcd(t) for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.InputThe first line contains one integer n\ (2\le n\le 100\,000).The second line contains n integers, a_1, a_2, \ldots, a_n (1 \leq a_i \leq 200\,000).OutputPrint one integer: \gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}).ExamplesInput 2 1 1 Output 1 Input 4 10 24 40 80 Output 40 Input 10 540 648 810 648 720 540 594 864 972 648 Output 54 NoteFor the first example, t=\{\textrm{lcm}(\{1,1\})\}=\{1\}, so \gcd(t)=1.For the second example, t=\{120,40,80,120,240,80\}, and it's not hard to see that \gcd(t)=40.
2 1 1
1
3 seconds
256 megabytes
['data structures', 'math', 'number theory', '*1600']
F. Phoenix and Memorytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix is trying to take a photo of his n friends with labels 1, 2, \dots, n who are lined up in a row in a special order. But before he can take the photo, his friends get distracted by a duck and mess up their order.Now, Phoenix must restore the order but he doesn't remember completely! He only remembers that the i-th friend from the left had a label between a_i and b_i inclusive. Does there exist a unique way to order his friends based of his memory? InputThe first line contains one integer n (1 \le n \le 2\cdot10^5)  — the number of friends.The i-th of the next n lines contain two integers a_i and b_i (1 \le a_i \le b_i \le n)  — Phoenix's memory of the i-th position from the left.It is guaranteed that Phoenix's memory is valid so there is at least one valid ordering.OutputIf Phoenix can reorder his friends in a unique order, print YES followed by n integers  — the i-th integer should be the label of the i-th friend from the left.Otherwise, print NO. Then, print any two distinct valid orderings on the following two lines. If are multiple solutions, print any.ExamplesInput 4 4 4 1 3 2 4 3 4 Output YES 4 1 2 3 Input 4 1 3 2 4 3 4 2 3 Output NO 1 3 4 2 1 2 4 3
4 4 4 1 3 2 4 3 4
YES 4 1 2 3
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'greedy', '*2600']
E. Phoenix and Berriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix is picking berries in his backyard. There are n shrubs, and each shrub has a_i red berries and b_i blue berries.Each basket can contain k berries. But, Phoenix has decided that each basket may only contain berries from the same shrub or berries of the same color (red or blue). In other words, all berries in a basket must be from the same shrub or/and have the same color.For example, if there are two shrubs with 5 red and 2 blue berries in the first shrub and 2 red and 1 blue berries in the second shrub then Phoenix can fill 2 baskets of capacity 4 completely: the first basket will contain 3 red and 1 blue berries from the first shrub; the second basket will contain the 2 remaining red berries from the first shrub and 2 red berries from the second shrub. Help Phoenix determine the maximum number of baskets he can fill completely!InputThe first line contains two integers n and k ( 1\le n, k \le 500) — the number of shrubs and the basket capacity, respectively.The i-th of the next n lines contain two integers a_i and b_i (0 \le a_i, b_i \le 10^9) — the number of red and blue berries in the i-th shrub, respectively.OutputOutput one integer — the maximum number of baskets that Phoenix can fill completely.ExamplesInput 2 4 5 2 2 1 Output 2 Input 1 5 2 3 Output 1 Input 2 5 2 1 1 3 Output 0 Input 1 2 1000000000 1 Output 500000000 NoteThe first example is described above.In the second example, Phoenix can fill one basket fully using all the berries from the first (and only) shrub.In the third example, Phoenix cannot fill any basket completely because there are less than 5 berries in each shrub, less than 5 total red berries, and less than 5 total blue berries.In the fourth example, Phoenix can put all the red berries into baskets, leaving an extra blue berry behind.
2 4 5 2 2 1
2
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'math', '*2400']
D. Phoenix and Sciencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix has decided to become a scientist! He is currently investigating the growth of bacteria.Initially, on day 1, there is one bacterium with mass 1.Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass m splits, it becomes two bacteria of mass \frac{m}{2} each. For example, a bacterium of mass 3 can split into two bacteria of mass 1.5.Also, every night, the mass of every bacteria will increase by one.Phoenix is wondering if it is possible for the total mass of all the bacteria to be exactly n. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist!InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains an integer n (2 \le n \le 10^9) — the sum of bacteria masses that Phoenix is interested in. OutputFor each test case, if there is no way for the bacteria to exactly achieve total mass n, print -1. Otherwise, print two lines.The first line should contain an integer d  — the minimum number of nights needed.The next line should contain d integers, with the i-th integer representing the number of bacteria that should split on the i-th day.If there are multiple solutions, print any.ExampleInput 3 9 11 2 Output 3 1 0 2 3 1 1 2 1 0 NoteIn the first test case, the following process results in bacteria with total mass 9: Day 1: The bacterium with mass 1 splits. There are now two bacteria with mass 0.5 each. Night 1: All bacteria's mass increases by one. There are now two bacteria with mass 1.5. Day 2: None split. Night 2: There are now two bacteria with mass 2.5. Day 3: Both bacteria split. There are now four bacteria with mass 1.25. Night 3: There are now four bacteria with mass 2.25. The total mass is 2.25+2.25+2.25+2.25=9. It can be proved that 3 is the minimum number of nights needed. There are also other ways to obtain total mass 9 in 3 nights. In the second test case, the following process results in bacteria with total mass 11: Day 1: The bacterium with mass 1 splits. There are now two bacteria with mass 0.5. Night 1: There are now two bacteria with mass 1.5. Day 2: One bacterium splits. There are now three bacteria with masses 0.75, 0.75, and 1.5. Night 2: There are now three bacteria with masses 1.75, 1.75, and 2.5. Day 3: The bacteria with mass 1.75 and the bacteria with mass 2.5 split. There are now five bacteria with masses 0.875, 0.875, 1.25, 1.25, and 1.75. Night 3: There are now five bacteria with masses 1.875, 1.875, 2.25, 2.25, and 2.75. The total mass is 1.875+1.875+2.25+2.25+2.75=11. It can be proved that 3 is the minimum number of nights needed. There are also other ways to obtain total mass 11 in 3 nights. In the third test case, the bacterium does not split on day 1, and then grows to mass 2 during night 1.
3 9 11 2
3 1 0 2 3 1 1 2 1 0
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'greedy', 'implementation', 'math', '*1900']
C. Phoenix and Distributiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, \dots, a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and rearrange the letters within each string a_i however he wants.For example, if s = baba and k=2, Phoenix may distribute the letters of his string in many ways, such as: ba and ba a and abb ab and ab aa and bb But these ways are invalid: baa and ba b and ba baba and empty string (a_i should be non-empty) Phoenix wants to distribute the letters of his string s into k strings a_1, a_2, \dots, a_k to minimize the lexicographically maximum string among them, i. e. minimize max(a_1, a_2, \dots, a_k). Help him find the optimal distribution and print the minimal possible value of max(a_1, a_2, \dots, a_k).String x is lexicographically less than string y if either x is a prefix of y and x \ne y, or there exists an index i (1 \le i \le min(|x|, |y|)) such that x_i < y_i and for every j (1 \le j < i) x_j = y_j. Here |x| denotes the length of the string x.InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 1000) — the number of test cases. Each test case consists of two lines.The first line of each test case consists of two integers n and k (1 \le k \le n \le 10^5) — the length of string s and the number of non-empty strings, into which Phoenix wants to distribute letters of s, respectively.The second line of each test case contains a string s of length n consisting only of lowercase Latin letters.It is guaranteed that the sum of n over all test cases is \le 10^5.OutputPrint t answers — one per test case. The i-th answer should be the minimal possible value of max(a_1, a_2, \dots, a_k) in the i-th test case.ExampleInput 6 4 2 baba 5 2 baacb 5 3 baacb 5 3 aaaaa 6 4 aaxxzz 7 1 phoenix Output ab abbc b aa x ehinopx NoteIn the first test case, one optimal solution is to distribute baba into ab and ab. In the second test case, one optimal solution is to distribute baacb into abbc and a.In the third test case, one optimal solution is to distribute baacb into ac, ab, and b.In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a.In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x.In the sixth test case, one optimal solution is to distribute phoenix into ehinopx.
6 4 2 baba 5 2 baacb 5 3 baacb 5 3 aaaaa 6 4 aaxxzz 7 1 phoenix
ab abbc b aa x ehinopx
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'sortings', 'strings', '*1600']
B. Phoenix and Beautytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between 1 and n inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 50) — the number of test cases.The first line of each test case contains two integers n and k (1 \le k \le n \le 100).The second line of each test case contains n space-separated integers (1 \le a_i \le n) — the array that Phoenix currently has. This array may or may not be already beautiful.OutputFor each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines.The first line should contain the length of the beautiful array m (n \le m \le 10^4). You don't need to minimize m.The second line should contain m space-separated integers (1 \le b_i \le n) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array a. You may print integers that weren't originally in array a.If there are multiple solutions, print any. It's guaranteed that if we can make array a beautiful, we can always make it with resulting length no more than 10^4.ExampleInput 4 4 2 1 2 2 1 4 3 1 2 2 1 3 2 1 2 3 4 4 4 3 4 2 Output 5 1 2 1 2 1 4 1 2 2 1 -1 7 4 3 2 1 4 3 2NoteIn the first test case, we can make array a beautiful by inserting the integer 1 at index 3 (in between the two existing 2s). Now, all subarrays of length k=2 have the same sum 3. There exists many other possible solutions, for example: 2, 1, 2, 1, 2, 1 1, 2, 1, 2, 1, 2 In the second test case, the array is already beautiful: all subarrays of length k=3 have the same sum 5.In the third test case, it can be shown that we cannot insert numbers to make array a beautiful.In the fourth test case, the array b shown is beautiful and all subarrays of length k=4 have the same sum 10. There exist other solutions also.
4 4 2 1 2 2 1 4 3 1 2 2 1 3 2 1 2 3 4 4 4 3 4 2
5 1 2 1 2 1 4 1 2 2 1 -1 7 4 3 2 1 4 3 2
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'sortings', '*1400']
A. Phoenix and Balancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix has n coins with weights 2^1, 2^2, \dots, 2^n. He knows that n is even.He wants to split the coins into two piles such that each pile has exactly \frac{n}{2} coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weights in the second pile. Help Phoenix minimize |a-b|, the absolute value of a-b.InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains an integer n (2 \le n \le 30; n is even) — the number of coins that Phoenix has. OutputFor each test case, output one integer — the minimum possible difference of weights between the two piles.ExampleInput 2 2 4 Output 2 6 NoteIn the first test case, Phoenix has two coins with weights 2 and 4. No matter how he divides the coins, the difference will be 4-2=2.In the second test case, Phoenix has four coins of weight 2, 4, 8, and 16. It is optimal for Phoenix to place coins with weights 2 and 16 in one pile, and coins with weights 4 and 8 in another pile. The difference is (2+16)-(4+8)=6.
2 2 4
2 6
2 seconds
256 megabytes
['greedy', 'math', '*800']
I. Pac-Man 2.0time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is developing a new version of an old video game "Pac-Man". Though he really enjoyed playing the original game, he didn't like some aspects of it, so he decided to alter the rules a bit.In Polycarp's version, you play as Pac-Man and you have to collect pellets scattered over the game world while avoiding dangerous ghosts (no difference from the original yet). Polycarp didn't like the fact that there was no escape from the ghosts in the original, so, in his version, the game world is divided into n safe zones with m one-directional pathways between them — and it is guaranteed that Pac-Man can reach any safe zone from any other. Since safe zones are safe, the ghosts cannot attack Pac-Man while it is there, it is in danger only while traversing the pathways. Pac-Man starts the game in the safe zone s.All pellets are scattered over the safe zones; initially, the i-th safe zone contains a_i pellets (and if Pac-Man is in a safe zone, it may freely collect all the pellets in it). The pellets disappear after being collected, but after the last pellet in the game world is collected, new pellets spawn in the safe zones in the same quantity as before (a_i new pellets spawn in the i-th zone). The pellets can be respawned any number of times, so the game is essentially infinite.Polycarp has already determined the structure of the game world and the number of pellets in each safe zone. Now he is trying to find out if the game is difficult enough. There are q goals in the game, the i-th goal is to collect at least C_i pellets from the beginning of the game. Polycarp denotes the difficulty of the i-th goal as the minimum number of times the player has to traverse a one-directional pathway in order to collect C_i pellets (since only traversing a pathway puts Pac-Man in danger). If some pathway is traversed multiple times while Pac-Man is collecting the pellets, it is included in the answer the same number of times.Help Polycarp to calculate the difficulty of each goal!InputThe first line contains four integers n, m, q and s (2 \le n \le 15; n \le m \le n(n-1); 1 \le q \le 5000; 1 \le s \le n) — the number of safe zones, the number of pathways, the number of goals and the index of the starting safe zone, respectively.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9), where a_i is the initial number of pellets in the i-th safe zone (and the number of pellets that spawn in the i-th safe zone when the last pellet in the world is collected).Then m lines follow, each line contains two integers v_i and u_i (1 \le v_i, u_i \le n; v_i \ne u_i) denoting a one-directional pathway from the safe zone v_i to the safe zone u_i. Each ordered pair (v_i, u_i) appears in this section at most once (there are no multiple pathways from v_i to u_i), and it is possible to reach every safe zone from every other safe zone using these pathways.The last line contains q integers C_1, C_2, ..., C_q (1 \le C_i \le 10^{15}), where C_i is the minimum number of pellets the player has to collect in order to fulfil the i-th goal.OutputFor each goal i, print one integer — its difficulty (the minimum number of times the player has to traverse along some pathway in order to collect at least C_i pellets).ExamplesInput 3 4 2 1 3 1 2 1 2 2 1 1 3 3 1 5 8 Output 1 3 Input 5 7 4 2 1 3 2 2 1 2 3 4 2 3 4 3 1 1 4 5 4 4 5 7 14 23 27 Output 2 6 10 13 Input 4 4 3 3 2 3 1 4 3 4 4 1 1 2 2 3 13 42 1337 Output 3 13 401 NoteConsider the first test. In order to collect 5 pellets, the player should collect 3 pellets in the safe zone 1 (which is starting), move to zone 3, collect 2 pellets there.In order to collect 8 pellets, the player should collect 3 pellets in the safe zone 1, go to 2, collect 1 pellet, go to 1 without getting pellets, go to 3, collect 2 pellets. Now the last pellet in the world is collected, so they are respawned. The player can collect 2 pellets in the safe zone 3 and now the number of collected pellets is 8.Consider the second test.In order to collect 7 pellets let's do the following: 2(+3) \rightarrow 3(+2) \rightarrow 4(+2). In such a way 7 pellets were collected.In order to collect 14 pellets let's do the following: 2(+3) \rightarrow 3(+2) \rightarrow 1(+1) \rightarrow 4(+2) \rightarrow 5(+1) respawn of pellets 5(+1) \rightarrow 4 (+2) \rightarrow 2(+3). In such a way 15 pellets were collected.In order to collect 23 pellets let's do the following: 2(+3) \rightarrow 3(+2) \rightarrow 1(+1) \rightarrow 4(+2) \rightarrow 5(+1) respawn of pellets 5(+1) \rightarrow 4(+2) \rightarrow 2(+3) \rightarrow 3(+2) \rightarrow 1(+1) respawn of pellets 1(+1) \rightarrow 4(+2) \rightarrow 2(+3). In such a way 24 pellets were collected.
3 4 2 1 3 1 2 1 2 2 1 1 3 3 1 5 8
1 3
3 seconds
256 megabytes
['*special problem', 'dp', '*2900']
H. Game with Segmentstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game (yet again).They have two sequences of segments of the coordinate axis: a sequence of n initial segments: [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], and a sequence of m terminal segments: [L_1, R_1], [L_2, R_2], ..., [L_m, R_m]. At the beginning of the game, they choose one of the initial segments and set it as the current segment.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must shrink the current segment either by increasing its left endpoint by 1, or by decreasing its right endpoint by 1. So, if the current segment is [c_l, c_r], it becomes either [c_l + 1, c_r], or [c_l, c_r - 1].If at the beginning of the game or after Bob's move the current segment coincides with one of the terminal segments, Bob wins. If the current segment becomes degenerate (c_l = c_r), and Bob hasn't won yet, Alice wins. If the current segment coincides with one of the terminal segments after Alice's move, nothing happens — the game continues.Both players play optimally — if they can win, they always use a strategy that leads them to victory in the minimum number of turns, and if they cannot win, they try to prolong the game, using the strategy allowing them to make the maximum possible number of moves until their defeat.For each of the initial segments you have to determine who will win the game if this segment is chosen as the current segment at the beginning of the game. If Bob wins, you also have to calculate the number of moves Alice will make before her defeat.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of initial segments and terminal segments, respectively.Then n lines follow, the i-th line contains two integers l_i and r_i (1 \le l_i < r_i \le 10^6) — the endpoints of the i-th initial segment.Then m lines follow, the i-th line contains two integers L_i and R_i (1 \le L_i < R_i \le 10^6) — the endpoints of the i-th terminal segment.Note that some of the segments given in the input may coincide.OutputPrint n integers, the i-th of them should describe the result of the game if the i-th initial segment is chosen at the beginning of the game: if Alice wins, print -1; if Bob wins, print the number of moves Alice will make before she is defeated. ExamplesInput 1 1 4 7 4 7 Output 0 Input 1 2 2 5 2 4 3 5 Output -1 Input 2 1 1 5 1 4 2 3 Output -1 1
1 1 4 7 4 7
0
3 seconds
512 megabytes
['*special problem', 'data structures', 'games', '*2700']
G. Two IP Camerastime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have two IP cameras of the same model. Each camera can take photos starting from some moment of time with a fixed period. You can freely choose the starting moment but you can choose the period only as one of k values p_1, p_2, \dots, p_k which are chosen by the camera's manufacturer.You have n moments of interest x_1, x_2, \dots, x_n. You'd like to configure both cameras in such a way that at least one camera will take a photo in each of these moments. Configuring the camera means setting the moment when it takes the first photo and the gap between two consecutive photos (which should be one of the values p_1, p_2, \dots, p_k). It's not a problem for you that cameras can take photos at other moments of time — you only care about moments of interest.InputThe first line contains two integers k and n (1 \le k \le 10^5; 2 \le n \le 10^5) — the number of periods to choose and the number of moments of interest.The second line contains k integers p_1, p_2, \dots, p_k (1 \le p_1 < p_2 < \dots < p_k \le 10^6) — the periods to choose in the ascending order.The third line contains n integers x_1, x_2, \dots, x_n (1 \le x_1 < x_2 < \dots < x_n \le 10^6) — the moments of interest in the ascending order.OutputPrint YES (case insensitive) in the first line if there is a way to configure cameras.In the second line, print two integers s_1 and cp_1 (1 \le s_1 \le 10^6; 1 \le cp_1 \le 10^6; cp_1 \in \{p_1, \dots, p_k\}) — the starting moment and the period for the first camera. The period should be one of the given periods.In the third line, print two integers s_2 and cp_2 (1 \le s_2 \le 10^6; 1 \le cp_2 \le 10^6; cp_2 \in \{p_1, \dots, p_k\}) — the starting moment and the period for the second camera. The period should be one of the given periods.If there is no way to configure cameras, print NO (case insensitive). If there are multiple ways, you may print any of them.ExamplesInput 3 5 3 5 7 1 4 5 7 12 Output YES 1 3 5 7 Input 3 2 1 2 3 1 10 Output YES 1 1 10 1 Input 3 4 1 2 3 5 7 9 11 Output YES 5 1 5 1 Input 3 4 10 20 100 2 3 4 7 Output NO
3 5 3 5 7 1 4 5 7 12
YES 1 3 5 7
3 seconds
256 megabytes
['*special problem', 'math', 'number theory', '*2300']
F. Dune II: Battle For Arrakistime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're at the last mission in one very old and very popular strategy game Dune II: Battle For Arrakis. The map of the mission can be represented as a rectangular matrix of size n \times m. Initially, there are a_{i, j} units of your army in the cell (i, j).You want to prepare for the final battle, so you want to move all your army into exactly one cell of the map (i.e. nm-1 cells should contain 0 units of the army and the remaining cell should contain the entire army).To do this, you can do some (possibly, zero) number of moves. During one move, you can select exactly one unit from some cell and move it to one of the adjacent by side cells. I.e. from the cell (i, j) you can move the unit to cells: (i - 1, j); (i, j - 1); (i + 1, j); (i, j + 1). Of course, you want to move all your army into exactly one cell as fast as possible. So, you want to know the minimum number of moves you need to do that.And, of course, life goes on, so the situation on the map changes. There are q updates, the i-th update is denoted by three integers x, y, z. This update affects the army in the cell (x, y): after this update, the number of units in the cell (x, y) becomes z (i.e. you replace a_{x, y} with z).Also, you want to determine, for each i, the minimum number of moves needed to move your entire army into exactly one cell with the first i updates applied to the initial map. In other words, the map after the i-th update equals the initial map with the first i updates applied to it.InputThe first line of the input contains three integers n, m and q (1 \le n, m \le 1000; 1 \le q \le 5000) — the size of the matrix and the number of updates correspondingly.The next n lines contain m integers each, where the j-th integer in the i-th line is a_{i, j} (1 \le a_{i, j} \le 10^9) — the number of units in the cell (i, j).The next q lines contain three integers each, where the i-th line contains three integers x_i, y_i and z_i (1 \le x_i \le n; 1 \le y_i \le m; 1 \le z_i \le 10^9) — the cell in which the number of units updates and the new number of units in this cell correspondingly.OutputPrint q+1 integers r_0, r_1, r_2, \dots, r_n, where r_0 is the minimum number of moves you need to move all your army into exactly one cell, and r_i for all i from 1 to q is the minimum number of moves you need to move all your army into exactly one cell after the first i updates.ExamplesInput 3 3 1 1 2 3 2 1 2 1 1 2 2 3 100 Output 21 22 Input 4 4 3 2 5 6 3 4 8 10 5 2 6 7 1 8 4 2 1 1 1 8 2 3 4 4 4 5 Output 123 135 129 145
3 3 1 1 2 3 2 1 2 1 1 2 2 3 100
21 22
3 seconds
256 megabytes
['*special problem', 'data structures', 'greedy', 'math', '*2000']
E. Magic Trickstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha is going to participate in a talent show conducted by the university she studies at. She wants to impress the audience with lots of different magic tricks!For one of her tricks, she uses n sponge balls, one of which is a special one. First, she arranges the balls in a row in such a way that the special ball is put on position k (positions are numbered from 1 to n from left to right). After that, she performs m swaps: during the i-th swap, she chooses the ball on position x_i and the ball on position y_i, and swaps them.Since Masha is a magician, she fakes some of her actions to trick the audience — when she starts performing a swap, she may fake it, so it is not performed (but it looks like it is performed for the audience). There are no constraints on which swaps Masha should fake or should actually perform — for example, she may fake all of the swaps, or even not fake anything at all.For the trick to work perfectly, the special ball should end up on a specific position — Masha has not decided yet, which position is perfect. Since faking swaps is difficult, for each position she wants to know the minimum number of swaps she has to fake so that the special ball ends up there. Unfortunately, Masha is a magician, neither a mathematician nor a programmer. So she needs your help in calculating what she wants!InputThe first line contains three integers n, m and k (2 \le n \le 2 \cdot 10^5; 1 \le m \le 2 \cdot 10^5; 1 \le k \le n) — the number of balls, the number of swaps and the initial position of the special ball, respectively.Then m lines follow, the i-th line contains two integers x_i and y_i (1 \le x_i, y_i \le n; x_i \ne y_i) denoting the i-th swap.OutputPrint n integers. The i-th integer should be the minimum number of swaps Masha has to fake so the special ball ends up on position i (or -1, if Masha cannot put the special ball there).ExamplesInput 4 5 1 3 4 2 1 4 1 3 1 3 1 Output 2 0 3 1 Input 5 7 4 3 2 3 2 4 2 3 4 4 1 3 2 5 2 Output 2 2 0 3 1 Input 7 15 5 5 3 4 2 6 1 2 4 1 6 3 7 5 6 4 2 6 4 2 6 6 3 6 3 7 6 2 6 7 2 Output -1 1 1 1 2 1 0
4 5 1 3 4 2 1 4 1 3 1 3 1
2 0 3 1
2 seconds
256 megabytes
['*special problem', 'dp', 'graphs', '*1700']
D. Constructing the Dungeontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is developing an RPG game where the main character fights monsters and searches for treasure in dungeons. Now Polycarp is making one of the dungeons the character can explore.The dungeon consists of n rooms connected by m two-way tunnels, and it is possible to reach every room from every other room using tunnels. The rooms are guarded by monsters (the number of monsters in the i-th room is a_i), and the tunnels contain gold coins (the number of coins in the i-th tunnel is w_i). The i-th two-way tunnel connects rooms v_i and u_i.Polycarp has already fixed the number of coins in each tunnel (the values of w_i are already known), and now he tries to place the monsters in the rooms (the values of a_i are not known yet). Polycarp wants to choose the number of monsters in each room in such a way that the following two conditions are met: the number of coins for the tunnel connecting the rooms x and y should be equal to the minimum of a_x and a_y. That is, for each tunnel i, w_i = \min (a_{v_i}, a_{u_i}); the number of monsters in the dungeon is as small as possible. That is, the value of a_1 + a_2 + \dots + a_n is minimum possible. Help Polycarp to choose the values a_1, a_2, ..., a_n, or tell him that it is impossible and he has to change something in his dungeon plan.InputThe first line contains one integer t (1 \le t \le 100000) — the number of test cases. Then the test cases follow.The first line of each test case contains two integers n and m (2 \le n \le 200000; n - 1 \le m \le \min(200000, \frac{n(n-1)}{2})) — the number of rooms and tunnels in the dungeon, respectively.Then m lines follow, each line describing one of the tunnels in the dungeon. The i-th line contains three integers v_i, u_i and w_i (1 \le v_i, u_i \le n; v_i \ne u_i; 1 \le w_i \le 10^9) denoting a two-way tunnel that connects rooms v_i and u_i, and contains w_i coins. The tunnel system is connected in each test case (it is possible to reach every room from every other room using the tunnels). Each pair of rooms is connected by at most one tunnel.The sum of n over all test cases does not exceed 200000. Similarly, the sum of m over all test cases does not exceed 200000.OutputFor each test case, print the answer as follows:If it is impossible to find the values of a_1, a_2, ..., a_n satisfying all the constraints, print one single string NO on a separate line. Otherwise, print YES in the first line, and n integers a_1, a_2, ..., a_n in the second line. If there are multiple valid answers, print any of them.ExampleInput 3 3 2 1 2 1 2 3 1 5 7 3 2 7 3 4 9 1 5 5 1 2 5 4 1 5 4 2 7 3 1 5 4 4 1 2 5 3 2 2 4 1 3 3 4 4 Output YES 1 1 1 YES 5 7 9 9 5 NO
3 3 2 1 2 1 2 3 1 5 7 3 2 7 3 4 9 1 5 5 1 2 5 4 1 5 4 2 7 3 1 5 4 4 1 2 5 3 2 2 4 1 3 3 4 4
YES 1 1 1 YES 5 7 9 9 5 NO
2 seconds
256 megabytes
['*special problem', 'graphs', 'greedy', '*1600']
C. Spring Cleaningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to organize her bookcase. There are n bookshelves in the bookcase, the i-th bookshelf contains a_i books on it. Tanya will be satisfied if each bookshelf contains no more than k books.Tanya can do one of the two following operations to achieve her goal: Choose exactly one bookshelf and put all the books from it in the storage room (i. e. choose some i and assign a_i := 0). During this operation she spends x seconds. Take all books from all n bookshelves and distribute them between all n bookshelves evenly (the definition of the term is given below). During this operation she spends y seconds. Consider the sequence a of n integers. Then its even distribution is such a sequence b of n integers that the sum of b equals the sum of a and the value max(b) - min(b) is the minimum possible.For example, if the array a=[5, 4, 3] then its even distribution is b=[4, 4, 4]. If a=[1, 2, 3, 4] then its even distribution is b=[2, 3, 3, 2] (or any permutation of this array).Your task is to find the minimum number of seconds Tanya has to spend to obtain the bookcase with no more than k books on each bookshelf.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains four integers n, k, x and y (1 \le k \le n \le 2 \cdot 10^5; 1 \le x, y \le 10^4) — the number of bookshelves, the maximum required number of books on each bookshelf and the number of seconds Tanya spends during the first and the second operation respectively.The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n), where a_i is the number of books on the i-th bookshelf.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the minimum number of seconds Tanya has to spend to obtain the bookcase with no more than k books on each bookshelf.ExampleInput 6 5 4 3 5 1 2 2 3 5 5 3 4 5 1 5 1 5 5 5 4 5 6 1 2 5 3 5 4 3 2 10 4 4 1 1 4 3 10 2 4 4 1 1 4 1 5 4 1 2 1 3 Output 3 9 6 4 2 9 NoteIn the first test case of the example, it's optimal to use the first operation on the fifth bookshelf. So the array a becomes [1, 2, 2, 3, 5] \rightarrow [1, 2, 2, 3, 0].In the second test case of the example, it's optimal to use the first operation on the second bookshelf and then use the second operation. So the array a becomes [1, 5, 1, 5, 5] \rightarrow [1, 0, 1, 5, 5] \rightarrow [2, 2, 3, 3, 2].In the third test case of the example, it's optimal to use the second operation. So the array a becomes [1, 2, 5, 3, 5] \rightarrow [4, 3, 3, 3, 3].In the fourth test case of the example, it's optimal to use the first operation on the first and the second bookshelves. So the array a becomes [4, 4, 1, 1] \rightarrow [0, 0, 1, 1].In the fifth test case of the example, it's optimal to use the second operation. So the array a becomes [4, 4, 1, 1] \rightarrow [2, 3, 2, 3].
6 5 4 3 5 1 2 2 3 5 5 3 4 5 1 5 1 5 5 5 4 5 6 1 2 5 3 5 4 3 2 10 4 4 1 1 4 3 10 2 4 4 1 1 4 1 5 4 1 2 1 3
3 9 6 4 2 9
2 seconds
256 megabytes
['*special problem', 'greedy', 'sortings', '*1600']
B. Boot Camptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland State University (BSU) is conducting a programming boot camp. The boot camp will last for n days, and the BSU lecturers are planning to give some number of lectures during these days.Some days of the boot camp are already planned as excursion days, and no lectures should be held during these days. To make sure the participants don't get too tired of learning to program, the number of lectures for each day should not exceed k_1, and the number of lectures for each pair of consecutive days should not exceed k_2.Can you calculate the maximum number of lectures that can be conducted during the boot camp? Formally, find the maximum integer m such that it is possible to choose n non-negative integers c_1, c_2, ..., c_n (where c_i is the number of lectures held during day i) so that: c_1 + c_2 + \dots + c_n = m; for each excursion day d, c_d = 0; for each day i, c_i \le k_1; for each pair of consecutive days (i, i + 1), c_i + c_{i + 1} \le k_2. Note that there might be some non-excursion days without lectures (i. e., it is possible that c_i = 0 even if i is not an excursion day).InputThe first line contains one integer t (1 \le t \le 50) — the number of testcases.Then the testcases follow, each consists of two lines. The first line contains three integers n, k_1, k_2 (1 \le n \le 5000; 1 \le k_1 \le k_2 \le 200\,000).The second line contains one string s consisting of exactly n characters, each character is either 0 or 1. If s_i = 0, then day i is an excursion day (so there should be no lectures during that day); if s_i = 1, then day i is not an excursion day.OutputFor each test case, print one integer — the maximum possible value of m (the number of lectures that can be conducted).ExampleInput 4 4 5 7 1011 4 4 10 0101 5 3 4 11011 6 4 6 011101 Output 12 8 8 14
4 4 5 7 1011 4 4 10 0101 5 3 4 11011 6 4 6 011101
12 8 8 14
2 seconds
256 megabytes
['*special problem', 'greedy', '*1400']
A. Color Revolutiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHmm, how long has it been since the last color revolution? 5 years?! It's totally the time to make a new one!So the general idea is the following. Division 1 should have n_1 participants. Division 2 should have n_2 and be exactly k times bigger than division 1 (n_2 = k \cdot n_1). Division 3 should have n_3 = k \cdot n_2 participants. Finally, division 4 should have n_4 = k \cdot n_3 participants.There are n participants on Codeforces in total. So n_1 + n_2 + n_3 + n_4 should be exactly equal to n.You know the values of n and k. You also know that n and k are chosen in such a way that there exist values n_1, n_2, n_3 and n_4 such that all the conditions are satisfied.What will be the number of participants in each division (n_1, n_2, n_3 and n_4) after the revolution?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Each of the next t lines contains two integers n and k (4 \le n \le 10^9; 1 \le k \le 500) — the total number of participants on Codeforces and the size multiplier for the corresponding testcase. In each testcase, n and k are chosen in such a way that the answer exists.OutputFor each testcase print four integers n_1, n_2, n_3 and n_4 such that n_2 = k \cdot n_1, n_3 = k \cdot n_2, n_4 = k \cdot n_3 and n_1 + n_2 + n_3 + n_4 = n.ExampleInput 4 40 3 1200 7 320802005 400 4 1 Output 1 3 9 27 3 21 147 1029 5 2000 800000 320000000 1 1 1 1
4 40 3 1200 7 320802005 400 4 1
1 3 9 27 3 21 147 1029 5 2000 800000 320000000 1 1 1 1
1 second
256 megabytes
['*special problem', 'math', '*1000']
B. Card Constructionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows: You start with n cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?InputEach test consists of multiple test cases. The first line contains a single integer t (1\le t\le 1000) — the number of test cases. Next t lines contain descriptions of test cases.Each test case contains a single integer n (1\le n\le 10^9) — the number of cards.It is guaranteed that the sum of n over all test cases does not exceed 10^9.OutputFor each test case output a single integer — the number of pyramids you will have constructed in the end.ExampleInput 5 3 14 15 24 1 Output 1 2 1 3 0 NoteIn the first test, you construct a pyramid of height 1 with 2 cards. There is 1 card remaining, which is not enough to build a pyramid.In the second test, you build two pyramids, each of height 2, with no cards remaining.In the third test, you build one pyramid of height 3, with no cards remaining.In the fourth test, you build one pyramid of height 3 with 9 cards remaining. Then you build a pyramid of height 2 with 2 cards remaining. Then you build a final pyramid of height 1 with no cards remaining.In the fifth test, one card is not enough to build any pyramids.
5 3 14 15 24 1
1 2 1 3 0
1 second
256 megabytes
['binary search', 'brute force', 'dp', 'math', '*1100']
A. Puzzle Piecestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a special jigsaw puzzle consisting of n\cdot m identical pieces. Every piece has three tabs and one blank, as pictured below. The jigsaw puzzle is considered solved if the following conditions hold: The pieces are arranged into a grid with n rows and m columns. For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece. Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.InputThe test consists of multiple test cases. The first line contains a single integer t (1\le t\le 1000) — the number of test cases. Next t lines contain descriptions of test cases.Each test case contains two integers n and m (1 \le n,m \le 10^5).OutputFor each test case output a single line containing "YES" if it is possible to solve the jigsaw puzzle, or "NO" otherwise. You can print each letter in any case (upper or lower).ExampleInput 3 1 3 100000 100000 2 2 Output YES NO YES NoteFor the first test case, this is an example solution: For the second test case, we can show that no solution exists.For the third test case, this is an example solution:
3 1 3 100000 100000 2 2
YES NO YES
1 second
256 megabytes
['math', '*800']
F. Piet's Palettetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPiet Mondrian is an artist most famous for his minimalist works, consisting only of the four colors red, yellow, blue, and white. Most people attribute this to his style, but the truth is that his paint behaves in a very strange way where mixing two primary colors only produces another primary color! A lesser known piece, entitled "Pretentious rectangles" A sequence of primary colors (red, yellow, blue) is mixed as follows. While there are at least two colors, look at the first two. If they are distinct, replace them with the missing color. If they are the same, remove them from the sequence. In the end, if there is one color, that is the resulting color. Otherwise, if the sequence is empty, we say the resulting color is white. Here are two example mixings:   Piet has a color palette with cells numbered from 1 to n. Each cell contains a primary color or is empty. Piet is very secretive, and will not share his palette with you, so you do not know what colors belong to each cell.However, he did perform k operations. There are four kinds of operations: In a mix operation, Piet chooses a subset of cells and mixes their colors together in some order. The order is not necessarily by increasing indexes. He records the resulting color. Empty cells are skipped over, having no effect on the mixing process. The mixing does not change the color values stored in the cells. In a RY operation, Piet chooses a subset of cells. Any red cells in this subset become yellow, and any yellow cells in this subset become red. Blue and empty cells remain unchanged. In a RB operation, Piet chooses a subset of cells. Any red cells in this subset become blue, and any blue cells in this subset become red. Yellow and empty cells remain unchanged. In a YB operation, Piet chooses a subset of cells. Any yellow cells in this subset become blue, and any blue cells in this subset become yellow. Red and empty cells remain unchanged. Piet only tells you the list of operations he performs in chronological order, the indexes involved, and the resulting color of each mix operation. For each mix operation, you also know the order in which the cells are mixed. Given this information, determine the color of each cell in the initial palette. That is, you should find one possible state of the palette (before any operations were performed), or say that the described situation is impossible.InputThe first line contains two integers n and k (1\le n,k\le 1000) — the number of cells in the palette and the number of operations, respectively.The next k lines describe the operations. The i-th line begins with the name of the i-th operation and an integer m (1\le m\le n) — the number of indexes involved. Then follow m integers j_1,\ldots,j_m (1\le j_i\le n) — the indexes of the operation. It is guaranteed that all j_i are distinct within an operation. If it is a mix operation, the indexes are listed in the order the colors are mixed, and the line also ends with a character representing the resulting color: "R" for red, "Y" for yellow, "B" for blue, and "W" for white.OutputOutput "YES" if a solution exists, or "NO" otherwise. You can print each character in any case (upper or lower).If the answer is "YES", on the next line output a string of length n, consisting of characters "R", "Y", "B", and ".", representing the paint colors in the n cells of the initial palette (red, yellow, blue, and empty, respectively). If there are multiple solutions, print any. You can print each character in any case (upper or lower).ExamplesInput 3 2 mix 2 2 1 R mix 2 1 3 Y Output YES YB. Input 2 3 mix 1 2 Y RB 1 2 mix 1 2 W Output NO Input 1 3 RY 1 1 YB 1 1 mix 1 1 B Output YES R Input 3 8 mix 2 1 2 R mix 2 1 3 Y RY 2 2 3 RB 3 1 2 3 YB 3 1 2 3 mix 1 1 W mix 1 2 B mix 1 3 Y Output YES .RY NoteFor the first test case, the answer "YB." is consistent with both mixings. The first mixing "BY" results in red, while the second mixing "Y" results in yellow (the empty cell is ignored). Other valid solutions include "BYR" and ".RY".For the second test case, we can show that no solution exists.For the third test case, the answer "R" is consistent with all operations. In the first two operations it changes to "Y", then "B". In the final operation, the mixing "B" results in blue.For the fourth test case, the answer ".RY" is consistent with all operations. The first two mixings are "R" and "Y", resulting in red and yellow, respectively. During the next three operations, the palette changes to ".YR", then ".YB", then ".BY". The final three mixings agree with this palette.
3 2 mix 2 2 1 R mix 2 1 3 Y
YES YB.
2 seconds
256 megabytes
['matrices', '*3200']
E. Train Trackstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThat's right. I'm a Purdue student, and I shamelessly wrote a problem about trains.There are n stations and m trains. The stations are connected by n-1 one-directional railroads that form a tree rooted at station 1. All railroads are pointed in the direction from the root station 1 to the leaves. A railroad connects a station u to a station v, and has a distance d, meaning it takes d time to travel from u to v. Each station with at least one outgoing railroad has a switch that determines the child station an incoming train will be directed toward. For example, it might look like this: Here, stations 1 and 3 have switches directed toward stations 2 and 4, respectively. Initially, no trains are at any station. Train i will enter station 1 at time t_i. Every unit of time, starting at time 1, the following two steps happen: You can switch at most one station to point to a different child station. A switch change takes effect before step 2. For every train that is on a station u, it is directed toward the station v indicated by u's switch. So, if the railroad from u to v has distance d, the train will enter station v in d units of time from now. Every train has a destination station s_i. When it enters s_i, it will stop there permanently. If at some point the train is going in the wrong direction, so that it will never be able to reach s_i no matter where the switches point, it will immediately explode.Find the latest possible time of the first explosion if you change switches optimally, or determine that you can direct every train to its destination so that no explosion occurs. Also, find the minimum number of times you need to change a switch to achieve this.InputThe first line contains two integers n and m (1\le n,m\le 10^5) — the number of stations and trains, respectively.The next n-1 lines describe the railroads. The i-th line contains three integers u,v,d (1\le u,v\le n, 1\le d\le 10^9), denoting a railroad from station u to station v with distance d. It is guaranteed that the railroads form a tree rooted at station 1. The switch of a station u is initially directed towards the last outgoing railroad from u that appears in the input.The next m lines describe the trains. The i-th line contains two integers s_i,t_i (1\le s_i\le n, 1\le t_1<t_2<\cdots<t_m\le 10^9) — the destination station and the time the i-th train enters station 1, respectively.OutputOutput two integers: the latest possible time of the first explosion (or -1 if it is possible to never have an explosion) and the minimum number of switch changes to achieve it.ExamplesInput 5 4 1 2 1 1 3 2 3 4 1 3 5 3 2 1 4 2 2 6 5 10 Output -1 6 Input 5 4 1 2 1 1 3 2 3 4 1 3 5 3 5 1 4 2 4 3 2 4 Output 4 0 Input 11 6 1 2 1 1 3 2 3 4 1 3 5 2 5 6 1 5 7 2 7 8 1 7 9 2 9 10 1 9 11 1 2 1 8 3 6 5 10 7 4 9 2 11 Output 11 4 NoteFor the first test, here's an example timeline: At time 1, train 1 enters station 1. We switch station 1 to point to station 2. Train 1 is directed to station 2. At time 2, train 2 enters station 1, and train 1 enters station 2, where it stops permanently. We switch station 1 to point to station 3. Train 2 is directed to station 3. At time 4, train 2 enters station 3. We switch station 3 to point to station 4. Train 2 is directed to station 4. At time 5, train 2 enters station 4, where it stops permanently. At time 6, train 3 enters station 1. We switch station 1 to point to station 2. Train 3 is directed to station 2. At time 7, train 3 enters station 2, where it stops permanently. We switch station 3 to point to station 5. At time 10, train 4 enters station 1. We switch station 1 to point to station 3. Train 4 is directed to station 3. At time 12, train 4 enters station 3. Train 4 is directed to station 5. At time 15, train 4 enters station 5, where it stops permanently. For the second test, we switch nothing. At time 4, train 2 is directed to station 5 and train 4 is directed to station 3. They both explode. It is impossible to prevent an explosion by time 4.For the third test, denote a switch change by (u\to v,t) if we make station u point to station v at time t. One solution is to make these 4 switch changes: (1\to 2,1),(1\to 3,2),(7\to 8,5),(5\to 6,8). At time 11, trains 4,5, and 6 explode. It is impossible to prevent an explosion by time 11.
5 4 1 2 1 1 3 2 3 4 1 3 5 3 2 1 4 2 2 6 5 10
-1 6
5 seconds
256 megabytes
['data structures', 'trees', '*3100']
D. Résumé Reviewtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0\le b_i \le a_i for all i.Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require \sum\limits_{i=1}^n b_i=k.Find values for b_1,\ldots, b_n that maximize the value of f(b_1,\ldots,b_n) while satisfying the above two constraints.InputThe first line contains two integers n and k (1\le n\le 10^5, 1\le k\le \sum\limits_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively.The next line contains n integers a_1,\ldots,a_n (1\le a_i\le 10^9) — a_i is equal to the number of completed projects of type i.OutputIn a single line, output n integers b_1,\ldots, b_n that achieve the maximum value of f(b_1,\ldots,b_n), while satisfying the requirements 0\le b_i\le a_i and \sum\limits_{i=1}^n b_i=k. If there are multiple solutions, output any.Note that you do not have to output the value f(b_1,\ldots,b_n).ExamplesInput 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 NoteFor the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint \sum\limits_{i=1}^n b_i=k.For the second test, the optimal answer is f=9.
10 32 1 2 3 4 5 5 5 5 5 5
1 2 3 3 3 4 4 4 4 4
4 seconds
256 megabytes
['binary search', 'greedy', 'math', '*2700']
C. Quantifier Questiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLogical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal (\forall) and existential (\exists). You can read more about them here.The universal quantifier is used to make a claim that a statement holds for all real numbers. For example: \forall x,x<100 is read as: for all real numbers x, x is less than 100. This statement is false. \forall x,x>x-1 is read as: for all real numbers x, x is greater than x-1. This statement is true. The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example: \exists x,x<100 is read as: there exists a real number x such that x is less than 100. This statement is true. \exists x,x>x-1 is read as: there exists a real number x such that x is greater than x-1. This statement is true. Moreover, these quantifiers can be nested. For example: \forall x,\exists y,x<y is read as: for all real numbers x, there exists a real number y such that x is less than y. This statement is true since for every x, there exists y=x+1. \exists y,\forall x,x<y is read as: there exists a real number y such that for all real numbers x, x is less than y. This statement is false because it claims that there is a maximum real number: a number y larger than every x. Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.There are n variables x_1,x_2,\ldots,x_n, and you are given some formula of the form f(x_1,\dots,x_n):=(x_{j_1}<x_{k_1})\land (x_{j_2}<x_{k_2})\land \cdots\land (x_{j_m}<x_{k_m}), where \land denotes logical AND. That is, f(x_1,\ldots, x_n) is true if every inequality x_{j_i}<x_{k_i} holds. Otherwise, if at least one inequality does not hold, then f(x_1,\ldots,x_n) is false.Your task is to assign quantifiers Q_1,\ldots,Q_n to either universal (\forall) or existential (\exists) so that the statement Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) is true, and the number of universal quantifiers is maximized, or determine that the statement is false for every possible assignment of quantifiers.Note that the order the variables appear in the statement is fixed. For example, if f(x_1,x_2):=(x_1<x_2) then you are not allowed to make x_2 appear first and use the statement \forall x_2,\exists x_1, x_1<x_2. If you assign Q_1=\exists and Q_2=\forall, it will only be interpreted as \exists x_1,\forall x_2,x_1<x_2.InputThe first line contains two integers n and m (2\le n\le 2\cdot 10^5; 1\le m\le 2\cdot 10^5) — the number of variables and the number of inequalities in the formula, respectively.The next m lines describe the formula. The i-th of these lines contains two integers j_i,k_i (1\le j_i,k_i\le n, j_i\ne k_i).OutputIf there is no assignment of quantifiers for which the statement is true, output a single integer -1.Otherwise, on the first line output an integer, the maximum possible number of universal quantifiers.On the next line, output a string of length n, where the i-th character is "A" if Q_i should be a universal quantifier (\forall), or "E" if Q_i should be an existential quantifier (\exists). All letters should be upper-case. If there are multiple solutions where the number of universal quantifiers is maximum, print any.ExamplesInput 2 1 1 2 Output 1 AE Input 4 3 1 2 2 3 3 1 Output -1 Input 3 2 1 3 2 3 Output 2 AAE NoteFor the first test, the statement \forall x_1, \exists x_2, x_1<x_2 is true. Answers of "EA" and "AA" give false statements. The answer "EE" gives a true statement, but the number of universal quantifiers in this string is less than in our answer.For the second test, we can show that no assignment of quantifiers, for which the statement is true exists.For the third test, the statement \forall x_1, \forall x_2, \exists x_3, (x_1<x_3)\land (x_2<x_3) is true: We can set x_3=\max\{x_1,x_2\}+1.
2 1 1 2
1 AE
1 second
256 megabytes
['dfs and similar', 'dp', 'graphs', 'math', '*2600']
B. Monopole Magnetstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.There is an n\times m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met. There is at least one south magnet in every row and every column. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement. Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).InputThe first line contains two integers n and m (1\le n,m\le 1000)  — the number of rows and the number of columns, respectively.The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.OutputOutput a single integer, the minimum possible number of north magnets required.If there is no placement of magnets that satisfies all conditions, print a single integer -1.ExamplesInput 3 3 .#. ### ##. Output 1 Input 4 2 ## .# .# ## Output -1 Input 4 5 ....# ####. .###. .#... Output 2 Input 2 1 . # Output -1 Input 3 5 ..... ..... ..... Output 0 NoteIn the first test, here is an example placement of magnets: In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column. In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets. In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square. In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
3 3 .#. ### ##.
1
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', '*2000']
A. Hilbert's Hoteltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).For any integer k and positive integer n, let k\bmod n denote the remainder when k is divided by n. More formally, r=k\bmod n is the smallest non-negative integer such that k-r is divisible by n. It always holds that 0\le k\bmod n\le n-1. For example, 100\bmod 12=4 and (-1337)\bmod 3=1.Then the shuffling works as follows. There is an array of n integers a_0,a_1,\ldots,a_{n-1}. Then for each integer k, the guest in room k is moved to room number k+a_{k\bmod n}.After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.InputEach test consists of multiple test cases. The first line contains a single integer t (1\le t\le 10^4) — the number of test cases. Next 2t lines contain descriptions of test cases.The first line of each test case contains a single integer n (1\le n\le 2\cdot 10^5) — the length of the array.The second line of each test case contains n integers a_0,a_1,\ldots,a_{n-1} (-10^9\le a_i\le 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, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower).ExampleInput 6 1 14 2 1 -1 4 5 5 5 1 3 3 2 1 2 0 1 5 -239 -2 -100 -3 -11 Output YES YES YES NO NO YES NoteIn the first test case, every guest is shifted by 14 rooms, so the assignment is still unique.In the second test case, even guests move to the right by 1 room, and odd guests move to the left by 1 room. We can show that the assignment is still unique.In the third test case, every fourth guest moves to the right by 1 room, and the other guests move to the right by 5 rooms. We can show that the assignment is still unique.In the fourth test case, guests 0 and 1 are both assigned to room 3.In the fifth test case, guests 1 and 2 are both assigned to room 2.
6 1 14 2 1 -1 4 5 5 5 1 3 3 2 1 2 0 1 5 -239 -2 -100 -3 -11
YES YES YES NO NO YES
1 second
256 megabytes
['math', 'number theory', 'sortings', '*1600']
F. Restore the Permutation by Sorted Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you.For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, \dots, p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order.For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: [2, 5, 6] [4, 6] [1, 3, 4] [1, 3] [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists).You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (2 \le n \le 200) — the length of the permutation.The next n-1 lines describe given segments.The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 \le k_i \le n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive.It is guaranteed that the required p exists for each test case.It is also guaranteed that the sum of n over all test cases does not exceed 200 (\sum n \le 200).OutputFor each test case, print the answer: n integers p_1, p_2, \dots, p_n (1 \le p_i \le n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input).ExampleInput 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1
5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5
3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'data structures', 'greedy', 'implementation', '*2400']
E. Weights Distributingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains five integers n, m, a, b and c (2 \le n \le 2 \cdot 10^5, n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5), 1 \le a, b, c \le n) — the number of vertices, the number of edges and districts in Mike's trip.The second line of the test case contains m integers p_1, p_2, \dots, p_m (1 \le p_i \le 10^9), where p_i is the i-th price from the array.The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 \le v_i, u_i \le n, u_i \ne v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i \ne u_i is satisfied. It is guaranteed that the given graph is connected.It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5, \sum m \le 2 \cdot 10^5).OutputFor each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.ExampleInput 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7
7 12
2 seconds
256 megabytes
['brute force', 'graphs', 'greedy', 'shortest paths', 'sortings', '*2100']
D. Constant Palindrome Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers (it is guaranteed that n is even, i.e. divisible by 2). All a_i does not exceed some integer k.Your task is to replace the minimum number of elements (replacement is the following operation: choose some index i from 1 to n and replace a_i with some integer in range [1; k]) to satisfy the following conditions: after all replacements, all a_i are positive integers not greater than k; for all i from 1 to \frac{n}{2} the following equation is true: a_i + a_{n - i + 1} = x, where x should be the same for all \frac{n}{2} pairs of elements. You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and k (2 \le n \le 2 \cdot 10^5, 1 \le k \le 2 \cdot 10^5) — the length of a and the maximum possible value of some a_i correspondingly. It is guratanteed that n is even (i.e. divisible by 2). The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le k), where a_i is the i-th element of a.It is guaranteed that the sum of n (as well as the sum of k) over all test cases does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5, \sum k \le 2 \cdot 10^5).OutputFor each test case, print the answer — the minimum number of elements you have to replace in a to satisfy the conditions from the problem statement.ExampleInput 4 4 2 1 2 1 2 4 3 1 2 2 1 8 7 6 1 1 7 6 3 4 6 6 6 5 2 6 1 3 4 Output 0 1 4 2
4 4 2 1 2 1 2 4 3 1 2 2 1 8 7 6 1 1 7 6 3 4 6 6 6 5 2 6 1 3 4
0 1 4 2
1 second
256 megabytes
['brute force', 'data structures', 'greedy', 'two pointers', '*1700']
C. Alternating Subsequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9, a_i \ne 0), where a_i is the i-th element of a.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.ExampleInput 4 5 1 2 3 -1 -2 4 -1 -2 -1 -3 10 -2 8 3 8 -4 -15 5 -2 -3 1 6 1 -1000000000 1 -1000000000 1 -1000000000 Output 2 -1 6 -2999999997 NoteIn the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
4 5 1 2 3 -1 -2 4 -1 -2 -1 -3 10 -2 8 3 8 -4 -15 5 -2 -3 1 6 1 -1000000000 1 -1000000000 1 -1000000000
2 -1 6 -2999999997
1 second
256 megabytes
['dp', 'greedy', 'two pointers', '*1200']
B. Balanced Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).You want to construct the array a of length n such that: The first \frac{n}{2} elements of a are even (divisible by 2); the second \frac{n}{2} elements of a are odd (not divisible by 2); all elements of a are distinct and positive; the sum of the first half equals to the sum of the second half (\sum\limits_{i=1}^{\frac{n}{2}} a_i = \sum\limits_{i=\frac{n}{2} + 1}^{n} a_i). If there are multiple answers, you can print any. It is not guaranteed that the answer exists.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains one integer n (2 \le n \le 2 \cdot 10^5) — the length of the array. It is guaranteed that that n is even (i.e. divisible by 2).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — "NO" (without quotes), if there is no suitable answer for the given test case or "YES" in the first line and any suitable array a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) satisfying conditions from the problem statement on the second line.ExampleInput 5 2 4 6 8 10 Output NO YES 2 4 1 5 NO YES 2 4 6 8 1 3 5 11 NO
5 2 4 6 8 10
NO YES 2 4 1 5 NO YES 2 4 6 8 1 3 5 11 NO
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
A. Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, \dots, 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k > 1.Vova will be satisfied if you tell him any positive integer x so there is an integer k>1 that x + 2x + 4x + \dots + 2^{k-1} x = n. It is guaranteed that at least one solution exists. Note that k > 1.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains one integer n (3 \le n \le 10^9) — the number of candy wrappers Vova found. It is guaranteed that there is some positive integer x and integer k>1 that x + 2x + 4x + \dots + 2^{k-1} x = n.OutputPrint one integer — any positive integer value of x so there is an integer k>1 that x + 2x + 4x + \dots + 2^{k-1} x = n.ExampleInput 7 3 6 7 21 28 999999999 999999984 Output 1 2 1 7 4 333333333 333333328 NoteIn the first test case of the example, one of the possible answers is x=1, k=2. Then 1 \cdot 1 + 2 \cdot 1 equals n=3.In the second test case of the example, one of the possible answers is x=2, k=2. Then 1 \cdot 2 + 2 \cdot 2 equals n=6.In the third test case of the example, one of the possible answers is x=1, k=3. Then 1 \cdot 1 + 2 \cdot 1 + 4 \cdot 1 equals n=7.In the fourth test case of the example, one of the possible answers is x=7, k=2. Then 1 \cdot 7 + 2 \cdot 7 equals n=21.In the fifth test case of the example, one of the possible answers is x=4, k=3. Then 1 \cdot 4 + 2 \cdot 4 + 4 \cdot 4 equals n=28.
7 3 6 7 21 28 999999999 999999984
1 2 1 7 4 333333333 333333328
1 second
256 megabytes
['brute force', 'math', '*900']
F. Make It Ascendingtime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n elements. You may apply several operations (possibly zero) to it.During each operation, you choose two indices i and j (1 \le i, j \le n; i \ne j), increase a_j by a_i, and remove the i-th element from the array (so the indices of all elements to the right to it decrease by 1, and n also decreases by 1).Your goal is to make the array a strictly ascending. That is, the condition a_1 < a_2 < \dots < a_n should hold (where n is the resulting size of the array).Calculate the minimum number of actions required to make the array strictly ascending.InputThe first line contains one integer T (1 \le T \le 10000) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (1 \le n \le 15) — the number of elements in the initial array a.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^6).It is guaranteed that: the number of test cases having n \ge 5 is not greater than 5000; the number of test cases having n \ge 8 is not greater than 500; the number of test cases having n \ge 10 is not greater than 100; the number of test cases having n \ge 11 is not greater than 50; the number of test cases having n \ge 12 is not greater than 25; the number of test cases having n \ge 13 is not greater than 10; the number of test cases having n \ge 14 is not greater than 3; the number of test cases having n \ge 15 is not greater than 1. OutputFor each test case, print the answer as follows:In the first line, print k — the minimum number of operations you have to perform. Then print k lines, each containing two indices i and j for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them.ExampleInput 4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Output 3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0 NoteIn the first test case, the sequence of operations changes a as follows:[2, 1, 3, 5, 1, 2, 4, 5] \rightarrow [2, 1, 3, 5, 1, 4, 7] \rightarrow [1, 3, 5, 1, 6, 7] \rightarrow [2, 3, 5, 6, 7].
4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14
3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0
7 seconds
512 megabytes
['bitmasks', 'brute force', 'dp', '*3000']
E. Placing Rookstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCalculate the number of ways to place n rooks on n \times n chessboard so that both following conditions are met: each empty cell is under attack; exactly k pairs of rooks attack each other. An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two rooks attack each other if they share the same row or column, and there are no other rooks between them. For example, there are only two pairs of rooks that attack each other in the following picture: One of the ways to place the rooks for n = 3 and k = 2 Two ways to place the rooks are considered different if there exists at least one cell which is empty in one of the ways but contains a rook in another way.The answer might be large, so print it modulo 998244353.InputThe only line of the input contains two integers n and k (1 \le n \le 200000; 0 \le k \le \frac{n(n - 1)}{2}).OutputPrint one integer — the number of ways to place the rooks, taken modulo 998244353.ExamplesInput 3 2 Output 6 Input 3 3 Output 0 Input 4 0 Output 24 Input 1337 42 Output 807905441
3 2
6
2 seconds
512 megabytes
['combinatorics', 'fft', 'math', '*2300']
D. Multiple Testcasestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSo you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem!Initially, each test in that problem is just an array. The maximum size of an array is k. For simplicity, the contents of arrays don't matter. You have n tests — the i-th test is an array of size m_i (1 \le m_i \le k).Your coordinator asks you to distribute all of your arrays into multiple testcases. Each testcase can include multiple arrays. However, each testcase should include no more than c_1 arrays of size greater than or equal to 1 (\ge 1), no more than c_2 arrays of size greater than or equal to 2, \dots, no more than c_k arrays of size greater than or equal to k. Also, c_1 \ge c_2 \ge \dots \ge c_k.So now your goal is to create the new testcases in such a way that: each of the initial arrays appears in exactly one testcase; for each testcase the given conditions hold; the number of testcases is minimum possible. Print the minimum possible number of testcases you can achieve and the sizes of arrays included in each testcase.InputThe first line contains two integers n and k (1 \le n, k \le 2 \cdot 10^5) — the number of initial tests and the limit for the size of each array.The second line contains n integers m_1, m_2, \dots, m_n (1 \le m_i \le k) — the sizes of the arrays in the original tests.The third line contains k integers c_1, c_2, \dots, c_k (n \ge c_1 \ge c_2 \ge \dots \ge c_k \ge 1); c_i is the maximum number of arrays of size greater than or equal to i you can have in a single testcase.OutputIn the first line print a single integer ans (1 \le ans \le n) — the minimum number of testcases you can achieve.Each of the next ans lines should contain the description of a testcase in the following format:t a_1 a_2 \dots a_{t} (1 \le t\le n) — the testcase includes t arrays, a_i is the size of the i-th array in that testcase.Each of the initial arrays should appear in exactly one testcase. In particular, it implies that the sum of t over all ans testcases should be equal to n.Note that the answer always exists due to c_k \ge 1 (and therefore c_1 \ge 1).If there are multiple answers, you can output any one of them.ExamplesInput 4 3 1 2 2 3 4 1 1 Output 3 1 2 2 1 3 1 2 Input 6 10 5 8 1 10 8 7 6 6 4 4 3 2 2 2 1 1 Output 2 3 8 5 7 3 10 8 1 Input 5 1 1 1 1 1 1 5 Output 1 5 1 1 1 1 1 Input 5 1 1 1 1 1 1 1 Output 5 1 1 1 1 1 1 1 1 1 1 NoteIn the first example there is no way to distribute the tests into less than 3 testcases. The given answer satisfies the conditions: each of the testcases includes no more than 4 arrays of size greater than or equal to 1 and no more than 1 array of sizes greater than or equal to 2 and 3.Note that there are multiple valid answers for this test. For example, testcases with sizes [[2], [1, 2], [3]] would also be correct.However, testcases with sizes [[1, 2], [2, 3]] would be incorrect because there are 2 arrays of size greater than or equal to 2 in the second testcase.Note the difference between the third and the fourth examples. You can include up to 5 arrays of size greater than or equal to 1 in the third example, so you can put all arrays into a single testcase. And you can have only up to 1 array in the fourth example. Thus, every array should be included in a separate testcase.
4 3 1 2 2 3 4 1 1
3 1 2 2 1 3 1 2
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'greedy', 'sortings', 'two pointers', '*1900']
C. Yet Another Counting Problemtime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i \le x \le r_i, and ((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a). Calculate the answer for each query.Recall that y \bmod z is the remainder of the division of y by z. For example, 5 \bmod 3 = 2, 7 \bmod 8 = 7, 9 \bmod 4 = 1, 9 \bmod 9 = 0.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases. Then the test cases follow.The first line of each test case contains three integers a, b and q (1 \le a, b \le 200; 1 \le q \le 500).Then q lines follow, each containing two integers l_i and r_i (1 \le l_i \le r_i \le 10^{18}) for the corresponding query.OutputFor each test case, print q integers — the answers to the queries of this test case in the order they appear.ExampleInput 2 4 6 5 1 1 1 3 1 5 1 7 1 9 7 10 2 7 8 100 200 Output 0 0 0 2 4 0 91
2 4 6 5 1 1 1 3 1 5 1 7 1 9 7 10 2 7 8 100 200
0 0 0 2 4 0 91
3.5 seconds
256 megabytes
['math', 'number theory', '*1600']
B. Binary Periodtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property.Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=4.You are given string t consisting only of 0's and 1's and you need to find such string s that: String s consists only of 0's and 1's; The length of s doesn't exceed 2 \cdot |t|; String t is a subsequence of string s; String s has smallest possible period among all strings that meet conditions 1—3. Let us recall that t is a subsequence of s if t can be derived from s by deleting zero or more elements (any) without changing the order of the remaining elements. For example, t="011" is a subsequence of s="10101".InputThe first line contains single integer T (1 \le T \le 100) — the number of test cases.Next T lines contain test cases — one per line. Each line contains string t (1 \le |t| \le 100) consisting only of 0's and 1's.OutputPrint one string for each test case — string s you needed to find. If there are multiple solutions print any one of them.ExampleInput 4 00 01 111 110 Output 00 01 11111 1010NoteIn the first and second test cases, s = t since it's already one of the optimal solutions. Answers have periods equal to 1 and 2, respectively.In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string s. String s has period equal to 1.
4 00 01 111 110
00 01 11111 1010
2 seconds
256 megabytes
['constructive algorithms', 'strings', '*1100']
A. Road To Zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers x and y. You can perform two types of operations: Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: x = 0, y = 6; x = 0, y = 8; x = -1, y = 7; x = 1, y = 7. Pay b dollars and increase or decrease both integers by 1. For example, if x = 0 and y = 7 there are two possible outcomes after this operation: x = -1, y = 6; x = 1, y = 8. Your goal is to make both given integers equal zero simultaneously, i.e. x = y = 0. There are no other requirements. In particular, it is possible to move from x=1, y=0 to x=y=0.Calculate the minimum amount of dollars you have to spend on it.InputThe first line contains one integer t (1 \le t \le 100) — the number of testcases.The first line of each test case contains two integers x and y (0 \le x, y \le 10^9).The second line of each test case contains two integers a and b (1 \le a, b \le 10^9).OutputFor each test case print one integer — the minimum amount of dollars you have to spend.ExampleInput 2 1 3 391 555 0 0 9 4 Output 1337 0 NoteIn the first test case you can perform the following sequence of operations: first, second, first. This way you spend 391 + 555 + 391 = 1337 dollars.In the second test case both integers are equal to zero initially, so you dont' have to spend money.
2 1 3 391 555 0 0 9 4
1337 0
1 second
256 megabytes
['greedy', 'math', '*1000']
B. Nastya and Doortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k \ge 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.Mountains are described by a sequence of heights a_1, a_2, \dots, a_n in order from left to right (k \le n). It is guaranteed that neighboring heights are not equal to each other (that is, a_i \ne a_{i+1} for all i from 1 to n-1).Peaks of mountains on the segment [l,r] (from l to r) are called indexes i such that l < i < r, a_{i - 1} < a_i and a_i > a_{i + 1}. It is worth noting that the boundary indexes l and r for the segment are not peaks. For example, if n=8 and a=[3,1,4,1,5,9,2,6], then the segment [1,8] has only two peaks (with indexes 3 and 6), and there are no peaks on the segment [3, 6].To break the door, Nastya throws it to a segment [l,l+k-1] of consecutive mountains of length k (1 \le l \le n-k+1). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to p+1, where p is the number of peaks on the segment [l,l+k-1].Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains [l, l+k-1] that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value l is minimal.Formally, you need to choose a segment of mountains [l, l+k-1] that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value l.InputThe first line contains an integer t (1 \leq t \leq 10^4)  — the number of test cases. Then the descriptions of the test cases follow.The first line of each test case contains two integers n and k (3 \leq k \leq n \leq 2 \cdot 10^5)  — the number of mountains and the length of the door.The second line of the input data set contains n integers a_1, a_2, \dots, a_n (0 \leq a_i \leq 10 ^ 9, a_i \neq a_{i + 1})  — the heights of mountains.It is guaranteed that the sum of n over all the test cases will not exceed 2 \cdot 10^5.OutputFor each test case, output two integers t and l  — the maximum number of parts that the door can split into, and the left border of the segment of length k that the door should be reset to.ExampleInput 5 8 6 1 2 4 1 2 4 1 2 5 3 3 2 3 2 1 10 4 4 3 4 3 2 3 2 1 0 1 15 7 3 7 4 8 2 3 4 5 21 2 3 4 2 1 3 7 5 1 2 3 4 5 6 1 Output 3 2 2 2 2 1 3 1 2 3 NoteIn the first example, you need to select a segment of mountains from 2 to 7. In this segment, the indexes 3 and 6 are peaks, so the answer is 3 (only 2 peaks, so the door will break into 3 parts). It is not difficult to notice that the mountain segments [1, 6] and [3, 8] are not suitable since they only have a 1 peak (for the first segment, the 6 index is not a peak, and for the second segment, the 3 index is not a peak).In the second example, you need to select a segment of mountains from 2 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts).In the third example, you need to select a segment of mountains from 1 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts). You can see that on the segments [2, 5], [4, 7] and [5, 8] the number of peaks is also 1, but these segments have a left border greater than the segment [1, 4], so they are not the correct answer.
5 8 6 1 2 4 1 2 4 1 2 5 3 3 2 3 2 1 10 4 4 3 4 3 2 3 2 1 0 1 15 7 3 7 4 8 2 3 4 5 21 2 3 4 2 1 3 7 5 1 2 3 4 5 6 1
3 2 2 2 2 1 3 1 2 3
1 second
256 megabytes
['greedy', 'implementation', '*1300']
A. Nastya and Ricetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the whole package of n grains weighs from c - d to c + d grams, inclusive (numbers c and d are known). The weight of the package is the sum of the weights of all n grains in it.Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the i-th grain weighs some integer number x_i (a - b \leq x_i \leq a + b), and in total they weigh from c - d to c + d, inclusive (c - d \leq \sum\limits_{i=1}^{n}{x_i} \leq c + d).InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 1000)  — the number of test cases. The next t lines contain descriptions of the test cases, each line contains 5 integers: n (1 \leq n \leq 1000)  — the number of grains that Nastya counted and a, b, c, d (0 \leq b < a \leq 1000, 0 \leq d < c \leq 1000)  — numbers that determine the possible weight of one grain of rice (from a - b to a + b) and the possible total weight of the package (from c - d to c + d).OutputFor each test case given in the input print "Yes", if the information about the weights is not inconsistent, and print "No" if n grains with masses from a - b to a + b cannot make a package with a total mass from c - d to c + d.ExampleInput 5 7 20 3 101 18 11 11 10 234 2 8 9 7 250 122 19 41 21 321 10 3 10 8 6 1 Output Yes No Yes No Yes NoteIn the first test case of the example, we can assume that each grain weighs 17 grams, and a pack 119 grams, then really Nastya could collect the whole pack.In the third test case of the example, we can assume that each grain weighs 16 grams, and a pack 128 grams, then really Nastya could collect the whole pack.In the fifth test case of the example, we can be assumed that 3 grains of rice weigh 2, 2, and 3 grams, and a pack is 7 grams, then really Nastya could collect the whole pack.In the second and fourth test cases of the example, we can prove that it is impossible to determine the correct weight of all grains of rice and the weight of the pack so that the weight of the pack is equal to the total weight of all collected grains.
5 7 20 3 101 18 11 11 10 234 2 8 9 7 250 122 19 41 21 321 10 3 10 8 6 1
Yes No Yes No Yes
1 second
256 megabytes
['math', '*900']
F. Nastya and CBStime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Nastya is a competitive programmer, but she is only studying now. Recently, Denis told her about the way to check if the string is correct bracket sequence. After that, unexpectedly, Nastya came up with a much more complex problem that Denis couldn't solve. Can you solve it? A string s is given. It consists of k kinds of pairs of brackets. Each bracket has the form t  — it is an integer, such that 1 \leq |t| \leq k. If the bracket has a form t, then: If t > 0, then it's an opening bracket of the type t. If t < 0, then it's a closing bracket of the type -t. Thus, there are k types of pairs of brackets in total. The queries need to be answered: Replace the bracket at position i with the bracket of the form t. Check if the substring from the l-th to r-th position (including) is the correct bracket sequence. Recall the definition of the correct bracket sequence: An empty sequence is correct. If A and B are two correct bracket sequences, then their concatenation "A B" is also correct bracket sequence. If A is the correct bracket sequence, c (1 \leq c \leq k) is a type of brackets, then the sequence "c A -c" is also correct bracket sequence. InputThe first line contains an integer n (1 \leq n \leq 10^5)  — length of string and k (1 \leq k \leq n)  — the number of kinds of pairs of brackets.The second line contains string s of length n  — n integers s_1, s_2, \ldots, s_n (1 \leq |s_i| \leq k)The third line contains single integer q (1 \leq q \leq 10^5)  — the number of queries.Each of the following q lines describes the queries: 1 i t - query of the 1 type (1 \leq i \leq n, 1 \leq |t| \leq k). 2 l r - query of the 2 type (1 \leq l \leq r \leq n). OutputFor each query of 2 type, output "Yes" if the substring from the query is the correct bracket sequence and "No", otherwise.All letters can be displayed in any case.ExamplesInput 2 1 1 -1 1 2 1 2 Output Yes Input 2 2 1 -2 1 2 1 2 Output No Input 6 2 1 2 -2 -1 1 -1 3 2 1 6 2 1 4 2 2 5 Output Yes Yes No Input 2 2 -1 1 4 2 1 2 1 1 1 1 2 -1 2 1 2 Output No Yes NoteIn the fourth test, initially, the string is not a correct bracket sequence, so the answer to the first query is "No". After two changes it will be equal to "1 -1", so it is a correct bracket sequence and the answer to the fourth query is "Yes".
2 1 1 -1 1 2 1 2
Yes
4 seconds
256 megabytes
['brute force', 'data structures', 'hashing', '*3300']
E. Nastya and Beestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputUnfortunately, a mistake was found in the proof of the author's solution to this problem. Currently, we don't know the absolutely correct solution. However, you can solve this task, but if your solution passes all the tests, it is not guaranteed to be correct. If your solution has passed all the tests and you are sure that it is correct, you can write to one of the contest authors about it. Surely you all read the book "Alice in Wonderland". In this task, Nastya got to the country of Three strange Bees. The bees are strange because their honeycombs are pentagonal. Nastya got there illegally, so she wants bees not to catch her. Help the bees punish the intruder! This is an interactive problem.A beehive is a connected undirected graph where bees and Nastya can move along the edges. A graph satisfies two properties: The degree of any of its vertex is no more than 3. For each edge, there exists a cycle of length not greater than 5 passing through this edge. There are three bees and Nastya. You play for bees. Firstly, you choose the vertices where you put the bees. Then Nastya chooses another vertex in which she will initially appear. One move is first moving the bees, then Nastya, in turn: For each of your bees, you can either move each one along some edge from the vertex they are currently staying or leave it in place. Then Nastya will necessarily move along some edge of the graph from the vertex she is currently staying/. You win if at least one of the bees and Nastya are in the same vertex at any time of the game.If this situation does not occur after n moves, then you lose.Several bees can be in the same vertex.InputThe first line contains two integers n (4 \leq n \leq 5000) and m (n \leq m \leq 3n)  — the number of vertices and edges in the graph.Each of the next m lines contains two integers v and u (1 \leq v, u \leq n), which mean that there is an edge between the vertices v and u. It is guaranteed that the graph is connected, does not contain loops that the degree of any vertex does not exceed 3 and a cycle of length no more than 5 passes through each edge. Note that the graph may contain multiple edges.InteractionAt each turn, you must output exactly three vertices a, b, c (1 \leq a, b, c \leq n). For the first time, 3 vertices displayed will indicate which vertices you originally placed bees on. In response, you will receive the vertex where the jury placed Nastya. Each next 3 vertices will indicate where the 3 bees move at your turn. Each of the bees can, regardless of other bees, both remain at the current vertex and move along the edge. After the next output of 3 vertices, in response, you get the number of the new vertex to which Nastya went.As soon as one of the bees is at the same vertex with Nastya or you have reached the limit on the number of moves, your program should stop working. That is if you made a move, and one of the bees ended up at the same vertex with Nastya, your program must stop working, or if Nastya made a move and ended up at the same vertex with one of the bees, you should not make your move and the program should stop working.If the number of moves exceeds limit (n, where n is the number of vertices), you will get the Wrong Answer verdict.Your solution may receive the verdict Idleness Limit Exceeded if you don't output anything or forget to flush the output buffer.To flush the output buffer, you need to do the following immediately after printing the query and the line end: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; for other languages see documentation. In this problem interactor is adaptive. This means that depending on all your previous moves, Nastya's behavior may change.Hacks are not available for this problem.ExamplesInput 5 5 1 2 2 3 3 4 4 5 5 1 4 5Output 1 1 2 1 5 3Input 8 9 1 2 2 3 3 4 4 5 5 1 5 6 6 7 7 8 8 4 1 5Output 7 3 3 6 2 2 5 3 1NoteLet Nastya be a green chip, and three numbered red ones are three bees.In the first test, the movement of the heroes looks like this. After selecting the starting vertices. The first move after the bees move. The first move after the Nastya's move. The first bee caught Nastya. In the second test, the movement of the heroes looks like this. After selecting the starting vertices. The first move after the bees move. The first move after the Nastya's move. The second move after the bees move. The first bee caught Nastya.
5 5 1 2 2 3 3 4 4 5 5 1 4 5
1 1 2 1 5 3
1 second
256 megabytes
['graphs', 'interactive', 'probabilities', '*3000']
D. Nastya and Time Machinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Denis came to Nastya and discovered that she was not happy to see him... There is only one chance that she can become happy. Denis wants to buy all things that Nastya likes so she will certainly agree to talk to him. The map of the city where they live has a lot of squares, some of which are connected by roads. There is exactly one way between each pair of squares which does not visit any vertex twice. It turns out that the graph of the city is a tree.Denis is located at vertex 1 at the time 0. He wants to visit every vertex at least once and get back as soon as possible.Denis can walk one road in 1 time. Unfortunately, the city is so large that it will take a very long time to visit all squares. Therefore, Denis took a desperate step. He pulled out his pocket time machine, which he constructed in his basement. With its help, Denis can change the time to any non-negative time, which is less than the current time.But the time machine has one feature. If the hero finds himself in the same place and at the same time twice, there will be an explosion of universal proportions and Nastya will stay unhappy. Therefore, Denis asks you to find him a route using a time machine that he will get around all squares and will return to the first and at the same time the maximum time in which he visited any square will be minimal.Formally, Denis's route can be represented as a sequence of pairs: \{v_1, t_1\}, \{v_2, t_2\}, \{v_3, t_3\}, \ldots, \{v_k, t_k\}, where v_i is number of square, and t_i is time in which the boy is now.The following conditions must be met: The route starts on square 1 at time 0, i.e. v_1 = 1, t_1 = 0 and ends on the square 1, i.e. v_k = 1. All transitions are divided into two types: Being in the square change the time: \{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \} : v_{i+1} = v_i, 0 \leq t_{i+1} < t_i. Walk along one of the roads: \{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \}. Herewith, v_i and v_{i+1} are connected by road, and t_{i+1} = t_i + 1 All pairs \{ v_i, t_i \} must be different. All squares are among v_1, v_2, \ldots, v_k. You need to find a route such that the maximum time in any square will be minimal, that is, the route for which \max{(t_1, t_2, \ldots, t_k)} will be the minimum possible.InputThe first line contains a single integer n (1 \leq n \leq 10^5)  — the number of squares in the city. The next n - 1 lines contain two integers u and v (1 \leq v, u \leq n, u \neq v) - the numbers of the squares connected by the road. It is guaranteed that the given graph is a tree.OutputIn the first line output the integer k (1 \leq k \leq 10^6)  — the length of the path of Denis.In the next k lines output pairs v_i, t_i  — pairs that describe Denis's route (as in the statement).All route requirements described in the statements must be met.It is guaranteed that under given restrictions there is at least one route and an answer whose length does not exceed 10^6. If there are several possible answers, print any.ExampleInput 5 1 2 2 3 2 4 4 5 Output 13 1 0 2 1 3 2 3 1 2 2 4 3 4 1 5 2 5 1 4 2 2 3 2 0 1 1
5 1 2 2 3 2 4 4 5
13 1 0 2 1 3 2 3 1 2 2 4 3 4 1 5 2 5 1 4 2 2 3 2 0 1 1
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'trees', '*2600']
C. Nastya and Unexpected Guesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.He knows many different integers d_1, d_2, \ldots, d_m, where 0 \leq d_i \leq n  — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by \pm 1 in 1 second. While doing so, he must always stay inside the segment [0, n]. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by \pm 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by \pm 1, and at any other point by -1. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to n.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.InputThe first line contains two integers n and m (1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))  — road width and the number of safety islands.The second line contains m distinct integers d_1, d_2, \ldots, d_m (0 \leq d_i \leq n)  — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.The third line contains two integers g, r (1 \leq g, r \leq 1000)  — the time that the green light stays on and the time that the red light stays on.OutputOutput a single integer  — the minimum time for which Denis can cross the road with obeying all the rules.If it is impossible to cross the road output -1.ExamplesInput 15 5 0 3 7 14 15 11 11 Output 45Input 13 4 0 3 7 13 9 9 Output -1NoteIn the first test, the optimal route is:      for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.      for the second green light reaches 14. Wait for the red light again.      for 1 second go to 15. As a result, Denis is at the end of the road. In total, 45 seconds are obtained.In the second test, it is impossible to cross the road according to all the rules.
15 5 0 3 7 14 15 11 11
45
1 second
256 megabytes
['dfs and similar', 'dp', 'graphs', 'shortest paths', '*2400']
B. Nastya and Scoreboardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of 7 segments, which can be turned on or off to display different numbers. The picture shows how all 10 decimal digits are displayed: After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke exactly k segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly k sticks (which are off now)? It is allowed that the number includes leading zeros.InputThe first line contains integer n (1 \leq n \leq 2000)  — the number of digits on scoreboard and k (0 \leq k \leq 2000)  — the number of segments that stopped working.The next n lines contain one binary string of length 7, the i-th of which encodes the i-th digit of the scoreboard.Each digit on the scoreboard consists of 7 segments. We number them, as in the picture below, and let the i-th place of the binary string be 0 if the i-th stick is not glowing and 1 if it is glowing. Then a binary string of length 7 will specify which segments are glowing now. Thus, the sequences "1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" encode in sequence all digits from 0 to 9 inclusive.OutputOutput a single number consisting of n digits  — the maximum number that can be obtained if you turn on exactly k sticks or -1, if it is impossible to turn on exactly k sticks so that a correct number appears on the scoreboard digits.ExamplesInput 1 7 0000000 Output 8Input 2 5 0010010 0010010 Output 97Input 3 5 0100001 1001001 1010011 Output -1NoteIn the first test, we are obliged to include all 7 sticks and get one 8 digit on the scoreboard.In the second test, we have sticks turned on so that units are formed. For 5 of additionally included sticks, you can get the numbers 07, 18, 34, 43, 70, 79, 81 and 97, of which we choose the maximum  — 97.In the third test, it is impossible to turn on exactly 5 sticks so that a sequence of numbers appears on the scoreboard.
1 7 0000000
8
1 second
256 megabytes
['bitmasks', 'dp', 'graphs', 'greedy', '*1700']
A. Nastya and Strange Generatortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of n steps. At the i-th step, a place is chosen for the number i (1 \leq i \leq n). The position for the number i is defined as follows: For all j from 1 to n, we calculate r_j  — the minimum index such that j \leq r_j \leq n, and the position r_j is not yet occupied in the permutation. If there are no such positions, then we assume that the value of r_j is not defined. For all t from 1 to n, we calculate count_t  — the number of positions 1 \leq j \leq n such that r_j is defined and r_j = t. Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the count array is maximum. The generator selects one of these positions for the number i. The generator can choose any position. Let's have a look at the operation of the algorithm in the following example: Let n = 5 and the algorithm has already arranged the numbers 1, 2, 3 in the permutation. Consider how the generator will choose a position for the number 4: The values of r will be r = [3, 3, 3, 4, \times], where \times means an indefinite value. Then the count values will be count = [0, 0, 3, 1, 0]. There are only two unoccupied positions in the permutation: 3 and 4. The value in the count array for position 3 is 3, for position 4 it is 1. The maximum value is reached only for position 3, so the algorithm will uniquely select this position for number 4. Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind p_1, p_2, \ldots, p_n and decided to find out if it could be obtained as a result of the generator.Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.InputThe first line contains a single integer t (1 \leq t \leq 10^5)  — the number of test cases. Then the descriptions of the test cases follow.The first line of the test case contains a single integer n (1 \leq n \leq 10^5)  — the size of the permutation.The second line of the test case contains n different integers p_1, p_2, \ldots, p_n (1 \leq p_i \leq n)  — the permutation written by Denis.It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.OutputPrint "Yes" if this permutation could be obtained as a result of the generator. Otherwise, print "No".All letters can be displayed in any case.ExampleInput 5 5 2 3 4 5 1 1 1 3 1 3 2 4 4 2 3 1 5 1 5 2 4 3 Output Yes Yes No Yes No NoteLet's simulate the operation of the generator in the first test.At the 1 step, r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]. The maximum value is reached in any free position, so the generator can choose a random position from 1 to 5. In our example, it chose 5.At the 2 step, r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]. The maximum value is reached in positions from 1 to 4, so the generator can choose a random position among them. In our example, it chose 1.At the 3 step, r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]. The maximum value is 2 and is reached only at the 2 position, so the generator will choose this position.At the 4 step, r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]. The maximum value is 3 and is reached only at the 3 position, so the generator will choose this position.At the 5 step, r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]. The maximum value is 4 and is reached only at the 4 position, so the generator will choose this position.In total, we got a permutation of 2, 3, 4, 5, 1, that is, a generator could generate it.
5 5 2 3 4 5 1 1 1 3 1 3 2 4 4 2 3 1 5 1 5 2 4 3
Yes Yes No Yes No
1 second
256 megabytes
['brute force', 'data structures', 'greedy', 'implementation', '*1500']
B. Sorted Adjacent Differencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have array of n numbers a_{1}, a_{2}, \ldots, a_{n}. Rearrange these numbers to satisfy |a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.Note that all numbers in a are not necessarily different. In other words, some numbers of a may be same.You have to answer independent t test cases.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 single integer n (3 \le n \le 10^{5}) — the length of array a. It is guaranteed that the sum of values of n over all test cases in the input does not exceed 10^{5}.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}).OutputFor each test case, print the rearranged version of array a which satisfies given condition. If there are multiple valid rearrangements, print any of them.ExampleInput 2 6 5 -2 4 8 6 5 4 8 1 4 2 Output 5 5 4 6 8 -2 1 2 4 8 NoteIn the first test case, after given rearrangement, |a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10. There are other possible answers like "5 4 5 6 -2 8".In the second test case, after given rearrangement, |a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4. There are other possible answers like "2 4 8 1".
2 6 5 -2 4 8 6 5 4 8 1 4 2
5 5 4 6 8 -2 1 2 4 8
1 second
256 megabytes
['constructive algorithms', 'sortings', '*1200']
A. Filling Diamondstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. 2 coverings are different if some 2 triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding. On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for n = 1, 2, 3, 4. You have to answer t independent test cases.InputThe first line contains a single integer t (1 \le t \le 10^{4}) — the number of test cases.Each of the next t lines contains a single integer n (1 \le n \le 10^{9}).OutputFor each test case, print the number of ways to fully cover belt-like area of 4n-2 triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed 10^{18}.ExampleInput 2 2 1 Output 2 1 NoteIn the first test case, there are the following 2 ways to fill the area: In the second test case, there is a unique way to fill the area:
2 2 1
2 1
1 second
256 megabytes
['brute force', 'dp', 'implementation', 'math', '*900']
E. JYPnationtime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDue to the success of TWICE, JYP Entertainment has earned countless money and emerged as the biggest entertainment firm by market capitalization. Therefore, the boss, JYP, has decided to create a new nation and has appointed you to provide a design diagram.The new nation consists of n cities and some roads between them. JYP has given some restrictions: To guarantee efficiency while avoiding chaos, for any 2 different cities A and B, there is exactly one road between them, and it is one-directional. There are no roads connecting a city to itself. The logo of rivaling companies should not appear in the plan, that is, there does not exist 4 distinct cities A,B,C,D , such that the following configuration occurs. JYP has given criteria for your diagram. For two cities A,B, let dis(A,B) be the smallest number of roads you have to go through to get from A to B. If it is not possible to walk from A to B, dis(A,B) = 614n. Then, the efficiency value is defined to be the sum of dis(A,B) for all ordered pairs of distinct cities (A,B).Note that dis(A,B) doesn't have to be equal to dis(B,A).You have drawn a design diagram that satisfies JYP's restrictions. Find the sum of dis(A,B) over all ordered pairs of cities (A,B) with A\neq B.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.InputThe first line contains a single integer n (4 \le n \le 8000, n \equiv 0 \pmod{4}) — the number of cities.A binary matrix is encrypted in the following format. Each of n next lines contains \frac{n}{4} one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from 0 to 9 or as uppercase Latin letters from A to F). Binary representation of each of these numbers denotes next 4 elements of the matrix in the corresponding row. For example, if the number B is given, then the corresponding elements are 1011, and if the number is 5, then the corresponding elements are 0101.After you obtain the decrypted binary matrix, the j-th character of the i-th row is 1 if the one-directional road between cities i and j is directed from i to j, and 0 otherwise. It is guaranteed that the graph satisfies the restrictions mentioned above.OutputOutput one integer, representing the sum of dis(A,B) over all ordered pairs of cities (A,B) with A\neq B.ExamplesInput 4 7 2 1 4 Output 7380 Input 8 7F 3F 1F 0C 06 03 11 18 Output 88464 NoteThe first example corresponds to the matrix:\begin{matrix} 0111 \\ 0010 \\ 0001 \\ 0100 \\ \end{matrix}Which corresponds to this graph:dis(1,2)=dis(1,3)=dis(1,4)=dis(2,3)=dis(3,4)=dis(4,2)=1dis(2,4)=dis(4,3)=dis(3,2)=2dis(2,1)=dis(3,1)=dis(4,1)=2456Therefore the answer for the diagram is 7380.
4 7 2 1 4
7380
2 seconds
1024 megabytes
['graphs', '*3500']
D. Nested Rubber Bandstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a tree of n vertices. You are going to convert this tree into n rubber bands on infinitely large plane. Conversion rule follows: For every pair of vertices a and b, rubber bands a and b should intersect if and only if there is an edge exists between a and b in the tree. Shape of rubber bands must be a simple loop. In other words, rubber band is a loop which doesn't self-intersect. Now let's define following things: Rubber band a includes rubber band b, if and only if rubber band b is in rubber band a's area, and they don't intersect each other. Sequence of rubber bands a_{1}, a_{2}, \ldots, a_{k} (k \ge 2) are nested, if and only if for all i (2 \le i \le k), a_{i-1} includes a_{i}. This is an example of conversion. Note that rubber bands 5 and 6 are nested. It can be proved that is it possible to make a conversion and sequence of nested rubber bands under given constraints.What is the maximum length of sequence of nested rubber bands can be obtained from given tree? Find and print it.InputThe first line contains integer n (3 \le n \le 10^{5}) — the number of vertices in tree.The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 \le a_{i} \lt b_{i} \le n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.OutputPrint the answer.ExamplesInput 6 1 3 2 3 3 4 4 5 4 6 Output 4 Input 4 1 2 2 3 3 4 Output 2 NoteIn the first sample, you can obtain a nested sequence of 4 rubber bands(1, 2, 5, and 6) by the conversion shown below. Of course, there are other conversions exist to make a nested sequence of 4 rubber bands. However, you cannot make sequence of 5 or more nested rubber bands with given tree. You can see one of the possible conversions for the second sample below.
6 1 3 2 3 3 4 4 5 4 6
4
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'dp', 'math', 'trees', '*2700']
C. Perfect Triplestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the infinite sequence s of positive integers, created by repeating the following steps: Find the lexicographically smallest triple of positive integers (a, b, c) such that a \oplus b \oplus c = 0, where \oplus denotes the bitwise XOR operation. a, b, c are not in s. Here triple of integers (a_1, b_1, c_1) is considered to be lexicographically smaller than triple (a_2, b_2, c_2) if sequence [a_1, b_1, c_1] is lexicographically smaller than sequence [a_2, b_2, c_2]. Append a, b, c to s in this order. Go back to the first step. You have integer n. Find the n-th element of s.You have to answer t independent test cases.A sequence a is lexicographically smaller than a sequence b if in the first position where a and b differ, the sequence a has a smaller element than the corresponding element in b.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.Each of the next t lines contains a single integer n (1\le n \le 10^{16}) — the position of the element you want to know.OutputIn each of the t lines, output the answer to the corresponding test case.ExampleInput 9 1 2 3 4 5 6 7 8 9 Output 1 2 3 4 8 12 5 10 15 NoteThe first elements of s are 1, 2, 3, 4, 8, 12, 5, 10, 15, \dots
9 1 2 3 4 5 6 7 8 9
1 2 3 4 8 12 5 10 15
2 seconds
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'divide and conquer', 'math', '*2200']
B. Edge Weight Assignmenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: For every two different leaves v_{1} and v_{2} of this tree, bitwise XOR of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0. Note that you can put very large positive integers (like 10^{(10^{10})}).It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment. In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5). In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0. What are the minimum and the maximum possible values of f for the given tree? Find and print both.InputThe first line contains integer n (3 \le n \le 10^{5}) — the number of vertices in given tree.The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 \le a_{i} \lt b_{i} \le n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.OutputPrint two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.ExamplesInput 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 NoteIn the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3. In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
6 1 3 2 3 3 4 4 5 5 6
1 4
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'dfs and similar', 'greedy', 'math', 'trees', '*1800']
A. Powered Additiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second: Select some distinct indices i_{1}, i_{2}, \ldots, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{x-1} for j = 1, 2, \ldots, k. Note that you are allowed to not select any indices at all. You have to make a nondecreasing as fast as possible. Find the smallest number T such that you can make the array nondecreasing after at most T seconds.Array a is nondecreasing if and only if a_{1} \le a_{2} \le \ldots \le a_{n}.You have to answer t independent test cases.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 single integer n (1 \le n \le 10^{5}) — the length of array a. It is guaranteed that the sum of values of n over all test cases in the input does not exceed 10^{5}.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}).OutputFor each test case, print the minimum number of seconds in which you can make a nondecreasing.ExampleInput 3 4 1 7 6 5 5 1 2 3 4 5 2 0 -4 Output 2 0 3 NoteIn the first test case, if you select indices 3, 4 at the 1-st second and 4 at the 2-nd second, then a will become [1, 7, 7, 8]. There are some other possible ways to make a nondecreasing in 2 seconds, but you can't do it faster.In the second test case, a is already nondecreasing, so answer is 0.In the third test case, if you do nothing at first 2 seconds and select index 2 at the 3-rd second, a will become [0, 0].
3 4 1 7 6 5 5 1 2 3 4 5 2 0 -4
2 0 3
1 second
256 megabytes
['greedy', 'math', '*1500']
B. Kana and Dragon Quest gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. The dragon has a hit point of x initially. When its hit point goes to 0 or under 0, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells. Void Absorption Assume that the dragon's current hit point is h, after casting this spell its hit point will become \left\lfloor \frac{h}{2} \right\rfloor + 10. Here \left\lfloor \frac{h}{2} \right\rfloor denotes h divided by two, rounded down. Lightning Strike This spell will decrease the dragon's hit point by 10. Assume that the dragon's current hit point is h, after casting this spell its hit point will be lowered to h-10.Due to some reasons Kana can only cast no more than n Void Absorptions and m Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.InputThe first line contains a single integer t (1 \leq t \leq 1000)  — the number of test cases.The next t lines describe test cases. For each test case the only line contains three integers x, n, m (1\le x \le 10^5, 0\le n,m\le30)  — the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.OutputIf it is possible to defeat the dragon, print "YES" (without quotes). Otherwise, print "NO" (without quotes).You can print each letter in any case (upper or lower).ExampleInput 7 100 3 4 189 3 4 64 2 3 63 2 3 30 27 7 10 9 1 69117 21 2 Output YES NO NO YES YES YES YES NoteOne possible casting sequence of the first test case is shown below: Void Absorption \left\lfloor \frac{100}{2} \right\rfloor + 10=60. Lightning Strike 60-10=50. Void Absorption \left\lfloor \frac{50}{2} \right\rfloor + 10=35. Void Absorption \left\lfloor \frac{35}{2} \right\rfloor + 10=27. Lightning Strike 27-10=17. Lightning Strike 17-10=7. Lightning Strike 7-10=-3.
7 100 3 4 189 3 4 64 2 3 63 2 3 30 27 7 10 9 1 69117 21 2
YES NO NO YES YES YES YES
1 second
256 megabytes
['greedy', 'implementation', 'math', '*900']
A. Ichihime and Triangletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIchihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem. You are given four positive integers a, b, c, d, such that a \leq b \leq c \leq d. Your task is to find three integers x, y, z, satisfying the following conditions: a \leq x \leq b. b \leq y \leq c. c \leq z \leq d. There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?InputThe first line contains a single integer t (1 \leq t \leq 1000)  — the number of test cases.The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 \leq a \leq b \leq c \leq d \leq 10^9).OutputFor each test case, print three integers x, y, z  — the integers you found satisfying the conditions given in the statement.It is guaranteed that the answer always exists. If there are multiple answers, print any.ExampleInput 4 1 3 5 7 1 5 5 7 100000 200000 300000 400000 1 1 977539810 977539810 Output 3 4 5 5 5 5 182690 214748 300999 1 977539810 977539810 NoteOne of the possible solutions to the first test case:One of the possible solutions to the second test case:
4 1 3 5 7 1 5 5 7 100000 200000 300000 400000 1 1 977539810 977539810
3 4 5 5 5 5 182690 214748 300999 1 977539810 977539810
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
F. Journeytime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIn the wilds far beyond lies the Land of Sacredness, which can be viewed as a tree  — connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. There are m travelers attracted by its prosperity and beauty. Thereupon, they set off their journey on this land. The i-th traveler will travel along the shortest path from s_i to t_i. In doing so, they will go through all edges in the shortest path from s_i to t_i, which is unique in the tree.During their journey, the travelers will acquaint themselves with the others. Some may even become friends. To be specific, the i-th traveler and the j-th traveler will become friends if and only if there are at least k edges that both the i-th traveler and the j-th traveler will go through. Your task is to find out the number of pairs of travelers (i, j) satisfying the following conditions: 1 \leq i < j \leq m. the i-th traveler and the j-th traveler will become friends. InputThe first line contains three integers n, m and k (2 \le n, m \le 1.5 \cdot 10^5, 1\le k\le n). Each of the next n-1 lines contains two integers u and v (1 \le u,v \le n), denoting there is an edge between u and v. The i-th line of the next m lines contains two integers s_i and t_i (1\le s_i,t_i\le n, s_i \neq t_i), denoting the starting point and the destination of i-th traveler. It is guaranteed that the given edges form a tree.OutputThe only line contains a single integer  — the number of pairs of travelers satisfying the given conditions.ExamplesInput 8 4 1 1 7 1 2 2 5 4 6 6 3 6 2 6 8 7 8 3 8 2 6 4 1 Output 4Input 10 4 2 3 10 9 3 4 9 4 6 8 2 1 7 2 1 4 5 6 7 7 1 8 7 9 2 10 3 Output 1Input 13 8 3 7 6 9 11 5 6 11 3 9 7 2 12 4 3 1 2 5 8 6 13 5 10 3 1 10 4 10 11 8 11 4 9 2 5 3 5 7 3 8 10 Output 14NoteIn the first example there are 4 pairs satisfying the given requirements: (1,2), (1,3), (1,4), (3,4). The 1-st traveler and the 2-nd traveler both go through the edge 6-8. The 1-st traveler and the 3-rd traveler both go through the edge 2-6. The 1-st traveler and the 4-th traveler both go through the edge 1-2 and 2-6. The 3-rd traveler and the 4-th traveler both go through the edge 2-6.
8 4 1 1 7 1 2 2 5 4 6 6 3 6 2 6 8 7 8 3 8 2 6 4 1
4
4 seconds
1024 megabytes
['data structures', 'divide and conquer', 'graphs', 'trees', '*3500']
E2. Chiori and Doll Picking (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between easy and hard versions is the constraint of m. You can make hacks only if both versions are solved.Chiori loves dolls and now she is going to decorate her bedroom! As a doll collector, Chiori has got n dolls. The i-th doll has a non-negative integer value a_i (a_i < 2^m, m is given). Chiori wants to pick some (maybe zero) dolls for the decoration, so there are 2^n different picking ways.Let x be the bitwise-xor-sum of values of dolls Chiori picks (in case Chiori picks no dolls x = 0). The value of this picking way is equal to the number of 1-bits in the binary representation of x. More formally, it is also equal to the number of indices 0 \leq i < m, such that \left\lfloor \frac{x}{2^i} \right\rfloor is odd.Tell her the number of picking ways with value i for each integer i from 0 to m. Due to the answers can be very huge, print them by modulo 998\,244\,353.InputThe first line contains two integers n and m (1 \le n \le 2 \cdot 10^5, 0 \le m \le 53)  — the number of dolls and the maximum value of the picking way.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i < 2^m)  — the values of dolls.OutputPrint m+1 integers p_0, p_1, \ldots, p_m  — p_i is equal to the number of picking ways with value i by modulo 998\,244\,353.ExamplesInput 4 4 3 5 8 14 Output 2 2 6 6 0 Input 6 7 11 45 14 9 19 81 Output 1 2 11 20 15 10 5 0
4 4 3 5 8 14
2 2 6 6 0
3 seconds
512 megabytes
['bitmasks', 'brute force', 'combinatorics', 'math', '*3500']