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
H. Submatricestime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given matrix s that contains n rows and m columns. Each element of a matrix is one of the 5 first Latin letters (in upper case).For each k (1 \le k \le 5) calculate the number of submatrices that contain exactly k different letters. Recall that a submatrix of matrix s is a matrix that can be obtained from s after removing several (possibly zero) first rows, several (possibly zero) last rows, several (possibly zero) first columns, and several (possibly zero) last columns. If some submatrix can be obtained from s in two or more ways, you have to count this submatrix the corresponding number of times.InputThe first line contains two integers n and m (1 \le n, m \le 800).Then n lines follow, each containing the string s_i (|s_i| = m) — i-th row of the matrix. OutputFor each k (1 \le k \le 5) print one integer — the number of submatrices that contain exactly k different letters.ExamplesInput 2 3 ABB ABA Output 9 9 0 0 0 Input 6 6 EDCECE EDDCEB ACCECC BAEEDC DDDDEC DDAEAD Output 56 94 131 103 57 Input 3 10 AEAAEEEEEC CEEAAEEEEE CEEEEAACAA Output 78 153 99 0 0
2 3 ABB ABA
9 9 0 0 0
3.5 seconds
256 megabytes
['*special problem', 'bitmasks', 'data structures', 'dp']
G. Biome Maptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp decided to generate a biome map for his game. A map is a matrix divided into cells 1 \times 1. Each cell of the map must contain one of the available biomes.Each biome is defined by two parameters: temperature (an integer from 1 to n) and humidity (an integer from 1 to m). But not for every temperature/humidity combination, a corresponding biome is available.The biome map should be generated according to the following rules: each cell of the map belongs to exactly one biome; each available biome has at least one cell on the map; if two cells of the map are adjacent by the side and they belong to biomes with parameters (t_1, h_1) and (t_2, h_2), respectively, then the equality |t_1-t_2| + |h_1-h_2| = 1 holds; let the number of available biomes be equal to k, then the number of rows and columns of the map (separately) should not exceed k. Help Polycarp generate a biome map that meets all the conditions described above (or report that this is impossible).InputThe first line contains a single integer t (1 \le t \le 20) — the number of test cases.The first line of each test case contains two integers n and m (1 \le n, m \le 10) — maximum temperature and humidity parameters.The following n lines contain m integers each a_{i,1}, a_{i, 2}, \dots, a_{i, m} (0 \le a_{i, j} \le 100), where a_{i, j} — the biome identifier with the parameters (i, j), if a_{i, j} \neq 0, otherwise the biome with such parameters is not available.All biome identifiers are different, and there are at least two biomes available.OutputFor each test case, print the answer in the following format: print -1 in a single line if there is no map that meets all the conditions; otherwise, in the first line, print two integers h and w — the number of rows and columns of the map, respectively. In the following h lines, print w integers — the identifiers of the biomes in the corresponding cells of the map. ExampleInput 4 2 3 0 2 5 0 1 0 3 5 0 3 4 9 11 1 5 0 10 12 0 6 7 0 0 2 2 2 0 0 5 1 2 13 37 Output 1 3 5 2 1 2 8 11 9 4 3 5 1 5 6 12 10 9 4 3 5 6 7 -1 1 2 13 37
4 2 3 0 2 5 0 1 0 3 5 0 3 4 9 11 1 5 0 10 12 0 6 7 0 0 2 2 2 0 0 5 1 2 13 37
1 3 5 2 1 2 8 11 9 4 3 5 1 5 6 12 10 9 4 3 5 6 7 -1 1 2 13 37
2 seconds
256 megabytes
['*special problem', 'constructive algorithms', 'dfs and similar', 'graphs']
F. Binary String Partitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a string t consisting of characters 0 and/or 1 beautiful, if either the number of occurrences of character 0 in this string does not exceed k, or the number of occurrences of characters 1 in this string does not exceed k (or both). For example, if k = 3, the strings 101010, 111, 0, 00000, 1111111000 are beautiful, and the strings 1111110000, 01010101 are not beautiful.You are given a string s. You have to divide it into the minimum possible number of beautiful strings, i. e., find a sequence of strings t_1, t_2, \dots, t_m such that every t_i is beautiful, t_1 + t_2 + \dots + t_m = s (where + is the concatenation operator), and m is minimum possible.For every k from 1 to |s|, find the minimum possible number of strings such that s can be divided into them (i. e. the minimum possible m in the partition).InputThe only line contains one string s (1 \le |s| \le 2 \cdot 10^5). Each character of s is either 0 or 1.OutputPrint |s| integers. The i-th integer should be equal to the minimum number of strings in the partition of s, when k = i.ExamplesInput 00100010 Output 2 1 1 1 1 1 1 1 Input 1001011100 Output 3 2 2 2 1 1 1 1 1 1
00100010
2 1 1 1 1 1 1 1
2 seconds
256 megabytes
['*special problem', 'binary search', 'greedy']
E. Chess Team Formingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is coaching a team for an upcoming game at the chess tournament. A complete team for the tournament should consist of n+1 members.There are n members in his team, the i-th member's skill value is a_i. Polycarp is yet to choose the final member for the team.The opposing team has n+1 members, the j-th member's skill value is b_j.Polycarp has m options for the final player of the team. The k-th of them has a skill value c_k.Before the game starts, Polycarp pairs up the members of his team with the members of the opposing team. Every member of both teams is in exactly one pair. The difficulty of a game for a certain player is the difference between his paired opponent's skill and his own skill. So if the i-th player of the Polycarp's team is paired up with the j-th member of the opposing team, then the difficulty is equal to b_j - a_i. The difficulty of the game for a team is the maximum difficulty of all its players.So, before the game starts, Polycarp wants to pair up the players in such a way that the difficulty of the game for his team is minimized.For each of the m options for the final player print the smallest difficulty of the game for the team Polycarp can achieve.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of members in the Polycarp's team.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the skill value of the i-th player of the Polycarp's team.The third line contains n+1 integers b_1, b_2, \dots, b_{n+1} (1 \le b_j \le 10^9), where b_j is the skill value of the j-th player of the opposing team.The fourth line contains a single integer m (1 \le m \le 2 \cdot 10^5) — the number of options for the final player.The fifth line contains m integers c_1, c_2, \dots, c_m (1 \le c_k \le 10^9), where c_k is the skill value of the k-th of the options for the final player of the Polycarp's team.OutputPrint m integers — the k-th of them should be equal to the smallest difficulty of the game for the team Polycarp can achieve if he picks the k-th option player as the final one.ExamplesInput 5 10 3 4 6 1 9 4 2 5 9 8 5 1 7 6 4 8 Output 4 2 3 4 2 Input 3 5 1 8 8 2 10 1 10 1 2 3 4 5 6 7 8 9 10 Output 3 3 3 3 3 2 2 2 1 0 Input 1 10 10 5 2 5 15 Output 0 -5 NoteIn the first example the optimal pairings for the first three options are the following. Note that there might be multiple valid pairing for the minimum answer.First option:Polycarp's team: 6 1 3 1 10 4Opposing team:  9 4 2 5  9 8The respective difficulties of the game for each player are: 3, 3, -1, 4, -1, 4. The maximum is 4, thus it's the difficulty of the game for the team.Second option:Polycarp's team: 10 4 1 3 7 6Opposing team:   9 4 2 5 9 8Third option:Polycarp's team: 6 3 1 4 10 6Opposing team:  9 4 2 5  9 8
5 10 3 4 6 1 9 4 2 5 9 8 5 1 7 6 4 8
4 2 3 4 2
2 seconds
256 megabytes
['*special problem', 'binary search', 'data structures', 'greedy']
D. String Searchingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array s consisting of n different strings. Each string consists of m lowercase Latin letters.You have to respond to q queries. Each query contains a string t of length m+1. Count the number of indices i, such that the string t can be obtained from the string s_i, if it is allowed to insert one letter in an arbitrary position.InputThe first line contains two integers n and m (1 \le n \le 10^5; 1 \le m \le 10) — the number of strings in the array and the length of each string.The following n lines contain strings s_i. All of the given strings are different.The next line contains a single integer q (1 \le q \le 10^5) — the number of queries.The following q lines contain query strings t of length m + 1.OutputFor each query, print the number of indices i, such that a string from the query can be obtained from the string s_i, if it is allowed to insert one letter in an arbitrary position.ExamplesInput 2 1 a c 4 aa ca mm cf Output 1 2 0 1 Input 6 3 dba abd cbb ada add bdd 5 ccbb abdd adba bada dddd Output 1 3 2 1 0 NoteExplanation of the first test of the example: the string a can be transformed into aa by inserting one letter; both strings a and c can be transformed into ca by inserting one letter; neither a nor c can be transformed into mm by inserting one letter; c can be transformed into cf by inserting one letter.
2 1 a c 4 aa ca mm cf
1 2 0 1
3 seconds
256 megabytes
['*special problem', 'hashing']
C. Sweetstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnya came to her friend's birthday party. There are n delicious sweets on a circle table (for convenience, we will number them from 1 to n in clockwise direction). For each of the sweets, it is known whether Anya likes it or not. Anya decided that she should eat all the sweets that are on the table, and she likes them.However, eating all the sweets in some random order is too boring. Therefore, Anya came up with a game that will make the process of eating sweets more interesting.The game is played according to the following rules: if there are no sweets that Anya likes left on the table, then the game ends; at the very beginning of the game, if there is at least one sweet on the table that Anya wants to eat, she eats the sweet number 1; after Anya has eaten some sweet, she counts k sweets clockwise, starting from the next sweet in the circle, and eats the k-th sweet in the count (if there are less than k sweets in the circle, some sweets can participate in the count more than once, and the last sweet in the count is picked). Obviously, the sweets that have already been eaten do not participate in the count. For example, let 6 sweets be arranged in a circle, Anya likes sweets 4, 5 and 6, k = 4. Then the game goes as follows: initially there are sweets [1, 2, 3, 4, 5, 6] on the table, Anya chooses the sweet number 1. Anya eats the sweet number 1, after that, there are sweets [2, 3, 4, 5, 6] on the table. Anya counts 4 sweets, starting with the 2-nd sweet, and stops at the 5-th sweet. Anya eats the 5-th sweet, after that, there are sweets [2, 3, 4, 6] on the table. Anya counts 4 sweets, starting with the 6-th sweet, and stops at the 4-th sweet. Anya eats the sweet number 4, after that, there are sweets [2, 3, 6] on the table. Anya counts 4 sweets, starting with the 6-th sweet, and stops at the 6-th sweet. Anya eats the sweet number 6, after that, there are sweets [2, 3] on the table. There are no sweets that Anya likes on the table, so the game ends. Your task is to calculate the number of sweets that Anya will eat.InputThe first line contains a single integer t (1 \le t \le 5000) — the number of test cases.The first line of each test case contains two integers n and k (1 \le k \le n \le 5000) — the number of sweets and the parameter k.The next line contains the string s, where s_i = 1 if Anya likes i-th sweet, and s_i = 0 otherwise.It is guaranteed that the sum of n over all test cases does not exceed 5000.OutputFor each test case, print one integer — the number of sweets that Anya will eat.ExampleInput 4 6 4 000111 7 3 0000100 3 2 000 5 1 10011 Output 4 4 0 5 NoteThe first test case of the example is described in the statement.
4 6 4 000111 7 3 0000100 3 2 000 5 1 10011
4 4 0 5
3 seconds
256 megabytes
['*special problem', 'data structures', 'implementation']
B. Nearest Point Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend has created a nearest point function. For a given array of integer points x (sorted in ascending order, without any duplicates) and a point y it can find the nearest point from x to the point y. In other words, it will find such a point x_i that |y - x_i| is the minimum possible, where |a| is the absolute value of a.For example, if x = [1, 2, 5, 7, 9, 11], the answer for y=3 will be 2, the answer for y=5 will be 5 and the answer for y=100 will be 11.This function is a bit buggy, though. If there are several nearest points to the given one, the function crashes. For example, if x = [1, 2, 5, 7, 9, 11] (as above) and y=6, the function will crash, since points 5 and 7 are both the nearest points for 6.Your task is, for a given array of integer points x (sorted in ascending order, without any duplicates), determine if it is possible to cause the function to crash by choosing some integer point y.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.The first line of the test case contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of points in the array x.The second line of the test case contains n integers x_1, x_2, \ldots, x_n (1 \le x_i \le 10^9), where x_i is the i-th point in the array x.All points in the array x are distinct, and the array x is sorted in ascending order (in other words, x_1 < x_2 < \ldots < x_n).The sum of n over the test cases in the input does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print YES if it is possible to find some integer point y that will crash the function and NO otherwise.ExampleInput 7 2 1 3 2 1 100 3 1 50 101 2 1 1000000000 2 1 999999999 6 1 2 5 7 9 11 6 1 2 5 8 9 12 Output YES NO NO NO YES YES NO NoteIn the first test case of the example, the function crashes if y = 2 is chosen.In the fifth test case of the example, the function crashes if y = 500000000 is chosen.In the sixth test case of the example, the function crashes if y = 10 is chosen.
7 2 1 3 2 1 100 3 1 50 101 2 1 1000000000 2 1 999999999 6 1 2 5 7 9 11 6 1 2 5 8 9 12
YES NO NO NO YES YES NO
1 second
256 megabytes
['*special problem', 'implementation']
A. Travel to Bertowntime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVika has decided to go on a trip to Bertown. She comes to Bertown on the k-th day. Vika does not want to spend money on hotels, fortunately she has n friends who live in Bertown and allow Vika to stay at their houses. The i-th friend told Vika that she could stay at their house from the l_i-th day till the r_i-th day, inclusive.Vika decided that she would stay at no more than one friend's house. Help Vika determine the maximum number of days that she will be able to stay in Bertown.InputThe first line contains a single integer t (1 \le t \le 500) — the number of test cases.The first line of each test case contains two integers n and k (1 \le n, k \le 100) — the number of Vika's friends and the day when Vika comes to Bertown.Then follow n lines, each containing two integers l_i and r_i (1 \le l_i \le r_i \le 100) denoting the period when Vika can stay at the i-th friend's house.OutputFor each test case, output a single integer — the maximum number of days that Vika can stay in Bertown (or 0 if none of Vika's friends can host her on day k).ExampleInput 3 3 3 1 4 2 6 4 10 2 4 2 3 5 8 2 4 4 4 1 3 Output 4 0 1 NoteIn the first example, Vika can stay at the 2-nd friend's house from 3-rd to 6-th day.In the second example, none of Vika's friends can host her on the 4-th day.In the third example, Vika can stay at the 1-st friend's house, but only for the 4-th day.
3 3 3 1 4 2 6 4 10 2 4 2 3 5 8 2 4 4 4 1 3
4 0 1
2 seconds
256 megabytes
['*special problem', 'implementation', 'math']
F. Prefixes and Suffixestime limit per test2.0 smemory limit per test512 MBinputstandard inputoutputstandard outputIvan wants to play a game with you. He picked some string s of length n consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from 1 to n-1), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given 2n-2 strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!InputThe first line of the input contains one integer number n (2 \le n \le 100) — the length of the guessed string s.The next 2n-2 lines are contain prefixes and suffixes, one per line. Each of them is the string of length from 1 to n-1 consisting only of lowercase Latin letters. They can be given in arbitrary order.It is guaranteed that there are exactly 2 strings of each length from 1 to n-1. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length n.OutputPrint one string of length 2n-2 — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The i-th character of this string should be 'P' if the i-th of the input strings is the prefix and 'S' otherwise.If there are several possible answers, you can print any.ExamplesInput 5 ba a abab a aba baba ab aba Output SPPSPSPS Input 3 a aa aa a Output PPSS Input 2 a c Output PS NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable.
5 ba a abab a aba baba ab aba
SPPSPSPS
2.0 s
512 MB
['*special problem', 'strings']
E. Good Arraytime limit per test2.0 smemory limit per test512 MBinputstandard inputoutputstandard outputLet's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array a=[1, 3, 3, 7] is good because there is the element a_4=7 which equals to the sum 1 + 3 + 3.You are given an array a consisting of n integers. Your task is to print all indices j of this array such that after removing the j-th element from the array it will be good (let's call such indices nice).For example, if a=[8, 3, 5, 2], the nice indices are 1 and 4: if you remove a_1, the array will look like [3, 5, 2] and it is good; if you remove a_4, the array will look like [8, 3, 5] and it is good. You have to consider all removals independently, i. e. remove the element, check if the resulting array is good, and return the element into the array.InputThe first line of the input contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of elements in the array a.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6) — elements of the array a.OutputIn the first line print one integer k — the number of indices j of the array a such that after removing the j-th element from the array it will be good (i.e. print the number of the nice indices).In the second line print k distinct integers j_1, j_2, \dots, j_k in any order — nice indices of the array a.If there are no such indices in the array a, just print 0 in the first line and leave the second line empty or do not print it at all.ExamplesInput 5 2 5 1 2 2 Output 3 4 1 5Input 4 8 3 5 2 Output 2 1 4 Input 5 2 1 2 4 3 Output 0 NoteIn the first example you can remove any element with the value 2 so the array will look like [5, 1, 2, 2]. The sum of this array is 10 and there is an element equals to the sum of remaining elements (5 = 1 + 2 + 2).In the second example you can remove 8 so the array will look like [3, 5, 2]. The sum of this array is 10 and there is an element equals to the sum of remaining elements (5 = 3 + 2). You can also remove 2 so the array will look like [8, 3, 5]. The sum of this array is 16 and there is an element equals to the sum of remaining elements (8 = 3 + 5).In the third example you cannot make the given array good by removing exactly one element.
5 2 5 1 2 2
3 4 1 5
2.0 s
512 MB
['*special problem']
D. Teams Formingtime limit per test2.0 smemory limit per test512 MBinputstandard inputoutputstandard outputThere are n students in a university. The number of students is even. The i-th student has programming skill equal to a_i. The coach wants to form \frac{n}{2} teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equal (otherwise they cannot understand each other and cannot form a team).Students can solve problems to increase their skill. One solved problem increases the skill by one.The coach wants to know the minimum total number of problems students should solve to form exactly \frac{n}{2} teams (i.e. each pair of students should form a team). Your task is to find this number.InputThe first line of the input contains one integer n (2 \le n \le 100) — the number of students. It is guaranteed that n is even.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100), where a_i is the skill of the i-th student.OutputPrint one number — the minimum total number of problems students should solve to form exactly \frac{n}{2} teams.ExamplesInput 6 5 10 2 3 14 5 Output 5 Input 2 1 100 Output 99 NoteIn the first example the optimal teams will be: (3, 4), (1, 6) and (2, 5), where numbers in brackets are indices of students. Then, to form the first team the third student should solve 1 problem, to form the second team nobody needs to solve problems and to form the third team the second student should solve 4 problems so the answer is 1 + 4 = 5.In the second example the first student should solve 99 problems to form a team with the second one.
6 5 10 2 3 14 5
5
2.0 s
512 MB
['*special problem', 'sortings']
C. Uniform Stringtime limit per test2.0 smemory limit per test512 MBinputstandard inputoutputstandard outputYou are given two integers n and k.Your task is to construct such a string s of length n that for each i from 1 to k there is at least one i-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minimal frequency of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print any.You have to answer t independent queries.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of queries.The next t lines are contain queries, one per line. The i-th line contains two integers n_i and k_i (1 \le n_i \le 100, 1 \le k_i \le min(n_i, 26)) — the length of the string in the i-th query and the number of characters in the i-th query.OutputPrint t lines. In the i-th line print the answer to the i-th query: any string s_i satisfying the conditions in the problem statement with constraints from the i-th query.ExampleInput 3 7 3 4 4 6 2 Output cbcacab abcd baabab NoteIn the first example query the maximum possible minimal frequency is 2, it can be easily seen that the better answer doesn't exist. Other examples of correct answers: "cbcabba", "ccbbaaa" (any permutation of given answers is also correct).In the second example query any permutation of first four letters is acceptable (the maximum minimal frequency is 1).In the third example query any permutation of the given answer is acceptable (the maximum minimal frequency is 3).
3 7 3 4 4 6 2
cbcacab abcd baabab
2.0 s
512 MB
['*special problem', 'implementation']
B. Frog Jumpingtime limit per test2.0 smemory limit per test512 MBinputstandard inputoutputstandard outputA frog is currently at the point 0 on a coordinate axis Ox. It jumps by the following algorithm: the first jump is a units to the right, the second jump is b units to the left, the third jump is a units to the right, the fourth jump is b units to the left, and so on.Formally: if the frog has jumped an even number of times (before the current jump), it jumps from its current position x to position x+a; otherwise it jumps from its current position x to position x-b. Your task is to calculate the position of the frog after k jumps.But... One more thing. You are watching t different frogs so you have to answer t independent queries.InputThe first line of the input contains one integer t (1 \le t \le 1000) — the number of queries.Each of the next t lines contain queries (one query per line).The query is described as three space-separated integers a, b, k (1 \le a, b, k \le 10^9) — the lengths of two types of jumps and the number of jumps, respectively.OutputPrint t integers. The i-th integer should be the answer for the i-th query.ExampleInput 6 5 2 3 100 1 4 1 10 5 1000000000 1 6 1 1 1000000000 1 1 999999999 Output 8 198 -17 2999999997 0 1 NoteIn the first query frog jumps 5 to the right, 2 to the left and 5 to the right so the answer is 5 - 2 + 5 = 8.In the second query frog jumps 100 to the right, 1 to the left, 100 to the right and 1 to the left so the answer is 100 - 1 + 100 - 1 = 198.In the third query the answer is 1 - 10 + 1 - 10 + 1 = -17.In the fourth query the answer is 10^9 - 1 + 10^9 - 1 + 10^9 - 1 = 2999999997.In the fifth query all frog's jumps are neutralized by each other so the answer is 0.The sixth query is the same as the fifth but without the last jump so the answer is 1.
6 5 2 3 100 1 4 1 10 5 1000000000 1 6 1 1 1000000000 1 1 999999999
8 198 -17 2999999997 0 1
2.0 s
512 MB
['*special problem', 'math']
A. A+B (Trial Problem)time limit per test2.0 smemory limit per test512 MBinputstandard 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 41 5314 15-99 99123 987Output 6 329 0 1110
41 5314 15-99 99123 987
6 329 0 1110
2.0 s
512 MB
['*special problem']
E3. Сортировка слияниемограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводРассмотрим следующий код сортировки слиянием на языке Python: def sort(a): n = len(a) b = [0 for i in range(n)] log = [] def mergeSort(l, r): if r - l <= 1: return m = (l + r) >> 1 mergeSort(l, m) mergeSort(m, r) i, j, k = l, m, l while i < m and j < r: if a[i] < a[j]: log.append('0') b[k] = a[i] i += 1 else: log.append('1') b[k] = a[j] j += 1 k += 1 while i < m: b[k] = a[i] i += 1 k += 1 while j < r: b[k] = a[j] j += 1 k += 1 for p in range(l, r): a[p] = b[p] mergeSort(0, n) return "".join(log)Как можно заметить, этот код использует логирование — важнейший инструмент разработки.Старший разработчик ВКонтакте Вася сгенерировал перестановку a (массив из n различных целых чисел от 1 до n), дал её на вход функции sort и получил на выходе строку s. На следующий день строку s Вася нашёл, а перестановка a потерялась. Вася хочет восстановить любую перестановку a такую, что вызов функции sort от неё даст ту же строку s. Помогите ему!Входные данныеВвод содержит непустую строку s, состоящую из символов 0 и 1. В этой версии задачи для любого теста существует перестановка длины не более 10^5, удовлетворяющая условию. Тем не менее, ваш ответ может иметь любую длину, в том числе превышающую 10^5.Выходные данныеВ первой строке выведите целое число n — длину перестановки.Во второй строке выведите n различных целых чисел a_0, a_1, \ldots, a_{n-1} (1 \le a_i \le n) — элементы перестановки.Если существует несколько вариантов ответа, выведите любой из них.ПримерыВходные данные 00000000000000000000000000000000 Выходные данные 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Входные данные 11111111111111111111111111111111 Выходные данные 16 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Входные данные 101011010001100100011011001111011000011110010 Выходные данные 16 13 6 1 7 12 5 4 15 14 16 10 11 3 8 9 2
Входные данные 00000000000000000000000000000000
Выходные данные 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', 'binary search']
E2. Сортировка слияниемограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводРассмотрим следующий код сортировки слиянием на языке Python: def sort(a): n = len(a) b = [0 for i in range(n)] log = [] def mergeSort(l, r): if r - l <= 1: return m = (l + r) >> 1 mergeSort(l, m) mergeSort(m, r) i, j, k = l, m, l while i < m and j < r: if a[i] < a[j]: log.append('0') b[k] = a[i] i += 1 else: log.append('1') b[k] = a[j] j += 1 k += 1 while i < m: b[k] = a[i] i += 1 k += 1 while j < r: b[k] = a[j] j += 1 k += 1 for p in range(l, r): a[p] = b[p] mergeSort(0, n) return "".join(log)Как можно заметить, этот код использует логирование — важнейший инструмент разработки.Старший разработчик ВКонтакте Вася сгенерировал перестановку a (массив из n различных целых чисел от 1 до n), дал её на вход функции sort и получил на выходе строку s. На следующий день строку s Вася нашёл, а перестановка a потерялась. Вася хочет восстановить любую перестановку a такую, что вызов функции sort от неё даст ту же строку s. Помогите ему!Входные данныеВвод содержит непустую строку s, состоящую из символов 0 и 1. В этой версии задачи для любого теста существует перестановка длины не более 10^3, удовлетворяющая условию. Тем не менее, ваш ответ может иметь любую длину, в том числе превышающую 10^3.Выходные данныеВ первой строке выведите целое число n — длину перестановки.Во второй строке выведите n различных целых чисел a_0, a_1, \ldots, a_{n-1} (1 \le a_i \le n) — элементы перестановки.Если существует несколько вариантов ответа, выведите любой из них.ПримерыВходные данные 00000000000000000000000000000000 Выходные данные 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Входные данные 11111111111111111111111111111111 Выходные данные 16 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Входные данные 101011010001100100011011001111011000011110010 Выходные данные 16 13 6 1 7 12 5 4 15 14 16 10 11 3 8 9 2
Входные данные 00000000000000000000000000000000
Выходные данные 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', '*special problem', 'brute force']
E1. Сортировка слияниемограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводРассмотрим следующий код сортировки слиянием на языке Python: def sort(a): n = len(a) b = [0 for i in range(n)] log = [] def mergeSort(l, r): if r - l <= 1: return m = (l + r) >> 1 mergeSort(l, m) mergeSort(m, r) i, j, k = l, m, l while i < m and j < r: if a[i] < a[j]: log.append('0') b[k] = a[i] i += 1 else: log.append('1') b[k] = a[j] j += 1 k += 1 while i < m: b[k] = a[i] i += 1 k += 1 while j < r: b[k] = a[j] j += 1 k += 1 for p in range(l, r): a[p] = b[p] mergeSort(0, n) return "".join(log)Как можно заметить, этот код использует логирование — важнейший инструмент разработки.Старший разработчик ВКонтакте Вася сгенерировал перестановку a (массив из n различных целых чисел от 1 до n), дал её на вход функции sort и получил на выходе строку s. На следующий день строку s Вася нашёл, а перестановка a потерялась. Вася хочет восстановить любую перестановку a такую, что вызов функции sort от неё даст ту же строку s. Помогите ему!Входные данныеВвод содержит непустую строку s, состоящую из символов 0 и 1. В этой версии задачи для любого теста существует перестановка длины 16, удовлетворяющая условию. Тем не менее, ваш ответ может иметь любую длину, в том числе отличную от 16.Выходные данныеВ первой строке выведите целое число n — длину перестановки.Во второй строке выведите n различных целых чисел a_0, a_1, \ldots, a_{n-1} (1 \le a_i \le n) — элементы перестановки.Если существует несколько вариантов ответа, выведите любой из них.ПримерыВходные данные 00000000000000000000000000000000 Выходные данные 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Входные данные 11111111111111111111111111111111 Выходные данные 16 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Входные данные 101011010001100100011011001111011000011110010 Выходные данные 16 13 6 1 7 12 5 4 15 14 16 10 11 3 8 9 2
Входные данные 00000000000000000000000000000000
Выходные данные 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem']
D. Редактируем Зингер | colorограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводНемногие знают, что сотрудники ВКонтакте могут менять цвет подсветки в куполе знаменитого Дома Зингера, где расположена штаб-квартира ВКонтакте. Для этого нужно всего лишь отправить сообщение с цветом в специальный чат «Зингер | color», а бот его распознает и сменит подсветку. При этом на время городских мероприятий смена цвета блокируется.Формально, бот обрабатывает три типа сообщений: lock: заблокировать изменение цвета. Если оно и так заблокировано на данный момент, сообщение игнорируется. unlock: разблокировать изменение цвета. Если оно и так разблокировано на данный момент, сообщение игнорируется. red / orange / yellow / green / blue / indigo / violet: изменить цвет купола на заданный, если изменение цвета на данный момент не заблокировано. Вам дана история сообщений, полученных ботом, в хронологическом порядке. Считайте, что перед получением первого сообщения купол подсвечивается голубым (blue), а изменение цвета не заблокировано.В качестве эксперимента было решено поддержать в боте эффективную обработку редактирования сообщений. Вам дана последовательность пар вида (i, msg), означающих, что i-е в хронологическом порядке сообщение было отредактировано и теперь имеет вид msg. Обратите внимание, что редактироваться может любое сообщение, и при редактировании сообщения бот должен обработать всю историю сообщений заново (в частности, перед обработкой первого сообщения цвет купола голубой, а изменение цвета не заблокировано).Определите, какой цвет будет у купола Дома Зингера до первой операции редактирования, а также после каждой операции редактирования.Входные данныеВ первой строке задано одно целое число n (1 \le n \le 10^5) — число сообщений, полученных ботом.В следующих n строках заданы сообщения, полученные ботом, в хронологическом порядке, по одному сообщению в строке. Каждое сообщение — строка из следующего набора: lock, unlock, red, orange, yellow, green, blue, indigo, violet. Сообщения пронумерованы от 1 до n.В следующей строке задано одно целое число t (1 \le t \le 10^5) — число операций редактирования сообщений.В следующих t строках заданы операции редактирования в хронологическом порядке, по одной в строке. Каждая операция — пара из номера сообщения i (1 \le i \le n) и его нового содержимого msg, также принадлежащего набору lock, unlock, red, orange, yellow, green, blue, indigo, violet.Выходные данныеВыведите t+1 строку: цвет купола до первой операции редактирования, а также после каждой операции редактирования в хронологическом порядке.ПримерыВходные данные 7 red violet unlock red orange lock indigo 6 5 green 6 lock 6 yellow 4 lock 1 lock 5 unlock Выходные данные orange green green indigo violet blue indigo Входные данные 1 red 8 1 lock 1 unlock 1 blue 1 unlock 1 unlock 1 lock 1 yellow 1 lock Выходные данные red blue blue blue blue blue blue yellow blue
Входные данные 7 red violet unlock red orange lock indigo 6 5 green 6 lock 6 yellow 4 lock 1 lock 5 unlock
Выходные данные orange green green indigo violet blue indigo
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', '*special problem']
C. Симметричный амфитеатрограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВсе готовятся к VK Fest 2021! Для того, чтобы зрителям была лучше видна главная сцена, планируется построить амфитеатр. В этой задаче мы будем рассматривать его сбоку — схематично он будет иметь форму лестницы из n одинаковых квадратов. Лестница — это одна или более башен квадратов, выстроенных в ряд, где высоты башен невозрастают слева направо.На следующем рисунке можно видеть три разные фигуры из 12 квадратов. Первые две фигуры — лестницы, а третья — нет. Из эстетических соображений было решено, что амфитеатр должен быть симметричным. Формально, амфитеатр называется симметричным, если при отражении его схемы относительно прямой x = y получается тот же самый рисунок (где ось x направлена слева направо, а ось y — снизу вверх). Например, первая лестница на рисунке выше — симметричная, а вторая — нет. Кроме того, амфитеатр должен быть максимально компактным — а именно, сторона минимального квадрата, внутрь которого можно его поместить, должна быть как можно меньше.По заданному числу n нарисуйте схему амфитеатра из ровно n квадратов, удовлетворяющую всем условиям.Входные данныеВ единственной строке задано одно целое число n (1 \le n \le 100) — число квадратов, из которых нужно составить схему амфитеатра.Выходные данныеЕсли не существует схемы амфитеатра из n квадратов, выведите единственное число -1.Иначе в первой строке выведите целое число m — минимальное возможное число строк и столбцов в схеме амфитеатра. Далее выведите m строк, описывающих схему. Каждая строка должна содержать ровно m символов 'o' (строчная латинская буква) или '.', где 'o' описывает построенный квадрат, а '.' — пустое место. Схема амфитеатра должна состоять ровно из n символов 'o'. Ячейка в левом нижнем углу должна содержать квадрат. Если возможных ответов с минимальным m несколько, выведите любой из них.ПримерыВходные данные 3 Выходные данные 2 o. oo Входные данные 17 Выходные данные 5 o.... ooo.. oooo. oooo. ooooo
Входные данные 3
Выходные данные 2 o. oo
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', 'constructive algorithms', 'dp']
B2. Мониторингограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВКонтакте открыла второй штаб в Санкт-Петербурге! Вы не преминули возможностью сменить обстановку и решили переехать из офиса в Доме Зингера в офис на Красном мосту.Для комфортной работы вам потребуются два монитора с одинаковой высотой, чтобы изображение на них выглядело единым целым. На складе офиса на Красном мосту есть n мониторов, i-й из них имеет ширину w_i и высоту h_i. Любой монитор можно повернуть на 90 градусов, и тогда он будет иметь ширину h_i и высоту w_i.Назовём неупорядоченную пару из двух различных мониторов подходящей, если можно их повернуть так, чтобы они имели одинаковую высоту. Любой из мониторов в паре можно как повернуть относительно исходной ориентации, так и не поворачивать.Подсчитайте подходящие пары мониторов.Входные данныеВ первой строке задано одно целое число n — число мониторов на складе.В каждой из следующих n строк заданы два целых числа w_i и h_i (1 \le w_i, h_i \le 10^9) — ширина и высота i-го монитора. Обратите внимание, что мониторы могут быть квадратными (w_i = h_i), а размеры разных мониторов могут совпадать.В этой версии задачи 2 \le n \le 10^5.Выходные данныеВыведите число подходящих пар мониторов.ПримерыВходные данные 5 3 2 2 2 5 5 3 5 4 3 Выходные данные 5 Входные данные 7 10 10 10 20 20 10 10 20 10 20 10 10 20 10 Выходные данные 21 ПримечаниеВ первом примере подходящими являются пары мониторов с номерами (1, 2), (1, 4), (1, 5), (3, 4), (4, 5).Во втором примере все пары мониторов — подходящие.
Входные данные 5 3 2 2 2 5 5 3 5 4 3
Выходные данные 5
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem']
B1. Мониторингограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВКонтакте открыла второй штаб в Санкт-Петербурге! Вы не преминули возможностью сменить обстановку и решили переехать из офиса в Доме Зингера в офис на Красном мосту.Для комфортной работы вам потребуются два монитора с одинаковой высотой, чтобы изображение на них выглядело единым целым. На складе офиса на Красном мосту есть n мониторов, i-й из них имеет ширину w_i и высоту h_i. Любой монитор можно повернуть на 90 градусов, и тогда он будет иметь ширину h_i и высоту w_i.Назовём неупорядоченную пару из двух различных мониторов подходящей, если можно их повернуть так, чтобы они имели одинаковую высоту. Любой из мониторов в паре можно как повернуть относительно исходной ориентации, так и не поворачивать.Подсчитайте подходящие пары мониторов.Входные данныеВ первой строке задано одно целое число n — число мониторов на складе.В каждой из следующих n строк заданы два целых числа w_i и h_i (1 \le w_i, h_i \le 10^9) — ширина и высота i-го монитора. Обратите внимание, что мониторы могут быть квадратными (w_i = h_i), а размеры разных мониторов могут совпадать.В этой версии задачи 2 \le n \le 10^3.Выходные данныеВыведите число подходящих пар мониторов.ПримерыВходные данные 5 3 2 2 2 5 5 3 5 4 3 Выходные данные 5 Входные данные 7 10 10 10 20 20 10 10 20 10 20 10 10 20 10 Выходные данные 21 ПримечаниеВ первом примере подходящими являются пары мониторов с номерами (1, 2), (1, 4), (1, 5), (3, 4), (4, 5).Во втором примере все пары мониторов — подходящие.
Входные данные 5 3 2 2 2 5 5 3 5 4 3
Выходные данные 5
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', '*special problem']
A. Зингер | colorограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводНемногие знают, что сотрудники ВКонтакте могут менять цвет подсветки в куполе знаменитого Дома Зингера, где расположена штаб-квартира ВКонтакте. Для этого нужно всего лишь отправить сообщение с цветом в специальный чат «Зингер | color», а бот его распознает и сменит подсветку. При этом на время городских мероприятий смена цвета блокируется.Формально, бот обрабатывает три типа сообщений: lock: заблокировать изменение цвета. Если оно и так заблокировано на данный момент, сообщение игнорируется. unlock: разблокировать изменение цвета. Если оно и так разблокировано на данный момент, сообщение игнорируется. red / orange / yellow / green / blue / indigo / violet: изменить цвет купола на заданный, если изменение цвета на данный момент не заблокировано. Вам дана история сообщений, полученных ботом, в хронологическом порядке. Считайте, что перед получением первого сообщения купол подсвечивается голубым (blue), а изменение цвета не заблокировано.Определите, какой цвет будет у купола Дома Зингера после обработки этих сообщений.Входные данныеВ первой строке задано одно целое число n (1 \le n \le 100) — число сообщений, полученных ботом.В следующих n строках заданы сообщения, полученные ботом, в хронологическом порядке, по одному сообщению в строке. Каждое сообщение — строка из следующего набора: lock, unlock, red, orange, yellow, green, blue, indigo, violet.Выходные данныеВыведите цвет купола после обработки сообщений ботом.ПримерыВходные данные 7 red violet unlock red orange lock indigo Выходные данные orange Входные данные 5 lock unlock lock unlock unlock Выходные данные blue
Входные данные 7 red violet unlock red orange lock indigo
Выходные данные orange
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', 'implementation']
H. Turing's Awardtime limit per test10 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlan Turing is standing on a tape divided into cells that is infinite in both directions.Cells are numbered with consecutive integers from left to right. Alan is initially standing in cell 0. Every cell x has cell x - 1 on the left and cell x + 1 on the right.Each cell can either contain an integer or be empty. Initially all cells are empty.Alan is given a permutation a_1, a_2, \ldots, a_n of integers from 1 to n that was chosen uniformly at random among all permutations of length n.At time 1, integer a_1 is written down into cell 0 where Alan is located.At each time i from 2 to n inclusive, the following happens. First, Alan decides whether to stay in the same cell he's currently in, move to the neighboring cell on the left, or move to the neighboring cell on the right. After that, integer a_i is written down into the cell where Alan is located. If that cell already contained some integer, the old integer is overwritten and irrelevant from that moment on.Once a_n is written down into some cell at time n, sequence b of all integers contained in the cells from left to right is formed. Empty cells are ignored.Turing's award is equal to the length of the longest increasing subsequence of sequence b.Help Alan and determine the largest possible value of his award if he acts optimally.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). Description of the test cases follows.Each test case is given in two lines. The first line of each test case contains a single integer n (2 \le n \le 15\,000) — the length of the permutation given to Alan.The second line contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of the permutation.It is guaranteed that the permutation was chosen uniformly at random among all permutations of the corresponding length.The sum of n over all test cases does not exceed 15\,000.OutputFor each test case output a single integer — the largest possible value of Turing's award.Hacks are not allowed for this problem.ExampleInput 4 2 1 2 4 4 1 2 3 7 3 6 5 7 4 1 2 7 5 2 3 7 6 1 4 Output 2 3 4 4 NoteLongest increasing subsequence of sequence b is the longest increasing sequence that can be obtained from b by deletion of several (possibly, zero or all) elements.In the first test case, Alan can make a decision only at time 2. If Alan stays in cell 0, sequence b will be equal to [2]. If Alan moves to the left, to cell -1, sequence b will be equal to [2, 1]. If Alan moves to the right, to cell 1, sequence b will be equal to [1, 2]. Only in the last case the length of the longest increasing subsequence of b is 2, therefore, the answer is equal to 2.In the second test case, one of the optimal sequences of actions looks as follows: move to the left at times 2 and 3, and move to the right at time 4. Then sequence b will be equal to [2, 3, 4], and the length of its longest increasing subsequence is 3.In the third test case, one of the best ways is to always move to the left. Then sequence b will be equal to [2, 1, 4, 7, 5, 6, 3], and the length of its longest increasing subsequence is 4.In the fourth test case, one of the best ways is to move to the right four times, then move to the left once, and stay in the same cell once. Sequence b will be equal to [5, 2, 3, 4, 6].
4 2 1 2 4 4 1 2 3 7 3 6 5 7 4 1 2 7 5 2 3 7 6 1 4
2 3 4 4
10 seconds
512 megabytes
['data structures', 'dp', '*3400']
G. What a Reversaltime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have two strings a and b of equal length n consisting of characters 0 and 1, and an integer k.You need to make strings a and b equal.In one step, you can choose any substring of a containing exactly k characters 1 (and arbitrary number of characters 0) and reverse it. Formally, if a = a_1 a_2 \ldots a_n, you can choose any integers l and r (1 \le l \le r \le n) such that there are exactly k ones among characters a_l, a_{l+1}, \ldots, a_r, and set a to a_1 a_2 \ldots a_{l-1} a_r a_{r-1} \ldots a_l a_{r+1} a_{r+2} \ldots a_n.Find a way to make a equal to b using at most 4n reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 2000). Description of the test cases follows.Each test case consists of three lines. The first line of each test case contains two integers n and k (1 \le n \le 2000; 0 \le k \le n).The second line contains string a of length n.The third line contains string b of the same length. Both strings consist of characters 0 and 1.It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case, if it's impossible to make a equal to b in at most 4n reversals, print a single integer -1.Otherwise, print an integer m (0 \le m \le 4n), denoting the number of reversals in your sequence of steps, followed by m pairs of integers l_i, r_i (1 \le l_i \le r_i \le n), denoting the boundaries of the substrings of a to be reversed, in chronological order. Each substring must contain exactly k ones at the moment of reversal.Note that m doesn't have to be minimized. If there are multiple answers, print any.ExampleInput 6 6 1 101010 010101 6 3 101010 010101 6 0 101010 010101 6 6 101010 010101 4 2 0000 1111 9 2 011100101 101001011 Output 3 1 2 3 4 5 6 1 1 6 -1 -1 -1 5 4 8 8 9 3 6 1 4 3 6 NoteIn the first test case, after the first reversal a = 011010, after the second reversal a = 010110, after the third reversal a = 010101.
6 6 1 101010 010101 6 3 101010 010101 6 0 101010 010101 6 6 101010 010101 4 2 0000 1111 9 2 011100101 101001011
3 1 2 3 4 5 6 1 1 6 -1 -1 -1 5 4 8 8 9 3 6 1 4 3 6
2 seconds
512 megabytes
['constructive algorithms', '*3300']
F. Bingotime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGetting ready for VK Fest 2021, you prepared a table with n rows and n columns, and filled each cell of this table with some event related with the festival that could either happen or not: for example, whether you will win a prize on the festival, or whether it will rain.Forecasting algorithms used in VK have already estimated the probability for each event to happen. Event in row i and column j will happen with probability a_{i, j} \cdot 10^{-4}. All of the events are mutually independent.Let's call the table winning if there exists a line such that all n events on it happen. The line could be any horizontal line (cells (i, 1), (i, 2), \ldots, (i, n) for some i), any vertical line (cells (1, j), (2, j), \ldots, (n, j) for some j), the main diagonal (cells (1, 1), (2, 2), \ldots, (n, n)), or the antidiagonal (cells (1, n), (2, n - 1), \ldots, (n, 1)).Find the probability of your table to be winning, and output it modulo 31\,607 (see Output section).InputThe first line contains a single integer n (2 \le n \le 21) — the dimensions of the table.The i-th of the next n lines contains n integers a_{i, 1}, a_{i, 2}, \ldots, a_{i, n} (0 < a_{i, j} < 10^4). The probability of event in cell (i, j) to happen is a_{i, j} \cdot 10^{-4}.OutputPrint the probability that your table will be winning, modulo 31\,607.Formally, let M = 31\,607. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExamplesInput 2 5000 5000 5000 5000 Output 5927 Input 2 2500 6000 3000 4000 Output 24812 Input 3 1000 2000 3000 4000 5000 6000 7000 8000 9000 Output 25267 NoteIn the first example, any two events form a line, and the table will be winning if any two events happen. The probability of this is \frac{11}{16}, and 5927 \cdot 16 \equiv 11 \pmod{31\,607}.
2 5000 5000 5000 5000
5927
7 seconds
512 megabytes
['bitmasks', 'combinatorics', 'dp', 'math', 'probabilities', '*2600']
E. Minimaxtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPrefix function of string t = t_1 t_2 \ldots t_n and position i in it is defined as the length k of the longest proper (not equal to the whole substring) prefix of substring t_1 t_2 \ldots t_i which is also a suffix of the same substring.For example, for string t = abacaba the values of the prefix function in positions 1, 2, \ldots, 7 are equal to [0, 0, 1, 0, 1, 2, 3].Let f(t) be equal to the maximum value of the prefix function of string t over all its positions. For example, f(abacaba) = 3.You are given a string s. Reorder its characters arbitrarily to get a string t (the number of occurrences of any character in strings s and t must be equal). The value of f(t) must be minimized. Out of all options to minimize f(t), choose the one where string t is the lexicographically smallest.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.The only line of each test case contains string s (1 \le |s| \le 10^5) consisting of lowercase English letters.It is guaranteed that the sum of lengths of s over all test cases does not exceed 10^5.OutputFor each test case print a single string t.The multisets of letters in strings s and t must be equal. The value of f(t), the maximum of prefix functions in string t, must be as small as possible. String t must be the lexicographically smallest string out of all strings satisfying the previous conditions.ExampleInput 3 vkcup abababa zzzzzz Output ckpuv aababab zzzzzz NoteA string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.In the first test case, f(t) = 0 and the values of prefix function are [0, 0, 0, 0, 0] for any permutation of letters. String ckpuv is the lexicographically smallest permutation of letters of string vkcup.In the second test case, f(t) = 1 and the values of prefix function are [0, 1, 0, 1, 0, 1, 0].In the third test case, f(t) = 5 and the values of prefix function are [0, 1, 2, 3, 4, 5].
3 vkcup abababa zzzzzz
ckpuv aababab zzzzzz
2 seconds
512 megabytes
['constructive algorithms', 'greedy', 'strings', '*2100']
D. Secret Santatime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEvery December, VK traditionally holds an event for its employees named "Secret Santa". Here's how it happens.n employees numbered from 1 to n take part in the event. Each employee i is assigned a different employee b_i, to which employee i has to make a new year gift. Each employee is assigned to exactly one other employee, and nobody is assigned to themselves (but two employees may be assigned to each other). Formally, all b_i must be distinct integers between 1 and n, and for any i, b_i \ne i must hold.The assignment is usually generated randomly. This year, as an experiment, all event participants have been asked who they wish to make a gift to. Each employee i has said that they wish to make a gift to employee a_i.Find a valid assignment b that maximizes the number of fulfilled wishes of the employees.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.Each test case consists of two lines. The first line contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of participants of the event.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n; a_i \ne i) — wishes of the employees in order from 1 to n.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print two lines.In the first line, print a single integer k (0 \le k \le n) — the number of fulfilled wishes in your assignment.In the second line, print n distinct integers b_1, b_2, \ldots, b_n (1 \le b_i \le n; b_i \ne i) — the numbers of employees assigned to employees 1, 2, \ldots, n.k must be equal to the number of values of i such that a_i = b_i, and must be as large as possible. If there are multiple answers, print any.ExampleInput 2 3 2 1 2 7 6 4 6 2 4 5 6 Output 2 3 1 2 4 6 4 7 2 3 5 1 NoteIn the first test case, two valid assignments exist: [3, 1, 2] and [2, 3, 1]. The former assignment fulfills two wishes, while the latter assignment fulfills only one. Therefore, k = 2, and the only correct answer is [3, 1, 2].
2 3 2 1 2 7 6 4 6 2 4 5 6
2 3 1 2 4 6 4 7 2 3 5 1
2 seconds
512 megabytes
['constructive algorithms', 'flows', 'graphs', 'greedy', 'math', '*1600']
C. Pursuittime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou and your friend Ilya are participating in an individual programming contest consisting of multiple stages. A contestant can get between 0 and 100 points, inclusive, for each stage, independently of other contestants.Points received by contestants in different stages are used for forming overall contest results. Suppose that k stages of the contest are completed. For each contestant, k - \lfloor \frac{k}{4} \rfloor stages with the highest scores are selected, and these scores are added up. This sum is the overall result of the contestant. (Here \lfloor t \rfloor denotes rounding t down.)For example, suppose 9 stages are completed, and your scores are 50, 30, 50, 50, 100, 10, 30, 100, 50. First, 7 stages with the highest scores are chosen — for example, all stages except for the 2-nd and the 6-th can be chosen. Then your overall result is equal to 50 + 50 + 50 + 100 + 30 + 100 + 50 = 430.As of now, n stages are completed, and you know the points you and Ilya got for these stages. However, it is unknown how many more stages will be held. You wonder what the smallest number of additional stages is, after which your result might become greater than or equal to Ilya's result, at least in theory. Find this number!InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the number of completed stages.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 100) — your points for the completed stages.The third line contains n integers b_1, b_2, \ldots, b_n (0 \le b_i \le 100) — Ilya's points for the completed stages.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print a single integer — the smallest number of additional stages required for your result to be able to become greater than or equal to Ilya's result.If your result is already not less than Ilya's result, print 0.ExampleInput 5 1 100 0 1 0 100 4 20 30 40 50 100 100 100 100 4 10 20 30 40 100 100 100 100 7 7 59 62 52 27 31 55 33 35 50 98 83 80 64 Output 0 1 3 4 2 NoteIn the first test case, you have scored 100 points for the first stage, while Ilya has scored 0. Thus, your overall result (100) is already not less than Ilya's result (0).In the second test case, you have scored 0 points for the first stage, while Ilya has scored 100. A single stage with an opposite result is enough for both your and Ilya's overall scores to become equal to 100.In the third test case, your overall result is 30 + 40 + 50 = 120, while Ilya's result is 100 + 100 + 100 = 300. After three additional stages your result might become equal to 420, while Ilya's result might become equal to 400.In the fourth test case, your overall result after four additional stages might become equal to 470, while Ilya's result might become equal to 400. Three stages are not enough.
5 1 100 0 1 0 100 4 20 30 40 50 100 100 100 100 4 10 20 30 40 100 100 100 100 7 7 59 62 52 27 31 55 33 35 50 98 83 80 64
0 1 3 4 2
2 seconds
512 megabytes
['binary search', 'brute force', 'greedy', 'sortings', '*1200']
B. Putting Platestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputTo celebrate your birthday you have prepared a festive table! Now you want to seat as many guests as possible.The table can be represented as a rectangle with height h and width w, divided into h \times w cells. Let (i, j) denote the cell in the i-th row and the j-th column of the rectangle (1 \le i \le h; 1 \le j \le w).Into each cell of the table you can either put a plate or keep it empty.As each guest has to be seated next to their plate, you can only put plates on the edge of the table — into the first or the last row of the rectangle, or into the first or the last column. Formally, for each cell (i, j) you put a plate into, at least one of the following conditions must be satisfied: i = 1, i = h, j = 1, j = w.To make the guests comfortable, no two plates must be put into cells that have a common side or corner. In other words, if cell (i, j) contains a plate, you can't put plates into cells (i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1), (i - 1, j - 1), (i - 1, j + 1), (i + 1, j - 1), (i + 1, j + 1).Put as many plates on the table as possible without violating the rules above.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.Each of the following t lines describes one test case and contains two integers h and w (3 \le h, w \le 20) — the height and the width of the table.OutputFor each test case, print h lines containing w characters each. Character j in line i must be equal to 1 if you are putting a plate into cell (i, j), and 0 otherwise. If there are multiple answers, print any.All plates must be put on the edge of the table. No two plates can be put into cells that have a common side or corner. The number of plates put on the table under these conditions must be as large as possible.You are allowed to print additional empty lines.ExampleInput 3 3 5 4 4 5 6 Output 10101 00000 10101 0100 0001 1000 0010 010101 000000 100001 000000 101010 NoteFor the first test case, example output contains the only way to put 6 plates on the table.For the second test case, there are many ways to put 4 plates on the table, example output contains one of them.Putting more than 6 plates in the first test case or more than 4 plates in the second test case is impossible.
3 3 5 4 4 5 6
10101 00000 10101 0100 0001 1000 0010 010101 000000 100001 000000 101010
2 seconds
512 megabytes
['constructive algorithms', 'implementation', '*800']
A. Binary Decimaltime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either 0 or 1. For example, 1\,010\,111 is a binary decimal, while 10\,201 and 787\,788 are not.Given a number n, you are asked to represent n as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.InputThe first line contains a single integer t (1 \le t \le 1000), denoting the number of test cases.The only line of each test case contains a single integer n (1 \le n \le 10^9), denoting the number to be represented.OutputFor each test case, output the smallest number of binary decimals required to represent n as a sum.ExampleInput 3 121 5 1000000000 Output 2 5 1 NoteIn the first test case, 121 can be represented as 121 = 110 + 11 or 121 = 111 + 10.In the second test case, 5 can be represented as 5 = 1 + 1 + 1 + 1 + 1.In the third test case, 1\,000\,000\,000 is a binary decimal itself, thus the answer is 1.
3 121 5 1000000000
2 5 1
1 second
512 megabytes
['greedy', 'math', '*800']
B. Sifid and Strange Subsequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence (b_1, b_2, \ldots, b_k) is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair (i, j) with 1 \le i<j \le k, we have |a_i-a_j|\geq MAX, where MAX is the largest element of the sequence. In particular, any sequence of length at most 1 is strange.For example, the sequences (-2021, -1, -1, -1) and (-1, 0, 1) are strange, but (3, 0, 1) is not, because |0 - 1| < 3.Sifid has an array a of n integers. Sifid likes everything big, so among all the strange subsequences of a, he wants to find the length of the longest one. Can you help him?A sequence c is a subsequence of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer t (1\le t\le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1\le n\le 10^5) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-10^9\le a_i \le 10^9) — the elements of the array a.It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.OutputFor each test case output a single integer — the length of the longest strange subsequence of a.ExampleInput 6 4 -1 -2 0 0 7 -3 4 -2 0 -4 6 1 5 0 5 -3 2 -5 3 2 3 1 4 -3 0 2 0 6 -3 -2 -1 1 1 1 Output 4 5 4 1 3 4 NoteIn the first test case, one of the longest strange subsequences is (a_1, a_2, a_3, a_4)In the second test case, one of the longest strange subsequences is (a_1, a_3, a_4, a_5, a_7).In the third test case, one of the longest strange subsequences is (a_1, a_3, a_4, a_5).In the fourth test case, one of the longest strange subsequences is (a_2).In the fifth test case, one of the longest strange subsequences is (a_1, a_2, a_4).
6 4 -1 -2 0 0 7 -3 4 -2 0 -4 6 1 5 0 5 -3 2 -5 3 2 3 1 4 -3 0 2 0 6 -3 -2 -1 1 1 1
4 5 4 1 3 4
1 second
256 megabytes
['greedy', 'math', 'sortings', '*1100']
A. Eshag Loves Big Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEshag has an array a consisting of n integers.Eshag can perform the following operation any number of times: choose some subsequence of a and delete every element from it which is strictly larger than AVG, where AVG is the average of the numbers in the chosen subsequence.For example, if a = [1 , 4 , 3 , 2 , 4] and Eshag applies the operation to the subsequence containing a_1, a_2, a_4 and a_5, then he will delete those of these 4 elements which are larger than \frac{a_1+a_2+a_4+a_5}{4} = \frac{11}{4}, so after the operation, the array a will become a = [1 , 3 , 2].Your task is to find the maximum number of elements Eshag can delete from the array a by applying the operation described above some number (maybe, zero) times.A sequence b is a subsequence of an array c if b can be obtained from c by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer t (1\le t\le 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1\le n\le 100) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1\le a_i \le 100) — the elements of the array a.OutputFor each test case print a single integer — the maximum number of elements Eshag can delete from the array a.ExampleInput 3 6 1 1 1 2 2 3 6 9 9 9 9 9 9 6 6 4 1 1 4 1 Output 3 0 3 NoteConsider the first test case.Initially a = [1, 1, 1, 2, 2, 3].In the first operation, Eshag can choose the subsequence containing a_1, a_5 and a_6, their average is equal to \frac{a_1 + a_5 + a_6}{3} = \frac{6}{3} = 2. So a_6 will be deleted.After this a = [1, 1, 1, 2, 2].In the second operation, Eshag can choose the subsequence containing the whole array a, the average of all its elements is equal to \frac{7}{5}. So a_4 and a_5 will be deleted.After this a = [1, 1, 1].In the second test case, Eshag can't delete any element.
3 6 1 1 1 2 2 3 6 9 9 9 9 9 9 6 6 4 1 1 4 1
3 0 3
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*800']
F. AmShZ Farmtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo AmShZ, all arrays are equal, but some arrays are more-equal than others. Specifically, the arrays consisting of n elements from 1 to n that can be turned into permutations of numbers from 1 to n by adding a non-negative integer to each element.Mashtali who wants to appear in every problem statement thinks that an array b consisting of k elements is compatible with a more-equal array a consisting of n elements if for each 1 \le i \le k we have 1 \le b_i \le n and also a_{b_1} = a_{b_2} = \ldots = a_{b_k}.Find the number of pairs of arrays a and b such that a is a more-equal array consisting of n elements and b is an array compatible with a consisting of k elements modulo 998244353.Note that the elements of b are not necessarily distinct, same holds for a.InputThe first line of input contains two integers n and k (1 \le n \le 10^9 , 1 \le k \le 10^5).OutputPrint a single integer — the answer to the problem modulo 998244353.ExamplesInput 1 1 Output 1 Input 2 2 Output 8 Input 5 4 Output 50400 Input 20 100 Output 807645526 Input 10000000 10000 Output 883232350 NoteThere are eight possible pairs for the second example: a = \{1, 1\}, b = \{1, 1\} a = \{1, 1\}, b = \{1, 2\} a = \{1, 1\}, b = \{2, 1\} a = \{1, 1\}, b = \{2, 2\} a = \{1, 2\}, b = \{1, 1\} a = \{1, 2\}, b = \{2, 2\} a = \{2, 1\}, b = \{1, 1\} a = \{2, 1\}, b = \{2, 2\}
1 1
1
2 seconds
256 megabytes
['combinatorics', 'fft', 'math', '*3300']
E. Mashtali and Hagh Treestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday is Mashtali's birthday! He received a Hagh tree from Haj Davood as his birthday present!A directed tree is called a Hagh tree iff: The length of the longest directed path in it is exactly n. Every vertex has at most three edges attached to it independent of their orientation. Let's call vertices u and v friends if one of them has a directed path to the other. For every pair of vertices u and v that are not friends, there should exist a vertex w that is friends with both u and v (a mutual friend). After opening his gift, Mashtali found out that the labels on the vertices were gone.Immediately, he asked himself: how many different unlabeled Hagh trees are there? That is, how many possible trees could he have received as his birthday present?At the first glance, the number of such trees seemed to be infinite since there was no limit on the number of vertices; but then he solved the problem and proved that there's a finite number of unlabeled Hagh trees!Amazed by this fact, he shared the task with you so that you could enjoy solving it as well. Since the answer can be rather large he asked you to find the number of different unlabeled Hagh trees modulo 998244353.Here two trees are considered different, if they are not isomorphic: if there is no way to map nodes of one tree to the second tree, so that edges are mapped to edges preserving the orientation.Some examples for n = 2: Directed trees D and E are Hagh. C is not Hagh because it has a vertex with 4 edges attached to it. A and B are not Hagh because their longest directed paths are not equal to n. Also in B the leftmost and rightmost vertices are not friends neither do they have a mutual friend.InputThe first line of input contains a single integer n (1 \le n \le 10^6).OutputPrint a single integer, the answer to Mashtali's task modulo 998244353.ExamplesInput 1 Output 5 Input 2 Output 31 Input 344031 Output 272040628 NoteAll the five Hagh trees for n = 1:
1
5
1 second
256 megabytes
['combinatorics', 'dp', 'trees', '*2900']
D. It's a bird! No, it's a plane! No, it's AaParsa!time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Shaazzzland, numbered from 0 to n-1. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.AaParsa has planted m transport cannons in the cities of Shaazzzland. The i-th cannon is planted in the city a_i and is initially pointing at city b_i.It is guaranteed that each of the n cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs (a_i, b_i) are distinct).AaParsa used very advanced technology to build the cannons, the cannons rotate every second. In other words, if the i-th cannon is pointing towards the city x at some second, it will target the city (x + 1) \mod n at the next second.As their name suggests, transport cannons are for transportation, specifically for human transport. If you use the i-th cannon to launch yourself towards the city that it's currently pointing at, you'll be airborne for c_i seconds before reaching your target destination.If you still don't get it, using the i-th cannon at the s-th second (using which is only possible if you are currently in the city a_i) will shoot you to the city (b_i + s) \mod n and you'll land in there after c_i seconds (so you'll be there in the (s + c_i)-th second). Also note the cannon that you initially launched from will rotate every second but you obviously won't change direction while you are airborne. AaParsa wants to use the cannons for travelling between Shaazzzland's cities in his grand plan, and he can start travelling at second 0. For him to fully utilize them, he needs to know the minimum number of seconds required to reach city u from city v using the cannons for every pair of cities (u, v).Note that AaParsa can stay in a city for as long as he wants.InputThe first line contains two integers n and m (2 \le n \le 600 , n \le m \le n^2) — the number of cities and cannons correspondingly.The i-th line of the following m lines contains three integers a_i, b_i and c_i ( 0 \le a_i , b_i \le n-1 , 1 \le c_i \le 10^9), denoting the cannon in the city a_i, which is initially pointing to b_i and travelling by which takes c_i seconds.It is guaranteed that each of the n cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs (a_i, b_i) are distinct).OutputPrint n lines, each line should contain n integers.The j-th integer in the i-th line should be equal to the minimum time required to reach city j from city i. ExamplesInput 3 4 0 1 1 0 2 3 1 0 1 2 0 1 Output 0 1 2 1 0 2 1 2 0 Input 6 6 0 0 1 1 1 1 2 2 1 3 3 1 4 4 1 5 5 1 Output 0 2 3 3 4 4 4 0 2 3 3 4 4 4 0 2 3 3 3 4 4 0 2 3 3 3 4 4 0 2 2 3 3 4 4 0 Input 4 5 0 1 1 1 3 2 2 2 10 3 0 1 0 0 2 Output 0 1 2 3 3 0 3 2 12 13 0 11 1 2 2 0 NoteIn the first example one possible path for going from 0 to 2 would be: Stay inside 0 and do nothing for 1 second. Use the first cannon and land at 2 after 1 second. Note that: we could have used the second cannon in 0-th second but it would have taken us 3 seconds to reach city 2 in that case.
3 4 0 1 1 0 2 3 1 0 1 2 0 1
0 1 2 1 0 2 1 2 0
5 seconds
256 megabytes
['constructive algorithms', 'graphs', 'shortest paths', '*2500']
C. Trees of Tranquillitytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSoroush and Keshi each have a labeled and rooted tree on n vertices. Both of their trees are rooted from vertex 1.Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on n vertices.They add an edge between vertices u and v in the memorial graph if both of the following conditions hold: One of u or v is the ancestor of the other in Soroush's tree. Neither of u or v is the ancestor of the other in Keshi's tree. Here vertex u is considered ancestor of vertex v, if u lies on the path from 1 (the root) to the v.Popping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big. Help Mashtali by finding the size of the maximum clique in the memorial graph.As a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge.InputThe first line contains an integer t (1\le t\le 3 \cdot 10^5) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (2\le n\le 3 \cdot 10^5).The second line of each test case contains n-1 integers a_2, \ldots, a_n (1 \le a_i < i), a_i being the parent of the vertex i in Soroush's tree.The third line of each test case contains n-1 integers b_2, \ldots, b_n (1 \le b_i < i), b_i being the parent of the vertex i in Keshi's tree.It is guaranteed that the given graphs are trees.It is guaranteed that the sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case print a single integer — the size of the maximum clique in the memorial graph.ExampleInput 4 4 1 2 3 1 2 3 5 1 2 3 4 1 1 1 1 6 1 1 1 1 2 1 2 1 2 2 7 1 1 3 4 4 5 1 2 1 4 2 5 Output 1 4 1 3 NoteIn the first and third test cases, you can pick any vertex.In the second test case, one of the maximum cliques is \{2, 3, 4, 5\}.In the fourth test case, one of the maximum cliques is \{3, 4, 6\}.
4 4 1 2 3 1 2 3 5 1 2 3 4 1 1 1 1 6 1 1 1 1 2 1 2 1 2 2 7 1 1 3 4 4 5 1 2 1 4 2 5
1 4 1 3
3 seconds
256 megabytes
['data structures', 'dfs and similar', 'greedy', 'trees', '*2300']
B. Kavi on Pairing Dutytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKavi has 2n points lying on the OX axis, i-th of which is located at x = i.Kavi considers all ways to split these 2n points into n pairs. Among those, he is interested in good pairings, which are defined as follows:Consider n segments with ends at the points in correspondent pairs. The pairing is called good, if for every 2 different segments A and B among those, at least one of the following holds: One of the segments A and B lies completely inside the other. A and B have the same length. Consider the following example: A is a good pairing since the red segment lies completely inside the blue segment.B is a good pairing since the red and the blue segment have the same length.C is not a good pairing since none of the red or blue segments lies inside the other, neither do they have the same size.Kavi is interested in the number of good pairings, so he wants you to find it for him. As the result can be large, find this number modulo 998244353.Two pairings are called different, if some two points are in one pair in some pairing and in different pairs in another.InputThe single line of the input contains a single integer n (1\le n \le 10^6).OutputPrint the number of good pairings modulo 998244353.ExamplesInput 1 Output 1Input 2 Output 3Input 3 Output 6Input 100 Output 688750769NoteThe good pairings for the second example are: In the third example, the good pairings are:
1
1
1 second
256 megabytes
['combinatorics', 'dp', 'math', '*1700']
A. Parsa's Humongous Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputParsa has a humongous tree on n vertices.On each vertex v he has written two integers l_v and r_v.To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v \le a_v \le r_v) to each vertex v such that the beauty of Parsa's tree is maximized.Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |a_u - a_v| over all edges (u, v) of the tree.Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.InputThe first line contains an integer t (1\le t\le 250) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2\le n\le 10^5) — the number of vertices in Parsa's tree.The i-th of the following n lines contains two integers l_i and r_i (1 \le l_i \le r_i \le 10^9).Each of the next n-1 lines contains two integers u and v (1 \le u , v \le n, u\neq v) meaning that there is an edge between the vertices u and v in Parsa's tree.It is guaranteed that the given graph is a tree.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case print the maximum possible beauty for Parsa's tree.ExampleInput 3 2 1 6 3 8 1 2 3 1 3 4 6 7 9 1 2 2 3 6 3 14 12 20 12 19 2 12 10 17 3 17 3 2 6 5 1 5 2 6 4 6 Output 7 8 62 NoteThe trees in the example: In the first test case, one possible assignment is a = \{1, 8\} which results in |1 - 8| = 7.In the second test case, one of the possible assignments is a = \{1, 5, 9\} which results in a beauty of |1 - 5| + |5 - 9| = 8
3 2 1 6 3 8 1 2 3 1 3 4 6 7 9 1 2 2 3 6 3 14 12 20 12 19 2 12 10 17 3 17 3 2 6 5 1 5 2 6 4 6
7 8 62
1 second
256 megabytes
['dfs and similar', 'divide and conquer', 'dp', 'greedy', 'trees', '*1600']
E. Partition Gametime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers. Define the cost of some array t as follows:cost(t) = \sum_{x \in set(t) } last(x) - first(x), where set(t) is the set of all values in t without repetitions, first(x), and last(x) are the indices of the first and last occurrence of x in t, respectively. In other words, we compute the distance between the first and last occurrences for each distinct element and sum them up.You need to split the array a into k consecutive segments such that each element of a belongs to exactly one segment and the sum of the cost of individual segments is minimum.InputThe first line contains two integers n, k (1 \le n \le 35\,000, 1 \le k \le \min(n,100)).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n).OutputOutput the minimum sum of the cost of individual segments.ExamplesInput 7 2 1 6 6 4 6 6 6 Output 3 Input 7 4 5 5 5 5 2 3 3 Output 1 NoteIn the first example, we can divide the array into [1,6,6,4] and [6,6,6]. Cost of [1,6,6,4] will be (1-1) + (3 - 2) + (4-4) = 1 and cost of [6,6,6] will be 3-1 = 2. Total cost would be 1 + 2 = 3.In the second example, divide the array into [5,5],[5],[5,2,3] and [3]. Total Cost would be 1 + 0 + 0 + 0 = 1.
7 2 1 6 6 4 6 6 6
3
3 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'dp', '*2500']
D. MEX Treetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u \neq v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k.The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^{5}).The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 \le u,v \le n-1) denoting an edge between u and v (u \neq v).It is guaranteed that the given edges form a tree.It is also guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^{5}.OutputFor each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n.ExampleInput 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note In example case 1, For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. In example case 2, For k = 0, there are no such paths. For k = 1, there are no such paths. For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2.
2 4 0 1 0 2 2 3 2 1 0
1 2 1 1 1 0 0 1
1.5 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'implementation', 'math', 'trees', '*2400']
C. Sequence Pair Weighttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe weight of a sequence is defined as the number of unordered pairs of indexes (i,j) (here i \lt j) with same value (a_{i} = a_{j}). For example, the weight of sequence a = [1, 1, 2, 2, 1] is 4. The set of unordered pairs of indexes with same value are (1, 2), (1, 5), (2, 5), and (3, 4).You are given a sequence a of n integers. Print the sum of the weight of all subsegments of a. A sequence b is a subsegment of a sequence a if b can be obtained from a by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print a single integer — the sum of the weight of all subsegments of a.ExampleInput 2 4 1 2 1 1 4 1 2 3 4 Output 6 0 Note In test case 1, all possible subsegments of sequence [1, 2, 1, 1] having size more than 1 are: [1, 2] having 0 valid unordered pairs; [2, 1] having 0 valid unordered pairs; [1, 1] having 1 valid unordered pair; [1, 2, 1] having 1 valid unordered pairs; [2, 1, 1] having 1 valid unordered pair; [1, 2, 1, 1] having 3 valid unordered pairs. Answer is 6. In test case 2, all elements of the sequence are distinct. So, there is no valid unordered pair with the same value for any subarray. Answer is 0.
2 4 1 2 1 1 4 1 2 3 4
6 0
2 seconds
256 megabytes
['hashing', 'implementation', 'math', '*1600']
B2. Palindrome Game (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations: Choose any i (1 \le i \le n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.InputThe first line contains a single integer t (1 \le t \le 10^3). Then t test cases follow.The first line of each test case contains a single integer n (1 \le n \le 10^3).The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.Note that there is no limit on the sum of n over test cases.OutputFor each test case print a single word in a new line: "ALICE", if Alice will win the game, "BOB", if Bob will win the game, "DRAW", if the game ends in a draw. ExampleInput 3 3 110 2 00 4 1010 Output ALICE BOB ALICE NoteIn the first test case of example, in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation. in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over. Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.In the second test case of example, in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome. in the 2-nd move Bob reverses the string. in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over. Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
3 3 110 2 00 4 1010
ALICE BOB ALICE
1 second
256 megabytes
['constructive algorithms', 'games', '*1900']
B1. Palindrome Game (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string s (which is initially a palindrome in this version) of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations: Choose any i (1 \le i \le n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.InputThe first line contains a single integer t (1 \le t \le 10^3). Then t test cases follow.The first line of each test case contains a single integer n (1 \le n \le 10^3).The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s is a palindrome and contains at least one '0'. Note that there is no limit on the sum of n over test cases.OutputFor each test case print a single word in a new line: "ALICE", if Alice will win the game, "BOB", if Bob will win the game, "DRAW", if the game ends in a draw. ExampleInput 2 4 1001 1 0 Output BOB BOB NoteIn the first test case of the example, in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome. in the 2-nd move Bob reverses the string. in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over. Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob always wins.
2 4 1001 1 0
BOB BOB
1 second
256 megabytes
['constructive algorithms', 'games', '*1200']
A. And Then There Were Ktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an integer n, find the maximum value of integer k such that the following condition holds: n & (n-1) & (n-2) & (n-3) & ... (k) = 0 where & denotes the bitwise AND operation.InputThe first line contains a single integer t (1 \le t \le 3 \cdot 10^4). Then t test cases follow.The first line of each test case contains a single integer n (1 \le n \le 10^9).OutputFor each test case, output a single integer — the required integer k.ExampleInput 3 2 5 17 Output 1 3 15 NoteIn the first testcase, the maximum value for which the continuous & operation gives 0 value, is 1.In the second testcase, the maximum value for which the continuous & operation gives 0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0. 5 \, \& \, 4 \neq 0, 5 \, \& \, 4 \, \& \, 3 = 0. Hence, 3 is the answer.
3 2 5 17
1 3 15
1 second
256 megabytes
['bitmasks', '*800']
F. Median Queriestime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There is a secret permutation p (1-indexed) of numbers from 1 to n. More formally, for 1 \leq i \leq n, 1 \leq p[i] \leq n and for 1 \leq i < j \leq n, p[i] \neq p[j]. It is known that p[1]<p[2].In 1 query, you give 3 distinct integers a,b,c (1 \leq a,b,c \leq n), and receive the median of \{|p[a]-p[b]|,|p[b]-p[c]|,|p[a]-p[c]|\}.In this case, the median is the 2-nd element (1-indexed) of the sequence when sorted in non-decreasing order. The median of \{4,6,2\} is 4 and the median of \{0,123,33\} is 33.Can you find the secret permutation in not more than 2n+420 queries?Note: the grader is not adaptive: the permutation is fixed before any queries are made.InputThe first line of input contains a single integer t (1 \leq t \leq 1000) — the number of testcases.The first line of each testcase consists of a single integer n (20 \leq n \leq 100000) — the length of the secret permutation.It is guaranteed that the sum of n over all test cases does not exceed 100000.InteractionFor each testcase, you begin the interaction by reading n.To perform a query, output "? a b c" where a,b,c is the 3 indices you want to use for the query.Numbers have to satisfy 1 \leq a,b,c \leq n and a \neq b,b \neq c,a \neq c.For each query, you will receive a single integer x: the median of \{|p[a]-p[b]|,|p[b]-p[c]|,|p[a]-p[c]|\}.In case your query is invalid or you asked more than 2n+420 queries, the interactor will print "−1" and will finish interaction. You will receive Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you have determined the secret permutation, output "! p[1] p[2] ... p[n]". If the secret permutation is correct, the interactor will print "1". Otherwise, the interactor will print "-1" and will finish interaction. You will receive Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded verdict.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.Hacks:To hack, use the following format of test: The first line should contain a single integer t (1 \leq t \leq 1000) — the number of testcases.The first line of each testcase should contain a single integer n (20 \leq n \leq 100000) — the length of the secret permutation.The following line of should contain n integers p[1],p[2],p[3],\ldots,p[n]. p[1]<p[2] and p must be a permutation of integers from 1 to n.You must ensure that the sum of n over all testcases does not exceed 100000.ExampleInput 1 20 6 9 1Output ? 1 5 2 ? 20 19 2 ! 9 10 19 7 16 18 11 14 15 6 20 8 17 4 5 3 12 2 13 1 NoteThe secret permutation is \{9,10,19,7,16,18,11,14,15,6,20,8,17,4,5,3,12,2,13,1\}.For the first query, the values of (a,b,c) is (1,5,2). Since p[1]=9, p[5]=16 and p[2]=10. The return value is the median of \{|9-16|,|16-10|,|9-10|\} which is 6.For the second query, the values of (a,b,c) is (20,19,2). Since p[20]=1, p[19]=13 and p[2]=10. The return value is the median of \{|1-13|,|13-10|,|1-10|\} which is 9.By some miracle, we have figured out that the secret permutation is \{9,10,19,7,16,18,11,14,15,6,20,8,17,4,5,3,12,2,13,1\}. We output it and receive 1 from the interactor, meaning that we have guessed the secret permutation correctly.
1 20 6 9 1
? 1 5 2 ? 20 19 2 ! 9 10 19 7 16 18 11 14 15 6 20 8 17 4 5 3 12 2 13 1
6 seconds
256 megabytes
['constructive algorithms', 'interactive', 'probabilities', '*3000']
E. Oolimry and Suffix Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array. More formally, given a suffix array of length n and having an alphabet size k, count the number of strings that produce such a suffix array. Let s be a string of length n. Then the i-th suffix of s is the substring s[i \ldots n-1]. A suffix array is the array of integers that represent the starting indexes of all the suffixes of a given string, after the suffixes are sorted in the lexicographic order. For example, the suffix array of oolimry is [3,2,4,1,0,5,6] as the array of sorted suffixes is [\texttt{imry},\texttt{limry},\texttt{mry},\texttt{olimry},\texttt{oolimry},\texttt{ry},\texttt{y}]. A string x is lexicographically smaller than string y, if either x is a prefix of y (and x\neq y), or there exists such i that x_i < y_i, and for any 1\leq j < i , x_j = y_j.InputThe first line contain 2 integers n and k (1 \leq n \leq 200000,1 \leq k \leq 200000) — the length of the suffix array and the alphabet size respectively.The second line contains n integers s_0, s_1, s_2, \ldots, s_{n-1} (0 \leq s_i \leq n-1) where s_i is the i-th element of the suffix array i.e. the starting position of the i-th lexicographically smallest suffix. It is guaranteed that for all 0 \leq i< j \leq n-1, s_i \neq s_j.OutputPrint how many strings produce such a suffix array. Since the number can be very large, print the answer modulo 998244353.ExamplesInput 3 2 0 2 1 Output 1Input 5 1 0 1 2 3 4 Output 0Input 6 200000 0 1 2 3 4 5 Output 822243495Input 7 6 3 2 4 1 0 5 6 Output 36NoteIn the first test case, "abb" is the only possible solution. In the second test case, it can be easily shown no possible strings exist as all the letters have to be equal. In the fourth test case, one possible string is "ddbacef".Please remember to print your answers modulo 998244353.
3 2 0 2 1
1
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'math', '*2400']
D. Kill Antontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAfter rejecting 10^{100} data structure problems, Errorgorn is very angry at Anton and decided to kill him.Anton's DNA can be represented as a string a which only contains the characters "ANTON" (there are only 4 distinct characters). Errorgorn can change Anton's DNA into string b which must be a permutation of a. However, Anton's body can defend against this attack. In 1 second, his body can swap 2 adjacent characters of his DNA to transform it back to a. Anton's body is smart and will use the minimum number of moves.To maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string B. Can you help him?InputThe first line of input contains a single integer t (1 \leq t \leq 100000) — the number of testcases.The first and only line of each testcase contains 1 string a (1 \leq |a| \leq 100000). a consists of only the characters "A", "N", "O" and "T".It is guaranteed that the sum of |a| over all testcases does not exceed 100000.OutputFor each testcase, print a single string, b. If there are multiple answers, you can output any one of them. b must be a permutation of the string a.ExampleInput 4 ANTON NAAN AAAAAA OAANTTON Output NNOTA AANN AAAAAA TNNTAOOA NoteFor the first testcase, it takes 7 seconds for Anton's body to transform NNOTA to ANTON: NNOTA \to NNOAT \to NNAOT \to NANOT \to NANTO \to ANNTO \to ANTNO \to ANTON. Note that you cannot output strings such as AANTON, ANTONTRYGUB, AAAAA and anton as it is not a permutation of ANTON.For the second testcase, it takes 2 seconds for Anton's body to transform AANN to NAAN. Note that other strings such as NNAA and ANNA will also be accepted.
4 ANTON NAAN AAAAAA OAANTTON
NNOTA AANN AAAAAA TNNTAOOA
2 seconds
512 megabytes
['brute force', 'constructive algorithms', 'data structures', 'math', 'strings', '*2200']
C2. Potions (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is that in this version n \leq 200000. You can make hacks only if both versions of the problem are solved.There are n potions in a line, with potion 1 on the far left and potion n on the far right. Each potion will increase your health by a_i when drunk. a_i can be negative, meaning that potion will decrease will health.You start with 0 health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?InputThe first line contains a single integer n (1 \leq n \leq 200000) — the number of potions. The next line contains n integers a_1, a_2, ... ,a_n (-10^9 \leq a_i \leq 10^9) which represent the change in health after drinking that potion.OutputOutput a single integer, the maximum number of potions you can drink without your health becoming negative.ExampleInput 6 4 -4 1 -3 1 -3 Output 5NoteFor the sample, you can drink 5 potions by taking potions 1, 3, 4, 5 and 6. It is not possible to drink all 6 potions because your health will go negative at some point
6 4 -4 1 -3 1 -3
5
1 second
256 megabytes
['data structures', 'greedy', '*1600']
C1. Potions (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is that in this version n \leq 2000. You can make hacks only if both versions of the problem are solved.There are n potions in a line, with potion 1 on the far left and potion n on the far right. Each potion will increase your health by a_i when drunk. a_i can be negative, meaning that potion will decrease will health.You start with 0 health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?InputThe first line contains a single integer n (1 \leq n \leq 2000) — the number of potions. The next line contains n integers a_1, a_2, ... ,a_n (-10^9 \leq a_i \leq 10^9) which represent the change in health after drinking that potion.OutputOutput a single integer, the maximum number of potions you can drink without your health becoming negative.ExampleInput 6 4 -4 1 -3 1 -3 Output 5NoteFor the sample, you can drink 5 potions by taking potions 1, 3, 4, 5 and 6. It is not possible to drink all 6 potions because your health will go negative at some point
6 4 -4 1 -3 1 -3
5
1 second
256 megabytes
['brute force', 'data structures', 'dp', 'greedy', '*1500']
B. I Hate 1111time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer x. Can you make x by summing up some number of 11, 111, 1111, 11111, \ldots? (You can use any number among them any number of times).For instance, 33=11+11+11 144=111+11+11+11 InputThe first line of input contains a single integer t (1 \leq t \leq 10000) — the number of testcases.The first and only line of each testcase contains a single integer x (1 \leq x \leq 10^9) — the number you have to make.OutputFor each testcase, you should output a single string. If you can make x, output "YES" (without quotes). Otherwise, output "NO".You can print each letter of "YES" and "NO" in any case (upper or lower).ExampleInput 3 33 144 69 Output YES YES NO NoteWays to make 33 and 144 were presented in the statement. It can be proved that we can't present 69 this way.
3 33 144 69
YES YES NO
1 second
256 megabytes
['dp', 'math', 'number theory', '*1400']
A. Mean Inequalitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours.More formally, find an array b, such that: b is a permutation of a.For every i from 1 to 2n, b_i \neq \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists.InputThe first line of input contains a single integer t (1 \leq t \leq 1000) — the number of testcases. The description of testcases follows.The first line of each testcase contains a single integer n (1 \leq n \leq 25).The second line of each testcase contains 2n integers a_1, a_2, \ldots, a_{2n} (1 \leq a_i \leq 10^9) — elements of the array.Note that there is no limit to the sum of n over all testcases.OutputFor each testcase, you should output 2n integers, b_1, b_2, \ldots b_{2n}, for which the conditions from the statement are satisfied.ExampleInput 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 NoteIn the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and \frac{3+4}{2}\neq 1, \frac{1+2}{2}\neq 4, \frac{4+5}{2}\neq 2, \frac{2+6}{2}\neq 5, \frac{5+3}{2}\neq 6, \frac{6+1}{2}\neq 3.
3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9
3 1 4 2 5 6 123 10 456 789 9 6
1 second
256 megabytes
['constructive algorithms', 'sortings', '*800']
F. Goblins And Gnomestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp plays a computer game called "Goblins and Gnomes". In this game, he manages a large underground city of gnomes and defends it from hordes of goblins.The city consists of n halls and m one-directional tunnels connecting them. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. The city will be attacked by k waves of goblins; during the i-th wave, i goblins attack the city. Monocarp's goal is to pass all k waves.The i-th wave goes as follows: firstly, i goblins appear in some halls of the city and pillage them; at most one goblin appears in each hall. Then, goblins start moving along the tunnels, pillaging all the halls in their path. Goblins are very greedy and cunning, so they choose their paths so that no two goblins pass through the same hall. Among all possible attack plans, they choose a plan which allows them to pillage the maximum number of halls. After goblins are done pillaging, they leave the city.If all halls are pillaged during the wave — Monocarp loses the game. Otherwise, the city is restored. If some hall is pillaged during a wave, goblins are still interested in pillaging it during the next waves.Before each wave, Monocarp can spend some time preparing to it. Monocarp doesn't have any strict time limits on his preparations (he decides when to call each wave by himself), but the longer he prepares for a wave, the fewer points he gets for passing it. If Monocarp prepares for the i-th wave for t_i minutes, then he gets \max(0, x_i - t_i \cdot y_i) points for passing it (obviously, if he doesn't lose in the process).While preparing for a wave, Monocarp can block tunnels. He can spend one minute to either block all tunnels leading from some hall or block all tunnels leading to some hall. If Monocarp blocks a tunnel while preparing for a wave, it stays blocked during the next waves as well.Help Monocarp to defend against all k waves of goblins and get the maximum possible amount of points!InputThe first line contains three integers n, m and k (2 \le n \le 50; 0 \le m \le \frac{n(n - 1)}{2}; 1 \le k \le n - 1) — the number of halls in the city, the number of tunnels and the number of goblin waves, correspondely.Next m lines describe tunnels. The i-th line contains two integers u_i and v_i (1 \le u_i, v_i \le n; u_i \ne v_i). It means that the tunnel goes from hall u_i to hall v_i. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. There is at most one tunnel between each pair of halls.Next k lines describe the scoring system. The i-th line contains two integers x_i and y_i (1 \le x_i \le 10^9; 1 \le y_i \le 10^9). If Monocarp prepares for the i-th wave for t_i minutes, then he gets \max(0, x_i - t_i \cdot y_i) points for passing it.OutputPrint the optimal Monocarp's strategy in the following format:At first, print one integer a (k \le a \le 2n + k) — the number of actions Monocarp will perform. Next, print actions themselves in the order Monocarp performs them. The i-th action is described by a single integer b_i (-n \le b_i \le n) using the following format: if b_i > 0 then Monocarp blocks all tunnels going out from the hall b_i; if b_i < 0 then Monocarp blocks all tunnels going into the hall |b_i|; if b_i = 0 then Monocarp calls the next goblin wave. You can't repeat the same block action b_i several times. Monocarp must survive all waves he calls (goblins shouldn't be able to pillage all halls). Monocarp should call exactly k waves and earn the maximum possible number of points in total.If there are several optimal strategies — print any of them.ExamplesInput 5 4 4 1 2 2 3 4 3 5 3 100 1 200 5 10 10 100 1 Output 6 -2 -3 0 0 0 0 Input 5 4 4 1 2 2 3 4 3 5 3 100 100 200 5 10 10 100 1 Output 6 0 -3 0 0 1 0 Input 5 10 1 1 2 1 3 1 4 1 5 5 2 5 3 5 4 4 2 4 3 2 3 100 100 Output 6 1 2 3 4 5 0 NoteIn the first example, Monocarp, firstly, block all tunnels going in hall 2, secondly — all tunnels going in hall 3, and after that calls all waves. He spent two minutes to prepare to wave 1, so he gets 98 points for it. He didn't prepare after that, that's why he gets maximum scores for each of next waves (200, 10 and 100). In total, Monocarp earns 408 points.In the second example, Monocarp calls for the first wave immediately and gets 100 points. Before the second wave he blocks all tunnels going in hall 3. He spent one minute preparing to the wave, so he gets 195 points. Monocarp didn't prepare for the third wave, so he gets 10 points by surviving it. Before the fourth wave he blocks all tunnels going out from hall 1. He spent one minute, so he gets 99 points for the fourth wave. In total, Monocarp earns 404 points.In the third example, it doesn't matter how many minutes Monocarp will spend before the wave, since he won't get any points for it. That's why he decides to block all tunnels in the city, spending 5 minutes. He survived the wave though without getting any points.
5 4 4 1 2 2 3 4 3 5 3 100 1 200 5 10 10 100 1
6 -2 -3 0 0 0 0
4 seconds
512 megabytes
['brute force', 'dp', 'flows', 'graph matchings', '*2800']
E. Assimilation IVtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!InputThe first line contains two integers n and m (1 \le n \le 20; 1 \le m \le 5 \cdot 10^4) — the number of cities and the number of points.Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 \le d_{i, j} \le n + 1) is the distance between the i-th city and the j-th point.OutputIt can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction \frac{x}{y}. Print this fraction modulo 998\,244\,353, i. e. value x \cdot y^{-1} \bmod 998244353 where y^{-1} is such number that y \cdot y^{-1} \bmod 998244353 = 1.ExampleInput 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 NoteLet's look at all possible orders of cities Monuments will be build in: [1, 2, 3]: the first city controls all points at distance at most 3, in other words, points 1 and 4; the second city controls all points at distance at most 2, or points 1, 3 and 5; the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is \frac{4 + 3 + 3 + 3 + 3 + 3}{6} = \frac{19}{6} or 19 \cdot 6^{-1} \equiv 19 \cdot 166374059 \equiv 166374062 \pmod{998244353}
3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3
166374062
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'probabilities', 'two pointers', '*2100']
D. Armchairstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than \frac{n}{2}.For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?InputThe first line contains one integer n (2 \le n \le 5000) — the number of armchairs.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most \frac{n}{2}.OutputPrint one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.ExamplesInput 7 1 0 0 1 0 0 1 Output 3 Input 6 1 1 1 0 0 0 Output 9 Input 5 0 0 0 0 0 Output 0 NoteIn the first test, you can perform the following sequence: ask a person to move from armchair 1 to armchair 2, it takes 1 minute; ask a person to move from armchair 7 to armchair 6, it takes 1 minute; ask a person to move from armchair 4 to armchair 5, it takes 1 minute. In the second test, you can perform the following sequence: ask a person to move from armchair 1 to armchair 4, it takes 3 minutes; ask a person to move from armchair 2 to armchair 6, it takes 4 minutes; ask a person to move from armchair 4 to armchair 5, it takes 1 minute; ask a person to move from armchair 3 to armchair 4, it takes 1 minute. In the third test, no seat is occupied so your goal is achieved instantly.
7 1 0 0 1 0 0 1
3
2 seconds
512 megabytes
['dp', 'flows', 'graph matchings', 'greedy', '*1800']
C. Robot Collisionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m.The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then the descriptions of t testcases follow.The first line of each testcase contains two integers n and m (1 \le n \le 3 \cdot 10^5; 2 \le m \le 10^8) — the number of robots and the coordinate of the right wall.The second line of each testcase contains n integers x_1, x_2, \dots, x_n (0 < x_i < m) — the starting coordinates of the robots.The third line of each testcase contains n space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right).All coordinates x_i in the testcase are distinct.The sum of n over all testcases doesn't exceed 3 \cdot 10^5.OutputFor each testcase print n integers — for the i-th robot output the time it explodes at if it does and -1 otherwise.ExampleInput 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 NoteHere is the picture for the seconds 0, 1, 2 and 3 of the first testcase: Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer.After second 3 robot 6 just drive infinitely because there's no robot to collide with.
5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L
1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3
2 seconds
256 megabytes
['data structures', 'greedy', 'implementation', 'sortings', '*2000']
B. Permutation Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3].Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order.InputThe first line contains a single integer t (1 \le t \le 2000) — the number of test cases.The first line of the test case contains a single integer n (3 \le n \le 50) — the number of elements in the permutation.The second line of the test case contains n distinct integers from 1 to n — the given permutation a.OutputFor each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order.ExampleInput 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 NoteIn the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element.In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5].
3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3
1 0 2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*900']
A. Potion-makingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly k\ \% magic essence and (100 - k)\ \% water.In one step, you can pour either one liter of magic essence or one liter of water into the cauldron. What is the minimum number of steps to brew a potion? You don't care about the total volume of the potion, only about the ratio between magic essence and water in it.A small reminder: if you pour e liters of essence and w liters of water (e + w > 0) into the cauldron, then it contains \frac{e}{e + w} \cdot 100\ \% (without rounding) magic essence and \frac{w}{e + w} \cdot 100\ \% water.InputThe first line contains the single t (1 \le t \le 100) — the number of test cases.The first and only line of each test case contains a single integer k (1 \le k \le 100) — the percentage of essence in a good potion.OutputFor each test case, print the minimum number of steps to brew a good potion. It can be proved that it's always possible to achieve it in a finite number of steps.ExampleInput 3 3 100 25 Output 100 1 4 NoteIn the first test case, you should pour 3 liters of magic essence and 97 liters of water into the cauldron to get a potion with 3\ \% of magic essence.In the second test case, you can pour only 1 liter of essence to get a potion with 100\ \% of magic essence.In the third test case, you can pour 1 liter of magic essence and 3 liters of water.
3 3 100 25
100 1 4
1 second
256 megabytes
['math', 'number theory', '*800']
H. Hopping Around the Array time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output William really wants to get a pet. Since his childhood he dreamt about getting a pet grasshopper. William is being very responsible about choosing his pet, so he wants to set up a trial for the grasshopper!The trial takes place on an array a of length n, which defines lengths of hops for each of n cells. A grasshopper can hop around the sells according to the following rule: from a cell with index i it can jump to any cell with indices from i to i+a_i inclusive.Let's call the k-grasshopper value of some array the smallest number of hops it would take a grasshopper to hop from the first cell to the last, but before starting you can select no more than k cells and remove them from the array. When a cell is removed all other cells are renumbered but the values of a_i for each cell remains the same. During this the first and the last cells may not be removed.It is required to process q queries of the following format: you are given three numbers l, r, k. You are required to find the k-grasshopper value for an array, which is a subarray of the array a with elements from l to r inclusive.InputThe first line contains two integers n and q (1 \le n, q \le 20000), the length of the array and the number of queries respectively.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n)  – the elements of the array.The following q lines contain queries: each line contains three integers l, r and k (1 \le l \le r \le n, 0 \le k \le min(30, r-l)), which are the edges of the subarray and the number of the grasshopper value respectively.OutputFor each query print a single number in a new line  — the response to a query.ExampleInput 9 5 1 1 2 1 3 1 2 1 1 1 1 0 2 5 1 5 9 1 2 8 2 1 9 4 Output 0 2 1 2 2 NoteFor the second query the process occurs like this: For the third query the process occurs like this:
9 5 1 1 2 1 3 1 2 1 1 1 1 0 2 5 1 5 9 1 2 8 2 1 9 4
0 2 1 2 2
2 seconds
256 megabytes
['data structures', 'dp', '*3500']
G. Try Bookingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard output William owns a flat in central London. He decided to rent his flat out for the next n days to earn some money.Since his flat is in the center of the city, he instantly got m offers in the form (l_i, r_i), which means that someone wants to book the flat from day l_i until day r_i inclusive. To avoid spending a lot of time figuring out whether it's profitable for him to accept an offer, William decided to develop an algorithm. The algorithm processes all offers as they arrive and will only accept offer i if the following two conditions are satisfied: r_i - l_i + 1 \ge x. None of the days between l_i and r_i are occupied by a previously accepted offer William isn't sure what value x should have and he asks you for help. For all x from 1 to n he wants you to calculate the total number of days for which the flat would be occupied if the corresponding value will be assigned to x.InputThe first line contains two integers n and m (1 \le n \le 5 \cdot 10^4, 1 \le m \le 10^5), which are the number of days and the number of offers, respectively.Each of the next m lines contains two integers l_i and r_i (1 \le l_i \le r_i \le n), which describe the i-th renting offer. All offers are given in chronological order.OutputPrint n integers. The number in i-th line must be equal to the number of days the flat would be occupied if the algorithm will use the value of x equal to i.ExampleInput 6 5 2 3 3 5 1 1 1 5 1 6 Output 3 2 3 5 5 6 NoteThe description of segments from the first sample test for each x: x = 1  — algorithm will approve offers: 1 (2..3), 3 (1..1). The total number of days for which William's flat will be rented out is 3 x = 2  — algorithm will approve offers: 1 (2..3). The total number of days for which William's flat will be rented out is 2 x = 3  — algorithm will approve offers: 2 (3..5). The total number of days for which William's flat will be rented out is 3 x = 4  — algorithm will approve offers: 4 (1..5). The total number of days for which William's flat will be rented out is 5 x = 5  — algorithm will approve offers: 4 (1..5). The total number of days for which William's flat will be rented out is 5 x = 6  — algorithm will approve offers: 5 (1..6). The total number of days for which William's flat will be rented out is 6
6 5 2 3 3 5 1 1 1 5 1 6
3 2 3 5 5 6
2 seconds
512 megabytes
['data structures', 'divide and conquer', '*3200']
F. Favorite Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output After William is done with work for the day, he enjoys playing his favorite video game.The game happens in a 2D world, starting at turn 0. William can pick any cell in the game world and spawn in it. Then, each turn, William may remain at his current location or move from the current location (x, y) to one of the following locations: (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1).To accelerate movement the game has n fast travel towers. i-th tower is located at location (xa_i, ya_i). To be able to instantly travel to the tower from any location in the game world it must first be activated. Activation of tower i happens at the moment when the player is in cell (xa_i, ya_i) after this the tower remains active throughout the entire game.William also knows that the game has m quests. i-th quest can be completed instantly by being at location (xb_i, yb_i) on turn t_i.William wants to find out the maximal number of quests he will be able to complete by optimally traversing the game world.InputThe first line contains two integers n and m (0 \le n \le 14, 1 \le m \le 100), which are the number of towers and the number of quests, respectively.Each of the next n lines contains two integers xa_i, ya_i (1 \le xa_i, ya_i \le 10^6), which are the coordinates of fast travel towers.Each of the next m lines contains two integers xb_i, yb_i and t_i (1 \le xb_i, yb_i \le 10^6, 1 \le t_i \le 10^9), which are the coordinates of quests and the turn at which it may be completed.It is guaranteed that all locations in a test are different.OutputPrint a single number  — the maximal number of quests William will be able to complete.ExampleInput 3 4 1 1 2 3 5 2 2 2 12 5 1 4 6 2 11 3 5 10 Output 3 NoteIn the first sample test one of the possible sequences of William's actions is as follows: Spawn at (3, 2) On turn 1 move to (4, 2) On turn 2 move to (5, 2). By visiting this cell William activates tower number 3. On turn 3 move to (5, 1), where he waits for 1 turn to complete the 2nd quest On turn 5 move to (5, 2) On turn 6 move to (5, 3) On turn 7 move to (5, 4) On turn 8 move to (5, 5) On turn 9 move to (4, 5) On turn 10 move to (3, 5). By moving to this location William will complete the 4th quest On turn 10 instantly move to an already activated fast travel tower at (5, 2) On turn 11 move to (6, 2). By moving to this location William will complete the 3rd quest William will not be able to complete the quest number 1, because the tower at (2, 3) was not activated
3 4 1 1 2 3 5 2 2 2 12 5 1 4 6 2 11 3 5 10
3
2 seconds
256 megabytes
['bitmasks', 'dp', '*3300']
E. Crypto Lightstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of n lights arranged in a row. The device functions in the following way:Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distribution, picks a light that is turned off and turns it on, telling William which cryptocurrency he should invest in. After this iteration if any k consecutive lights contain more than one turned on light, then the device finishes working.William doesn't like uncertainty, so he wants you to calculate the expected value of the number of lights that are turned on in the device after it finishes working.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10). Description of the test cases follows.The only line for each test case contains two integers n and k (2 \le k \le n \le 10^5), which are the total number of lights and the length of subsegment of lights that are being checked, respectively.OutputFor each test case print the answer, modulo 10^9+7. Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExampleInput 3 3 2 15 2 40 15 Output 333333338 141946947 329622137 NoteExplanation of the first sample test case:Let's write out all possible sequences of light toggles, which will make the device complete its operation: (1, 2)  — 2 lights are turned on (1, 3, 2)  — 3 lights are turned on (2, 1)  — 2 lights are turned on (2, 3)  — 2 lights are turned on (3, 2)  — 2 lights are turned on (3, 1, 2)  — 3 lights are turned on Then the final expected value will be equal to \frac{2}{6} + \frac{3}{6} + \frac{2}{6} + \frac{2}{6} + \frac{2}{6} + \frac{3}{6} = \frac{14}{6} = \frac{7}{3}. Then the required output will be 333333338, since 333333338 \cdot 3 \equiv 7 \pmod{10^9+7}.
3 3 2 15 2 40 15
333333338 141946947 329622137
3 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'probabilities', '*2600']
D. Love-Hatetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output William is hosting a party for n of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others.For each William's friend i it is known whether he likes currency j. There are m currencies in total. It is also known that a trader may not like more than p currencies.Because friends need to have some common topic for discussions they need to find the largest by cardinality (possibly empty) subset of currencies, such that there are at least \lceil \frac{n}{2} \rceil friends (rounded up) who like each currency in this subset.InputThe first line contains three integers n, m and p (1 \le n \le 2 \cdot 10^5, 1 \le p \le m \le 60, 1 \le p \le 15), which is the number of trader friends, the number of currencies, the maximum number of currencies each friend can like.Each of the next n lines contain m characters. The j-th character of i-th line is 1 if friend i likes the currency j and 0 otherwise. It is guaranteed that the number of ones in each line does not exceed p.OutputPrint a string of length m, which defines the subset of currencies of the maximum size, which are liked by at least half of all friends. Currencies belonging to this subset must be signified by the character 1.If there are multiple answers, print any.ExamplesInput 3 4 3 1000 0110 1001 Output 1000 Input 5 5 4 11001 10101 10010 01110 11011 Output 10001 NoteIn the first sample test case only the first currency is liked by at least \lceil \frac{3}{2} \rceil = 2 friends, therefore it's easy to demonstrate that a better answer cannot be found.In the second sample test case the answer includes 2 currencies and will be liked by friends 1, 2, and 5. For this test case there are other currencies that are liked by at least half of the friends, but using them we cannot achieve a larger subset size.
3 4 3 1000 0110 1001
1000
3 seconds
256 megabytes
['bitmasks', 'brute force', 'dp', 'probabilities', '*2400']
C. Compression and Expansiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, on a new line, just after one of existing items a_1 \,.\, a_2 \,.\, a_3 \,.\, \,\cdots\, \,.\,a_k and can be one of two types: Add an item a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, a_k \,.\, 1 (starting a list of a deeper level), or Add an item a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, (a_k + 1) (continuing the current level). Operation can only be applied if the list does not contain two identical items afterwards. And also, if we consider every item as a sequence of numbers, then the sequence of items should always remain increasing in lexicographical order. Examples of valid and invalid lists that are shown in the picture can found in the "Notes" section.When William decided to save a Word document with the list of his errands he accidentally hit a completely different keyboard shortcut from the "Ctrl-S" he wanted to hit. It's not known exactly what shortcut he pressed but after triggering it all items in the list were replaced by a single number: the last number originally written in the item number.William wants you to help him restore a fitting original nested list.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10). Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^3), which is the number of lines in the list.Each of the next n lines contains a single integer a_i (1 \le a_i \le n), which is what remains of William's nested list.It is guaranteed that in each test case at least one fitting list exists.It is guaranteed that the sum of values n across all test cases does not exceed 10^3.OutputFor each test case output n lines which represent a valid nested list, which could become the data provided to you by William.If there are multiple answers, print any.ExampleInput 2 4 1 1 2 3 9 1 1 1 2 2 1 2 1 2 Output 1 1.1 1.2 1.3 1 1.1 1.1.1 1.1.2 1.2 1.2.1 2 2.1 2.2 NoteIn the second example test case one example of a fitting list is:11.1 1.1.11.1.21.21.2.122.12.2This list can be produced by using the sequence of operations shown below: Original list with a single item 1. Insert item 2 by using the insertion operation of the second type after item 1. Insert item 1.1 by using the insertion operation of the first type after item 1. Insert item 1.2 by using the insertion operation of the second type after item 1.1. Insert item 1.1.1 by using the insertion operation of the first type after item 1.1. Insert item 1.1.2 by using the insertion operation of the second type after item 1.1.1. Insert item 1.2.1 by using the insertion operation of the first type after item 1.2. Insert item 2.1 by using the insertion operation of the first type after item 2. Insert item 2.2 by using the insertion operation of the second type after item 2.1.
2 4 1 1 2 3 9 1 1 1 2 2 1 2 1 2
1 1.1 1.2 1.3 1 1.1 1.1.1 1.1.2 1.2 1.2.1 2 2.1 2.2
2 seconds
256 megabytes
['brute force', 'data structures', 'greedy', 'implementation', 'trees', '*1600']
B. Lord of the Valuestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from a_1, a_2, \ldots, a_n to -a_1, -a_2, \ldots, -a_n. For some unknown reason, the number of service variables is always an even number.William understands that with his every action he attracts more and more attention from the exchange's security team, so the number of his actions must not exceed 5\,000 and after every operation no variable can have an absolute value greater than 10^{18}. William can perform actions of two types for two chosen variables with indices i and j, where i < j: Perform assignment a_i = a_i + a_j Perform assignment a_j = a_j - a_i William wants you to develop a strategy that will get all the internal variables to the desired values.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 20). Description of the test cases follows.The first line of each test case contains a single even integer n (2 \le n \le 10^3), which is the number of internal variables.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9), which are initial values of internal variables.OutputFor each test case print the answer in the following format:The first line of output must contain the total number of actions k, which the strategy will perform. Note that you do not have to minimize k. The inequality k \le 5\,000 must be satisfied. Each of the next k lines must contain actions formatted as "type i j", where "type" is equal to "1" if the strategy needs to perform an assignment of the first type and "2" if the strategy needs to perform an assignment of the second type. Note that i < j should hold.We can show that an answer always exists.ExampleInput 2 4 1 1 1 1 4 4 3 1 2 Output 8 2 1 2 2 1 2 2 1 3 2 1 3 2 1 4 2 1 4 1 1 2 1 1 2 8 2 1 4 1 2 4 1 2 4 1 2 4 1 3 4 1 1 2 1 1 2 1 1 4 NoteFor the first sample test case one possible sequence of operations is as follows: "2 1 2". Values of variables after performing the operation: [1, 0, 1, 1] "2 1 2". Values of variables after performing the operation: [1, -1, 1, 1] "2 1 3". Values of variables after performing the operation: [1, -1, 0, 1] "2 1 3". Values of variables after performing the operation: [1, -1, -1, 1] "2 1 4". Values of variables after performing the operation: [1, -1, -1, 0] "2 1 4". Values of variables after performing the operation: [1, -1, -1, -1] "1 1 2". Values of variables after performing the operation: [0, -1, -1, -1] "1 1 2". Values of variables after performing the operation: [-1, -1, -1, -1] For the second sample test case one possible sequence of operations is as follows: "2 1 4". Values of variables after performing the operation: [4, 3, 1, -2] "1 2 4". Values of variables after performing the operation: [4, 1, 1, -2] "1 2 4". Values of variables after performing the operation: [4, -1, 1, -2] "1 2 4". Values of variables after performing the operation: [4, -3, 1, -2] "1 3 4". Values of variables after performing the operation: [4, -3, -1, -2] "1 1 2". Values of variables after performing the operation: [1, -3, -1, -2] "1 1 2". Values of variables after performing the operation: [-2, -3, -1, -2] "1 1 4". Values of variables after performing the operation: [-4, -3, -1, -2]
2 4 1 1 1 1 4 4 3 1 2
8 2 1 2 2 1 2 2 1 3 2 1 3 2 1 4 2 1 4 1 1 2 1 1 2 8 2 1 4 1 2 4 1 2 4 1 2 4 1 3 4 1 1 2 1 1 2 1 1 4
1 second
256 megabytes
['constructive algorithms', '*1100']
A. Game of Lifetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing n cells, with each cell either being alive or dead.Evolution of the array in William's cellular automaton occurs iteratively in the following way: If the element is dead and it has exactly 1 alive neighbor in the current state of the array, then on the next iteration it will become alive. For an element at index i the neighbors would be elements with indices i - 1 and i + 1. If there is no element at that index, it is considered to be a dead neighbor. William is a humane person so all alive elements stay alive. Check the note section for examples of the evolution.You are given some initial state of all elements and you need to help William find the state of the array after m iterations of evolution.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^3). Description of the test cases follows.The first line of each test case contains two integers n and m (2 \le n \le 10^3, 1 \le m \le 10^9), which are the total number of cells in the array and the number of iterations.The second line of each test case contains a string of length n made up of characters "0" and "1" and defines the initial state of the array. "1" means a cell is alive and "0" means it is dead.It is guaranteed that the sum of n over all test cases does not exceed 10^4.OutputIn each test case output a string of length n, made up of characters "0" and "1"  — the state of the array after m iterations of evolution.ExampleInput 4 11 3 01000000001 10 2 0110100101 5 2 10101 3 100 000 Output 11111001111 1110111101 10101 000 NoteSequence of iterations of evolution for the first test case 01000000001  — initial state 11100000011  — first iteration of evolution 11110000111  — second iteration of evolution 11111001111  — third iteration of evolution Sequence of iterations of evolution for the second test case 0110100101  — initial state 1110111101  — first iteration of evolution 1110111101  — second iteration of evolution
4 11 3 01000000001 10 2 0110100101 5 2 10101 3 100 000
11111001111 1110111101 10101 000
1 second
256 megabytes
['implementation', '*800']
E. Nastia and a Beautiful Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?Let a_i be how many numbers i (1 \le i \le k) you have.An n \times n matrix is called beautiful if it contains all the numbers you have, and for each 2 \times 2 submatrix of the original matrix is satisfied: The number of occupied cells doesn't exceed 3; The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size.InputThe first line contains a single integer t (1 \le t \le 10\,000) — the number of test cases.The first line of each test case contains 2 integers m and k (1 \le m, k \le 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.The second line of each test case contains k integers a_1, a_2, \ldots, a_{k} (0 \le a_i \le m, a_1 + a_2 + \ldots + a_{k} = m), where a_i is how many numbers i you have.It's guaranteed that the sum of m and k in one test doesn't exceed 2 \cdot 10^5.OutputFor each t test case print a single integer n — the size of the beautiful matrix.In the next n lines print n integers b_{i, j} (0 \le b_{i, j} \le k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. ExampleInput 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3NoteNote that 0 in this problem represents a blank, not a number.Examples of possible answers for the first test case:\begin{array}{cc} 1 & 1 \\ 4 & 0 \\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\ 1 & 0 \\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\ 1 & 1 \\ \end{array}Examples of not beautiful matrices for the first test case:\begin{array}{cc} 1 & 0 \\ 4 & 1 \\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\ 7 & 1 \\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\ 4 & 0 \\ \end{array}The example of the not beautiful matrix for the second test case:\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\ 3 & 2 & 3 & 3 & 0 \\ 0 & 1 & 0 & 0 & 0 \\ 3 & 0 & 0 & 0 & 0 \\ 2 & 1 & 3 & 3 & 3 \\ \end{array}Everything is okay, except the left-top submatrix contains 4 numbers.
2 3 4 2 0 0 1 15 4 2 4 8 1
2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'dp', 'greedy', '*2700']
D. Nastia Plays with a Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNastia has an unweighted tree with n vertices and wants to play with it!The girl will perform the following operation with her tree, as long as she needs: Remove any existing edge. Add an edge between any pair of vertices. What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.InputThe first line contains a single integer t (1 \le t \le 10\,000) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 10^5) — the number of vertices in the tree.Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 \le a_i, b_i \le n, a_i \neq b_i).It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 \cdot 10^5.OutputFor each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 \le x_1, y_1, x_2, y_{2} \le n, x_1 \neq y_1, x_2 \neq y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.ExampleInput 2 7 1 2 1 3 2 4 2 5 3 6 3 7 4 1 2 1 3 3 4 Output 2 2 5 6 7 3 6 4 5 0NoteNote the graph can be unconnected after a certain operation.Consider the first test case of the example: The red edges are removed, and the green ones are added.
2 7 1 2 1 3 2 4 2 5 3 6 3 7 4 1 2 1 3 3 4
2 2 5 6 7 3 6 4 5 0
3 seconds
256 megabytes
['constructive algorithms', 'data structures', 'dfs and similar', 'dp', 'dsu', 'greedy', 'implementation', 'trees', '*2500']
C. Nastia and a Hidden Permutationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem!Nastia has a hidden permutation p of length n consisting of integers from 1 to n. You, for some reason, want to figure out the permutation. To do that, you can give her an integer t (1 \le t \le 2), two different indices i and j (1 \le i, j \le n, i \neq j), and an integer x (1 \le x \le n - 1). Depending on t, she will answer: t = 1: \max{(\min{(x, p_i)}, \min{(x + 1, p_j)})}; t = 2: \min{(\max{(x, p_i)}, \max{(x + 1, p_j)})}. You can ask Nastia at most \lfloor \frac {3 \cdot n} { 2} \rfloor + 30 times. It is guaranteed that she will not change her permutation depending on your queries. Can you guess the permutation?InputThe input consists of several test cases. In the beginning, you receive the integer T (1 \le T \le 10\,000) — the number of test cases.At the beginning of each test case, you receive an integer n (3 \le n \le 10^4) — the length of the permutation p.It's guaranteed that the permutation is fixed beforehand and that the sum of n in one test doesn't exceed 2 \cdot 10^4.InteractionTo ask a question, print "? t i j x" (t = 1 or t = 2, 1 \le i, j \le n, i \neq j, 1 \le x \le n - 1) Then, you should read the answer.If we answer with −1 instead of a valid answer, that means you exceeded the number of queries or made an invalid query. Exit immediately after receiving −1 and you will see the Wrong Answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.To print the answer, print "! p_1 p_2 \ldots p_{n} (without quotes). Note that answering doesn't count as one of the \lfloor \frac {3 \cdot n} {2} \rfloor + 30 queries.After printing a query or printing the answer, do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; See the documentation for other languages. HacksTo hack the solution, use the following test format.The first line should contain a single integer T (1 \le T \le 10\,000) — the number of test cases.For each test case in the first line print a single integer n (3 \le n \le 10^4) — the length of the hidden permutation p.In the second line print n space-separated integers p_1, p_2, \ldots, p_n (1 \le p_i \le n), where p is permutation.Note that the sum of n over all test cases should not exceed 2 \cdot 10^4.ExampleInput 2 4 3 2 5 3Output ? 2 4 1 3 ? 1 2 4 2 ! 3 1 4 2 ? 2 3 4 2 ! 2 5 3 4 1 NoteConsider the first test case.The hidden permutation is [3, 1, 4, 2].We print: "? 2 4 1 3" and get back \min{(\max{(3, p_4}), \max{(4, p_1)})} = 3.We print: "? 1 2 4 2" and get back \max{(\min{(2, p_2)}, \min{(3, p_4)})} = 2.Consider the second test case.The hidden permutation is [2, 5, 3, 4, 1].We print: "? 2 3 4 2" and get back \min{(\max{(2, p_3}), \max{(3, p_4)})} = 3.
2 4 3 2 5 3
? 2 4 1 3 ? 1 2 4 2 ! 3 1 4 2 ? 2 3 4 2 ! 2 5 3 4 1
3 seconds
256 megabytes
['constructive algorithms', 'interactive', '*2000']
B. Nastia and a Good Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNastia has received an array of n positive integers as a gift.She calls such an array a good that for all i (2 \le i \le n) takes place gcd(a_{i - 1}, a_{i}) = 1, where gcd(u, v) denotes the greatest common divisor (GCD) of integers u and v.You can perform the operation: select two different indices i, j (1 \le i, j \le n, i \neq j) and two integers x, y (1 \le x, y \le 2 \cdot 10^9) so that \min{(a_i, a_j)} = \min{(x, y)}. Then change a_i to x and a_j to y.The girl asks you to make the array good using at most n operations.It can be proven that this is always possible.InputThe first line contains a single integer t (1 \le t \le 10\,000) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \ldots, a_{n} (1 \le a_i \le 10^9) — the array which Nastia has received as a gift.It's guaranteed that the sum of n in one test doesn't exceed 2 \cdot 10^5.OutputFor each of t test cases print a single integer k (0 \le k \le n) — the number of operations. You don't need to minimize this number.In each of the next k lines print 4 integers i, j, x, y (1 \le i \neq j \le n, 1 \le x, y \le 2 \cdot 10^9) so that \min{(a_i, a_j)} = \min{(x, y)} — in this manner you replace a_i with x and a_j with y.If there are multiple answers, print any.ExampleInput 2 5 9 6 3 11 15 3 7 5 13 Output 2 1 5 11 9 2 5 7 6 0NoteConsider the first test case.Initially a = [9, 6, 3, 11, 15].In the first operation replace a_1 with 11 and a_5 with 9. It's valid, because \min{(a_1, a_5)} = \min{(11, 9)} = 9.After this a = [11, 6, 3, 11, 9].In the second operation replace a_2 with 7 and a_5 with 6. It's valid, because \min{(a_2, a_5)} = \min{(7, 6)} = 6.After this a = [11, 7, 3, 11, 6] — a good array.In the second test case, the initial array is already good.
2 5 9 6 3 11 15 3 7 5 13
2 1 5 11 9 2 5 7 6 0
2 seconds
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1300']
A. Nastia and Nearly Good Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNastia has 2 positive integers A and B. She defines that: The integer is good if it is divisible by A \cdot B; Otherwise, the integer is nearly good, if it is divisible by A. For example, if A = 6 and B = 4, the integers 24 and 72 are good, the integers 6, 660 and 12 are nearly good, the integers 16, 7 are neither good nor nearly good.Find 3 different positive integers x, y, and z such that exactly one of them is good and the other 2 are nearly good, and x + y = z.InputThe first line contains a single integer t (1 \le t \le 10\,000) — the number of test cases.The first line of each test case contains two integers A and B (1 \le A \le 10^6, 1 \le B \le 10^6) — numbers that Nastia has.OutputFor each test case print: "YES" and 3 different positive integers x, y, and z (1 \le x, y, z \le 10^{18}) such that exactly one of them is good and the other 2 are nearly good, and x + y = z. "NO" if no answer exists. You can print each character of "YES" or "NO" in any case.If there are multiple answers, print any.ExampleInput 3 5 3 13 2 7 11 Output YES 10 50 60 YES 169 39 208 YES 28 154 182NoteIn the first test case: 60 — good number; 10 and 50 — nearly good numbers.In the second test case: 208 — good number; 169 and 39 — nearly good numbers.In the third test case: 154 — good number; 28 and 182 — nearly good numbers.
3 5 3 13 2 7 11
YES 10 50 60 YES 169 39 208 YES 28 154 182
1 second
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1000']
G. To Go Or Not To Go?time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDima overslept the alarm clock, which was supposed to raise him to school.Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.The city where Dima lives is a rectangular field of n \times m size. Each cell (i, j) on this field is denoted by one number a_{ij}: The number -1 means that the passage through the cell is prohibited; The number 0 means that the cell is free and Dima can walk though it. The number x (1 \le x \le 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free. From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).InputThe first line contains three integers n, m and w (2 \le n, m \le 2 \cdot 10^3, 1 \le w \le 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.The next n lines each contain m numbers (-1 \le a_{ij} \le 10^9) — descriptions of cells.It is guaranteed that the cells (1, 1) and (n, m) are free.OutputOutput the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".ExampleInput 5 5 1 0 -1 0 1 -1 0 20 0 0 -1 -1 -1 -1 -1 -1 3 0 0 0 0 -1 0 0 0 0 Output 14NoteExplanation for the first sample:
5 5 1 0 -1 0 1 -1 0 20 0 0 -1 -1 -1 -1 -1 -1 3 0 0 0 0 -1 0 0 0 0
14
3 seconds
512 megabytes
['brute force', 'dfs and similar', 'graphs', 'greedy', 'implementation', 'shortest paths', '*2200']
F2. Guess the K-th Zero (Hard version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.This is a hard version of the problem. The difference from the easy version is that in the hard version 1 \le t \le \min(n, 10^4) and the total number of queries is limited to 6 \cdot 10^4.Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.Polycarp can make no more than 6 \cdot 10^4 requests totally of the following type: ? l r — find out the sum of all elements in positions from l to r (1 \le l \le r \le n) inclusive. To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.Help Polycarp win the game.InteractionFirst, your program must read two integers n and t (1 \le n \le 2 \cdot 10^5, 1 \le t \le \min(n, 10^4)).Then t lines follow, each of which contains one integer k (1 \le k \le n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.After that, you can make no more than 6 \cdot 10^4 requests in total.Use the following format to output the answer (it is not a request, it doesn't count in 6 \cdot 10^4): ! x — position of the k-th zero. Positions in the array are numbered from left to right from 1 to n inclusive.After printing t answers, your program should exit immediately.In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.If the number of requests is exceeded, the verdict wrong answer will be displayed.Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character: fflush(stdout) or cout.flush() in C ++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. HacksUse the following format for hacks:On the first line print the string s (1 \le |s| \le 2 \cdot 10^5), consisting of zeros and ones, and an integer t (1 \le t \le \min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 \le k \le |s|).The hacked solution will not have direct access to the hidden array.ExampleInput 6 2 2 2 1 1 0 1 0Output ? 4 6 ? 1 1 ? 1 2 ? 5 5 ! 5 ? 2 2 ! 2 NoteIn the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
6 2 2 2 1 1 0 1 0
? 4 6 ? 1 1 ? 1 2 ? 5 5 ! 5 ? 2 2 ! 2
4 seconds
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'interactive', '*2200']
F1. Guess the K-th Zero (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.This is an easy version of the problem. The difference from the hard version is that in the easy version t=1 and the number of queries is limited to 20.Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.Polycarp can make no more than 20 requests of the following type: ? l r — find out the sum of all elements in positions from l to r (1 \le l \le r \le n) inclusive. In this (easy version) of the problem, this paragraph doesn't really make sense since t=1 always. To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1. Of course, this feature affects something only for t>1.Help Polycarp win the game.InteractionFirst, your program must read two integers n and t (1 \le n \le 2 \cdot 10^5, t=1).Then t lines follow, each of which contains one integer k (1 \le k \le n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the current value of k.After that, you can make no more than 20 requests.Use the following format to output the answer (it is not a request, it doesn't count in 20): ! x — position of the k-th zero. Positions in the array are numbered from left to right from 1 to n inclusive.After printing t answers, your program should exit immediately.In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.If the number of requests is exceeded, the verdict wrong answer will be displayed.Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character: fflush(stdout) or cout.flush() in C ++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. HacksUse the following format for hacks:On the first line print the string s (1 \le |s| \le 2 \cdot 10^5), consisting of zeros and ones, and an integer t (t = 1) — hidden array and number of requests, respectively. In the next t lines output the number k (1 \le k \le |s|).The hacked solution will not have direct access to the hidden array.ExampleInput 6 1 2 2 1 1 0 0Output ? 4 6 ? 1 1 ? 1 2 ? 2 2 ? 5 5 ! 5NoteIn the first test, the [1, 0, 1, 1, 0, 1] array is hidden. In this test k=2.
6 1 2 2 1 1 0 0
? 4 6 ? 1 1 ? 1 2 ? 2 2 ? 5 5 ! 5
1 second
256 megabytes
['binary search', 'interactive', '*1600']
E. Arranging The Sheeptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length n, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.For example, if n=6 and the level is described by the string "**.*..", then the following game scenario is possible: the sheep at the 4 position moves to the right, the state of the level: "**..*."; the sheep at the 2 position moves to the right, the state of the level: "*.*.*."; the sheep at the 1 position moves to the right, the state of the level: ".**.*."; the sheep at the 3 position moves to the right, the state of the level: ".*.**."; the sheep at the 2 position moves to the right, the state of the level: "..***."; the sheep are lined up and the game ends. For a given level, determine the minimum number of moves you need to make to complete the level.InputThe first line contains one integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains one integer n (1 \le n \le 10^6).The second line of each test case contains a string of length n, consisting of the characters '.' (empty space) and '*' (sheep) — the description of the level.It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case output the minimum number of moves you need to make to complete the level.ExampleInput 5 6 **.*.. 5 ***** 3 .*. 3 ... 10 *.*...*.** Output 1 0 0 0 9
5 6 **.*.. 5 ***** 3 .*. 3 ... 10 *.*...*.**
1 0 0 0 9
2 seconds
256 megabytes
['greedy', 'math', '*1400']
D. Same Differencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i.InputThe first line contains one integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains one integer n (1 \le n \le 2 \cdot 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — array a.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i.ExampleInput 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10
4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6
1 3 3 10
2 seconds
256 megabytes
['data structures', 'hashing', 'math', '*1200']
C. Not Adjacent Matrixtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1.We will consider cells of a square matrix n \times n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it.For a given number n, construct a square matrix n \times n such that: Each integer from 1 to n^2 occurs in this matrix exactly once; If (r_1, c_1) and (r_2, c_2) are adjacent cells, then the numbers written in them must not be adjacent. InputThe first line contains one integer t (1 \le t \le 100). Then t test cases follow.Each test case is characterized by one integer n (1 \le n \le 100).OutputFor each test case, output: -1, if the required matrix does not exist; the required matrix, otherwise (any such matrix if many of them exist). The matrix should be outputted as n lines, where each line contains n integers.ExampleInput 3 1 2 3 Output 1 -1 2 9 7 4 6 3 1 8 5
3 1 2 3
1 -1 2 9 7 4 6 3 1 8 5
4 seconds
256 megabytes
['constructive algorithms', '*1000']
B. Ordinary Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a positive integer n ordinary if in the decimal notation all its digits are the same. For example, 1, 2 and 99 are ordinary numbers, but 719 and 2021 are not ordinary numbers.For a given number n, find the number of ordinary numbers among the numbers from 1 to n.InputThe first line contains one integer t (1 \le t \le 10^4). Then t test cases follow.Each test case is characterized by one integer n (1 \le n \le 10^9).OutputFor each test case output the number of ordinary numbers among numbers from 1 to n.ExampleInput 6 1 2 3 4 5 100 Output 1 2 3 4 5 18
6 1 2 3 4 5 100
1 2 3 4 5 18
2 seconds
256 megabytes
['brute force', 'math', 'number theory', '*800']
A. Do Not Be Distracted!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".Help Polycarp find out if his teacher might be suspicious.InputThe first line contains an integer t (1 \le t \le 1000). Then t test cases follow.The first line of each test case contains one integer n (1 \le n \le 50) — the number of days during which Polycarp solved tasks.The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.OutputFor each test case output: "YES", if the teacher cannot be suspicious; "NO", otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).ExampleInput 5 3 ABA 11 DDBBCCCBBEZ 7 FFGZZZY 1 Z 2 AB Output NO NO YES YES YES
5 3 ABA 11 DDBBCCCBBEZ 7 FFGZZZY 1 Z 2 AB
NO NO YES YES YES
1 second
256 megabytes
['brute force', 'implementation', '*800']
F. Chests and Keystime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob play a game. Alice has got n treasure chests (the i-th of which contains a_i coins) and m keys (the j-th of which she can sell Bob for b_j coins).Firstly, Alice puts some locks on the chests. There are m types of locks, the locks of the j-th type can only be opened with the j-th key. To put a lock of type j on the i-th chest, Alice has to pay c_{i,j} dollars. Alice can put any number of different types of locks on each chest (possibly, zero).Then, Bob buys some of the keys from Alice (possibly none, possibly all of them) and opens each chest he can (he can open a chest if he has the keys for all of the locks on this chest). Bob's profit is the difference between the total number of coins in the opened chests and the total number of coins he spends buying keys from Alice. If Bob's profit is strictly positive (greater than zero), he wins the game. Otherwise, Alice wins the game.Alice wants to put some locks on some chests so no matter which keys Bob buys, she always wins (Bob cannot get positive profit). Of course, she wants to spend the minimum possible number of dollars on buying the locks. Help her to determine whether she can win the game at all, and if she can, how many dollars she has to spend on the locks.InputThe first line contains two integers n and m (1 \le n, m \le 6) — the number of chests and the number of keys, respectively.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 4), where a_i is the number of coins in the i-th chest.The third line contains m integers b_1, b_2, \dots, b_m (1 \le b_j \le 4), where b_j is the number of coins Bob has to spend to buy the j-th key from Alice.Then n lines follow. The i-th of them contains m integers c_{i,1}, c_{i,2}, \dots, c_{i,m} (1 \le c_{i,j} \le 10^7), where c_{i,j} is the number of dollars Alice has to spend to put a lock of the j-th type on the i-th chest.OutputIf Alice cannot ensure her victory (no matter which locks she puts on which chests, Bob always has a way to gain positive profit), print -1.Otherwise, print one integer — the minimum number of dollars Alice has to spend to win the game regardless of Bob's actions.ExamplesInput 2 3 3 3 1 1 4 10 20 100 20 15 80 Output 205 Input 2 3 3 3 2 1 4 10 20 100 20 15 80 Output 110 Input 2 3 3 4 1 1 4 10 20 100 20 15 80 Output -1 NoteIn the first example, Alice should put locks of types 1 and 3 on the first chest, and locks of type 2 and 3 on the second chest.In the second example, Alice should put locks of types 1 and 2 on the first chest, and a lock of type 3 on the second chest.
2 3 3 3 1 1 4 10 20 100 20 15 80
205
3 seconds
512 megabytes
['bitmasks', 'brute force', 'dfs and similar', 'dp', 'flows', '*3200']
E. Off by Onetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n points on an infinite plane. The i-th point has coordinates (x_i, y_i) such that x_i > 0 and y_i > 0. The coordinates are not necessarily integer.In one move you perform the following operations: choose two points a and b (a \neq b); move point a from (x_a, y_a) to either (x_a + 1, y_a) or (x_a, y_a + 1); move point b from (x_b, y_b) to either (x_b + 1, y_b) or (x_b, y_b + 1); remove points a and b. However, the move can only be performed if there exists a line that passes through the new coordinates of a, new coordinates of b and (0, 0). Otherwise, the move can't be performed and the points stay at their original coordinates (x_a, y_a) and (x_b, y_b), respectively.The numeration of points does not change after some points are removed. Once the points are removed, they can't be chosen in any later moves. Note that you have to move both points during the move, you can't leave them at their original coordinates.What is the maximum number of moves you can perform? What are these moves?If there are multiple answers, you can print any of them.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of points.The i-th of the next n lines contains four integers a_i, b_i, c_i, d_i (1 \le a_i, b_i, c_i, d_i \le 10^9). The coordinates of the i-th point are x_i = \frac{a_i}{b_i} and y_i = \frac{c_i}{d_i}.OutputIn the first line print a single integer c — the maximum number of moves you can perform.Each of the next c lines should contain a description of a move: two integers a and b (1 \le a, b \le n, a \neq b) — the points that are removed during the current move. There should be a way to move points a and b according to the statement so that there's a line that passes through the new coordinates of a, the new coordinates of b and (0, 0). No removed point can be chosen in a later move.If there are multiple answers, you can print any of them. You can print the moves and the points in the move in the arbitrary order.ExamplesInput 7 4 1 5 1 1 1 1 1 3 3 3 3 1 1 4 1 6 1 1 1 5 1 4 1 6 1 1 1 Output 3 1 6 2 4 5 7 Input 4 2 1 1 1 1 1 2 1 2 1 1 2 1 2 1 2 Output 1 1 2 Input 4 182 168 60 96 78 72 45 72 69 21 144 63 148 12 105 6 Output 1 2 4 NoteHere are the points and the moves for the ones that get chosen for the moves from the first example:
7 4 1 5 1 1 1 1 1 3 3 3 3 1 1 4 1 6 1 1 1 5 1 4 1 6 1 1 1
3 1 6 2 4 5 7
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'geometry', 'graphs', 'sortings', 'trees', '*2700']
D. Maximum Sum of Productstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integer arrays a and b of length n.You can reverse at most one subarray (continuous subsegment) of the array a. Your task is to reverse such a subarray that the sum \sum\limits_{i=1}^n a_i \cdot b_i is maximized.InputThe first line contains one integer n (1 \le n \le 5000).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^7).The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^7).OutputPrint single integer — maximum possible sum after reversing at most one subarray (continuous subsegment) of a.ExamplesInput 5 2 3 2 1 3 1 3 2 4 2 Output 29 Input 2 13 37 2 4 Output 174 Input 6 1 8 7 6 3 6 5 9 6 8 8 6 Output 235 NoteIn the first example, you can reverse the subarray [4, 5]. Then a = [2, 3, 2, 3, 1] and 2 \cdot 1 + 3 \cdot 3 + 2 \cdot 2 + 3 \cdot 4 + 1 \cdot 2 = 29.In the second example, you don't need to use the reverse operation. 13 \cdot 2 + 37 \cdot 4 = 174.In the third example, you can reverse the subarray [3, 5]. Then a = [1, 8, 3, 6, 7, 6] and 1 \cdot 5 + 8 \cdot 9 + 3 \cdot 6 + 6 \cdot 8 + 7 \cdot 8 + 6 \cdot 6 = 235.
5 2 3 2 1 3 1 3 2 4 2
29
2 seconds
256 megabytes
['brute force', 'dp', 'implementation', 'math', 'two pointers', '*1600']
C. Berland Regionaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.Polycarp has to decide on the rules now. In particular, the number of members in the team.Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.Help Polycarp to find the strength of the region for each choice of k from 1 to n.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.The first line of each testcase contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of universities and the number of students.The second line of each testcase contains n integers u_1, u_2, \dots, u_n (1 \le u_i \le n) — the university the i-th student is enrolled at.The third line of each testcase contains n integers s_1, s_2, \dots, s_n (1 \le s_i \le 10^9) — the programming skill of the i-th student.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase print n integers: the strength of the region — the total skill of the members of the present teams — for each choice of team size k.ExampleInput 4 7 1 2 1 2 1 2 1 6 8 3 1 5 1 5 10 1 1 1 2 2 2 2 3 3 3 3435 3014 2241 2233 2893 2102 2286 2175 1961 2567 6 3 3 3 3 3 3 5 9 6 7 9 7 1 1 3083 Output 29 28 26 19 0 0 0 24907 20705 22805 9514 0 0 0 0 0 0 43 43 43 32 38 43 3083 NoteIn the first testcase the teams from each university for each k are: k=1: university 1: [6], [5], [5], [3]; university 2: [8], [1], [1]; k=2: university 1: [6, 5], [5, 3]; university 2: [8, 1]; k=3: university 1: [6, 5, 5]; university 2: [8, 1, 1]; k=4: university 1: [6, 5, 5, 3];
4 7 1 2 1 2 1 2 1 6 8 3 1 5 1 5 10 1 1 1 2 2 2 2 3 3 3 3435 3014 2241 2233 2893 2102 2286 2175 1961 2567 6 3 3 3 3 3 3 5 9 6 7 9 7 1 1 3083
29 28 26 19 0 0 0 24907 20705 22805 9514 0 0 0 0 0 0 43 43 43 32 38 43 3083
2 seconds
256 megabytes
['brute force', 'data structures', 'greedy', 'number theory', 'sortings', '*1400']
B. The Cake Is a Lietime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a n \times m grid. You are standing at cell (1, 1) and your goal is to finish at cell (n, m).You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell (x, y). You can: move right to the cell (x, y + 1) — it costs x burles; move down to the cell (x + 1, y) — it costs y burles. Can you reach cell (n, m) spending exactly k burles?InputThe first line contains the single integer t (1 \le t \le 100) — the number of test cases.The first and only line of each test case contains three integers n, m, and k (1 \le n, m \le 100; 0 \le k \le 10^4) — the sizes of grid and the exact amount of money you need to spend.OutputFor each test case, if you can reach cell (n, m) spending exactly k burles, print YES. Otherwise, print NO.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).ExampleInput 6 1 1 0 2 2 2 2 2 3 2 2 4 1 4 3 100 100 10000 Output YES NO YES NO YES NO NoteIn the first test case, you are already in the final cell, so you spend 0 burles.In the second, third and fourth test cases, there are two paths from (1, 1) to (2, 2): (1, 1) \rightarrow (1, 2) \rightarrow (2, 2) or (1, 1) \rightarrow (2, 1) \rightarrow (2, 2). Both costs 1 + 2 = 3 burles, so it's the only amount of money you can spend.In the fifth test case, there is the only way from (1, 1) to (1, 4) and it costs 1 + 1 + 1 = 3 burles.
6 1 1 0 2 2 2 2 2 3 2 2 4 1 4 3 100 100 10000
YES NO YES NO YES NO
2 seconds
256 megabytes
['dp', 'math', '*800']
A. Red and Blue Beanstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: has at least one red bean (or the number of red beans r_i \ge 1); has at least one blue bean (or the number of blue beans b_i \ge 1); the number of red and blue beans should differ in no more than d (or |r_i - b_i| \le d) Can you distribute all beans?InputThe first line contains the single integer t (1 \le t \le 1000) — the number of test cases.The first and only line of each test case contains three integers r, b, and d (1 \le r, b \le 10^9; 0 \le d \le 10^9) — the number of red and blue beans and the maximum absolute difference in each packet.OutputFor each test case, if you can distribute all beans, print YES. Otherwise, print NO.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).ExampleInput 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO NoteIn the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 \le d.In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one.In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d.In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r \neq b.
4 1 1 0 2 7 3 6 1 4 5 4 0
YES YES NO NO
1 second
256 megabytes
['math', '*800']
H. Fly Around the Worldtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter hearing the story of Dr. Zhang, Wowo decides to plan his own flight around the world. He already chose n checkpoints in the world map. Due to the landform and the clouds, he cannot fly too high or too low. Formally, let b_i be the height of Wowo's aircraft at checkpoint i, x_i^-\le b_i\le x_i^+ should be satisfied for all integers i between 1 and n, where x_i^- and x_i^+ are given integers.The angle of Wowo's aircraft is also limited. For example, it cannot make a 90-degree climb. Formally, y_i^-\le b_i-b_{i-1}\le y_i^+ should be satisfied for all integers i between 2 and n, where y_i^- and y_i^+ are given integers.The final limitation is the speed of angling up or angling down. An aircraft should change its angle slowly for safety concerns. Formally, z_i^- \le (b_i - b_{i-1}) - (b_{i-1} - b_{i-2}) \le z_i^+ should be satisfied for all integers i between 3 and n, where z_i^- and z_i^+ are given integers.Taking all these into consideration, Wowo finds that the heights at checkpoints are too hard for him to choose. Please help Wowo decide whether there exists a sequence of real numbers b_1, \ldots, b_n satisfying all the contraints above.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 66\,666). Description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 100\,000).The i-th of the next n lines contains two integers x_i^-, x_i^+ (-10^8\le x_i^-\le x_i^+\le 10^8) denoting the lower and upper bound of b_i. The i-th of the next n-1 lines contains two integers y_{i+1}^-, y_{i+1}^+ (-10^8\le y_{i+1}^-\le y_{i+1}^+\le 10^8) denoting the lower and upper bound of b_{i+1}-b_i. The i-th of the next n-2 lines contains two integers z_{i+2}^-, z_{i+2}^+ (-10^8\le z_{i+2}^-\le z_{i+2}^+\le 10^8) denoting the lower and upper bound of (b_{i+2}-b_{i+1}) - (b_{i+1}-b_i). It is guaranteed that the sum of n over all test cases does not exceed 200\,000.It is guaranteed that relaxing every constraint by 10^{-6} (i.e., decrease x_i^-, y_i^-, z_i^- by 10^{-6} and increase x_i^+, y_i^+, z_i^+ by 10^{-6}) will not change the answer. OutputFor each test case, output YES if a sequence b_1,\ldots, b_n satisfying the constraints exists and NO otherwise. The sequence b_1,\ldots, b_n is not required.ExampleInput 4 3 0 1 0 1 0 1 1 1 1 1 -100 100 3 -967 541 -500 834 -724 669 -858 978 -964 962 -645 705 4 0 0 0 1 0 1 1 1 0 1 0 1 0 1 0 0 0 0 4 0 0 33 34 65 66 100 100 0 100 0 100 0 100 0 0 0 0 Output NO YES YES NO NoteIn the first test case, all b_i's are in [0,1]. Because of the constraints 1=y_2^-\le b_2-b_1\le y_2^+=1, b_2-b_1 must be 1. So b_2=1 and b_1=0 must hold. Then by 1=y_3^-\le b_3-b_2\le y_3^+=1, b_3 equals 2. This contradicts the constraint of b_3\le 1. So no solution exists.In the second test case, we can let all b_i's be 0.In the third test case, one possible solution is b_1=0, b_2=1/3, b_3=2/3, b_4=1.
4 3 0 1 0 1 0 1 1 1 1 1 -100 100 3 -967 541 -500 834 -724 669 -858 978 -964 962 -645 705 4 0 0 0 1 0 1 1 1 0 1 0 1 0 1 0 0 0 0 4 0 0 33 34 65 66 100 100 0 100 0 100 0 100 0 0 0 0
NO YES YES NO
5 seconds
256 megabytes
['dp', 'geometry', '*3500']
G. Starry Night Campingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the foot of Liyushan Mountain, n tents will be carefully arranged to provide accommodation for those who are willing to experience the joy of approaching nature, the tranquility of the night, and the bright starry sky.The i-th tent is located at the point of (x_i, y_i) and has a weight of w_i. A tent is important if and only if both x_i and y_i are even. You need to remove some tents such that for each remaining important tent (x, y), there do not exist 3 other tents (x'_1, y'_1), (x'_2, y'_2) and (x'_3, y'_3) such that both conditions are true: |x'_j-x|, |y'_j - y|\leq 1 for all j \in \{1, 2, 3\}, and these four tents form a parallelogram (or a rectangle) and one of its sides is parallel to the x-axis. Please maximize the sum of the weights of the tents that are not removed. Print the maximum value.InputThe first line contains a single integer n (1\leq n\leq 1\,000), representing the number of tents.Each of the next n lines contains three integers x_i, y_i and w_i (-10^9\leq x_i,y_i \leq 10^9, 1\leq w_i\leq 10^9), representing the coordinate of the i-th tent and its weight. No two tents are located at the same point.OutputA single integer — the maximum sum of the weights of the remaining tents.ExamplesInput 5 0 0 4 0 1 5 1 0 3 1 1 1 -1 1 2 Output 12 Input 32 2 2 1 2 3 1 3 2 1 3 3 1 2 6 1 2 5 1 3 6 1 3 5 1 2 8 1 2 9 1 1 8 1 1 9 1 2 12 1 2 11 1 1 12 1 1 11 1 6 2 1 7 2 1 6 3 1 5 3 1 6 6 1 7 6 1 5 5 1 6 5 1 6 8 1 5 8 1 6 9 1 7 9 1 6 12 1 5 12 1 6 11 1 7 11 1 Output 24 NoteHere is an illustration of the second example. Black triangles indicate the important tents. This example also indicates all 8 forbidden patterns.
5 0 0 4 0 1 5 1 0 3 1 1 1 -1 1 2
12
2 seconds
256 megabytes
['constructive algorithms', 'flows', 'graphs', '*3300']
F. Reuniontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is reported that the 2050 Conference will be held in Yunqi Town in Hangzhou from April 23 to 25, including theme forums, morning jogging, camping and so on.The relationship between the n volunteers of the 2050 Conference can be represented by a tree (a connected undirected graph with n vertices and n-1 edges). The n vertices of the tree corresponds to the n volunteers and are numbered by 1,2,\ldots, n.We define the distance between two volunteers i and j, dis(i,j) as the number of edges on the shortest path from vertex i to vertex j on the tree. dis(i,j)=0 whenever i=j.Some of the volunteers can attend the on-site reunion while others cannot. If for some volunteer x and nonnegative integer r, all volunteers whose distance to x is no more than r can attend the on-site reunion, a forum with radius r can take place. The level of the on-site reunion is defined as the maximum possible radius of any forum that can take place.Assume that each volunteer can attend the on-site reunion with probability \frac{1}{2} and these events are independent. Output the expected level of the on-site reunion. When no volunteer can attend, the level is defined as -1. When all volunteers can attend, the level is defined as n. InputThe first line contains a single integer n (2\le n\le 300) denoting the number of volunteers.Each of the next n-1 lines contains two integers a and b denoting an edge between vertex a and vertex b.OutputOutput the expected level modulo 998\,244\,353.Formally, let M = 998\,244\,353. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExamplesInput 3 1 2 2 3 Output 499122177 Input 5 1 2 2 3 3 4 3 5 Output 249561089 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 Output 821796866 NoteFor the first example, the following table shows all possible outcomes. yes means the volunteer can attend the on-site reunion and no means he cannot attend. \begin{array}{cccc} 1 & 2 & 3 & level\\ yes & yes & yes & 3\\ yes & yes & no & 1\\ yes & no & yes & 0\\ yes & no & no & 0\\ no & yes & yes & 1\\ no & yes & no & 0\\ no & no & yes & 0\\ no & no & no & -1\\ \end{array} The expected level is \frac{3+1+1+(-1)}{2^3}=\frac{1}{2}.
3 1 2 2 3
499122177
3 seconds
256 megabytes
['combinatorics', 'dp', 'trees', '*3200']
E. Group Phototime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the 2050 Conference, some people from the competitive programming community meet together and are going to take a photo. The n people form a line. They are numbered from 1 to n from left to right. Each of them either holds a cardboard with the letter 'C' or a cardboard with the letter 'P'.Let C=\{c_1,c_2,\dots,c_m\} (c_1<c_2<\ldots <c_m) be the set of people who hold cardboards of 'C'. Let P=\{p_1,p_2,\dots,p_k\} (p_1<p_2<\ldots <p_k) be the set of people who hold cardboards of 'P'. The photo is good if and only if it satisfies the following constraints: C\cup P=\{1,2,\dots,n\} C\cap P =\emptyset . c_i-c_{i-1}\leq c_{i+1}-c_i(1< i <m). p_i-p_{i-1}\geq p_{i+1}-p_i(1< i <k). Given an array a_1,\ldots, a_n, please find the number of good photos satisfying the following condition: \sum\limits_{x\in C} a_x < \sum\limits_{y\in P} a_y.The answer can be large, so output it modulo 998\,244\,353. Two photos are different if and only if there exists at least one person who holds a cardboard of 'C' in one photo but holds a cardboard of 'P' in the other.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 200\,000). Description of the test cases follows.The first line of each test case contains a single integer n (1\leq n\leq 200\,000).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 200\,000.OutputFor each test case, output the answer modulo 998\,244\,353 in a separate line.ExampleInput 3 5 2 1 2 1 1 4 9 2 2 2 1 998244353 Output 10 7 1 NoteFor the first test case, there are 10 possible good photos satisfying the condition: PPPPP, CPPPP, PCPPP, CCPPP, PCCPP, PCPCP, PPPPC, CPPPC, PCPPC, PPPCC.For the second test case, there are 7 possible good photos satisfying the condition: PPPP, PCPP, PCCP, PPPC, PCPC, PPCC, PCCC.
3 5 2 1 2 1 1 4 9 2 2 2 1 998244353
10 7 1
1 second
256 megabytes
['binary search', 'data structures', 'implementation', 'two pointers', '*2500']
D. Explorer Spacetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are wandering in the explorer space of the 2050 Conference.The explorer space can be viewed as an undirected weighted grid graph with size n\times m. The set of vertices is \{(i, j)|1\le i\le n, 1\le j\le m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.InputThe first line contains three integers n, m and k (2\leq n, m\leq 500, 1\leq k\leq 20).The j-th number (1\le j \le m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1). The j-th number (1\le j\le m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j). The number of exhibits on each edge is an integer between 1 and 10^6.OutputOutput n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1. ExamplesInput 3 3 10 1 1 1 1 1 1 1 1 1 1 1 1 Output 10 10 10 10 10 10 10 10 10 Input 2 2 4 1 3 4 2 Output 4 4 10 6 Input 2 2 3 1 2 3 4 Output -1 -1 -1 -1 NoteIn the first example, the answer is always 10 no matter how you walk.In the second example, answer_{21} = 10, the path is (2,1) \to (1,1) \to (1,2) \to (2,2) \to (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
3 3 10 1 1 1 1 1 1 1 1 1 1 1 1
10 10 10 10 10 10 10 10 10
2 seconds
256 megabytes
['dp', 'graphs', 'shortest paths', '*1800']
C. Fillomino 2time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:Consider an n by n chessboard. Its rows are numbered from 1 to n from the top to the bottom. Its columns are numbered from 1 to n from the left to the right. A cell on an intersection of x-th row and y-th column is denoted (x, y). The main diagonal of the chessboard is cells (x, x) for all 1 \le x \le n.A permutation of \{1, 2, 3, \dots, n\} is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly 1+2+ \ldots +n such cells) into n connected regions satisfying the following constraints: Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell. The x-th region should contain cell on the main diagonal with number x for all 1\le x\le n. The number of cells that belong to the x-th region should be equal to x for all 1\le x\le n. Each cell under and on the main diagonal should belong to exactly one region. InputThe first line contains a single integer n (1\le n \le 500) denoting the size of the chessboard.The second line contains n integers p_1, p_2, ..., p_n. p_i is the number written on cell (i, i). It is guaranteed that each integer from \{1, \ldots, n\} appears exactly once in p_1, ..., p_n.OutputIf no solution exists, output -1.Otherwise, output n lines. The i-th line should contain i numbers. The j-th number on the i-th line should be x if cell (i, j) belongs to the the region with x cells.ExamplesInput 3 2 3 1 Output 2 2 3 3 3 1 Input 5 1 2 3 4 5 Output 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 NoteThe solutions to the examples are illustrated in the following pictures:
3 2 3 1
2 2 3 3 3 1
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'greedy', 'implementation', '*1400']
B. Morning Joggingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.There are n+1 checkpoints on the trail. They are numbered by 0, 1, ..., n. A runner must start at checkpoint 0 and finish at checkpoint n. No checkpoint is skippable — he must run from checkpoint 0 to checkpoint 1, then from checkpoint 1 to checkpoint 2 and so on. Look at the picture in notes section for clarification.Between any two adjacent checkpoints, there are m different paths to choose. For any 1\le i\le n, to run from checkpoint i-1 to checkpoint i, a runner can choose exactly one from the m possible paths. The length of the j-th path between checkpoint i-1 and i is b_{i,j} for any 1\le j\le m and 1\le i\le n.To test the trail, we have m runners. Each runner must run from the checkpoint 0 to the checkpoint n once, visiting all the checkpoints. Every path between every pair of adjacent checkpoints needs to be ran by exactly one runner. If a runner chooses the path of length l_i between checkpoint i-1 and i (1\le i\le n), his tiredness is \min_{i=1}^n l_i, i. e. the minimum length of the paths he takes.Please arrange the paths of the m runners to minimize the sum of tiredness of them.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10\,000). Description of the test cases follows.The first line of each test case contains two integers n and m (1 \leq n,m \leq 100).The i-th of the next n lines contains m integers b_{i,1}, b_{i,2}, ..., b_{i,m} (1 \le b_{i,j} \le 10^9).It is guaranteed that the sum of n\cdot m over all test cases does not exceed 10^4.OutputFor each test case, output n lines. The j-th number in the i-th line should contain the length of the path that runner j chooses to run from checkpoint i-1 to checkpoint i. There should be exactly m integers in the i-th line and these integers should form a permuatation of b_{i, 1}, ..., b_{i, m} for all 1\le i\le n.If there are multiple answers, print any.ExampleInput 2 2 3 2 3 4 1 3 5 3 2 2 3 4 1 3 5 Output 2 3 4 5 3 1 2 3 4 1 3 5 NoteIn the first case, the sum of tiredness is \min(2,5) + \min(3,3) + \min(4,1) = 6. In the second case, the sum of tiredness is \min(2,4,3) + \min(3,1,5) = 3.
2 2 3 2 3 4 1 3 5 3 2 2 3 4 1 3 5
2 3 4 5 3 1 2 3 4 1 3 5
1 second
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*1200']
A. Sum of 2050time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA number is called 2050-number if it is 2050, 20500, ..., (2050 \cdot 10^k for integer k \ge 0).Given a number n, you are asked to represent n as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.InputThe first line contains a single integer T (1\le T\leq 1\,000) denoting the number of test cases.The only line of each test case contains a single integer n (1\le n\le 10^{18}) denoting the number to be represented.OutputFor each test case, output the minimum number of 2050-numbers in one line. If n cannot be represented as the sum of 2050-numbers, output -1 instead. ExampleInput 6 205 2050 4100 20500 22550 25308639900 Output -1 1 2 1 2 36 NoteIn the third case, 4100 = 2050 + 2050.In the fifth case, 22550 = 20500 + 2050.
6 205 2050 4100 20500 22550 25308639900
-1 1 2 1 2 36
1 second
256 megabytes
['greedy', 'math', '*800']
E. Baby Ehab Plays with Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis time around, Baby Ehab will play with permutations. He has n cubes arranged in a row, with numbers from 1 to n written on them. He'll make exactly j operations. In each operation, he'll pick up 2 cubes and switch their positions.He's wondering: how many different sequences of cubes can I have at the end? Since Baby Ehab is a turbulent person, he doesn't know how many operations he'll make, so he wants the answer for every possible j between 1 and k.InputThe only line contains 2 integers n and k (2 \le n \le 10^9, 1 \le k \le 200) — the number of cubes Baby Ehab has, and the parameter k from the statement.OutputPrint k space-separated integers. The i-th of them is the number of possible sequences you can end up with if you do exactly i operations. Since this number can be very large, print the remainder when it's divided by 10^9+7.ExamplesInput 2 3 Output 1 1 1 Input 3 2 Output 3 3 Input 4 2 Output 6 12 NoteIn the second example, there are 3 sequences he can get after 1 swap, because there are 3 pairs of cubes he can swap. Also, there are 3 sequences he can get after 2 swaps: [1,2,3], [3,1,2], [2,3,1].
2 3
1 1 1
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*2500']
D. Cuttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following: he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, \ldots, a_r out, removing the rest of the array. he then cuts this range into multiple subranges. to add a number theory spice to it, he requires that the elements of every subrange must have their product equal to their least common multiple (LCM). Formally, he partitions the elements of a_l, a_{l + 1}, \ldots, a_r into contiguous subarrays such that the product of every subarray is equal to its LCM. Now, for q independent ranges (l, r), tell Baby Ehab the minimum number of subarrays he needs.InputThe first line contains 2 integers n and q (1 \le n,q \le 10^5) — the length of the array a and the number of queries.The next line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^5) — the elements of the array a.Each of the next q lines contains 2 integers l and r (1 \le l \le r \le n) — the endpoints of this query's interval.OutputFor each query, print its answer on a new line.ExampleInput 6 3 2 3 10 7 5 14 1 6 2 4 3 5 Output 3 1 2 NoteThe first query asks about the whole array. You can partition it into [2], [3,10,7], and [5,14]. The first subrange has product and LCM equal to 2. The second has product and LCM equal to 210. And the third has product and LCM equal to 70. Another possible partitioning is [2,3], [10,7], and [5,14].The second query asks about the range (2,4). Its product is equal to its LCM, so you don't need to partition it further.The last query asks about the range (3,5). You can partition it into [10,7] and [5].
6 3 2 3 10 7 5 14 1 6 2 4 3 5
3 1 2
1 second
256 megabytes
['binary search', 'data structures', 'dp', 'graphs', 'number theory', 'two pointers', '*2100']
C. Baby Ehab Partitions Againtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBaby Ehab was toying around with arrays. He has an array a of length n. He defines an array to be good if there's no way to partition it into 2 subsequences such that the sum of the elements in the first is equal to the sum of the elements in the second. Now he wants to remove the minimum number of elements in a so that it becomes a good array. Can you help him?A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero or all) elements. A partitioning of an array is a way to divide it into 2 subsequences such that every element belongs to exactly one subsequence, so you must use all the elements, and you can't share any elements.InputThe first line contains an integer n (2 \le n \le 100) — the length of the array a.The second line contains n integers a_1, a_2, \ldots, a_{n} (1 \le a_i \le 2000) — the elements of the array a.OutputThe first line should contain the minimum number of elements you need to remove.The second line should contain the indices of the elements you're removing, separated by spaces.We can show that an answer always exists. If there are multiple solutions, you can print any.ExamplesInput 4 6 3 9 12 Output 1 2Input 2 1 2 Output 0NoteIn the first example, you can partition the array into [6,9] and [3,12], so you must remove at least 1 element. Removing 3 is sufficient.In the second example, the array is already good, so you don't need to remove any elements.
4 6 3 9 12
1 2
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'math', '*1700']
B. AGAGA XOOORRRtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBaby Ehab is known for his love for a certain operation. He has an array a of length n, and he decided to keep doing the following operation on it: he picks 2 adjacent elements; he then removes them and places a single integer in their place: their bitwise XOR. Note that the length of the array decreases by one. Now he asks you if he can make all elements of the array equal. Since babies like to make your life harder, he requires that you leave at least 2 elements remaining.InputThe first line contains an integer t (1 \le t \le 15) — the number of test cases you need to solve.The first line of each test case contains an integers n (2 \le n \le 2000) — the number of elements in the array a.The second line contains n space-separated integers a_1, a_2, \ldots, a_{n} (0 \le a_i < 2^{30}) — the elements of the array a.OutputIf Baby Ehab can make all elements equal while leaving at least 2 elements standing, print "YES". Otherwise, print "NO".ExampleInput 2 3 0 2 2 4 2 3 1 10 Output YES NO NoteIn the first sample, he can remove the first 2 elements, 0 and 2, and replace them by 0 \oplus 2=2. The array will be [2,2], so all the elements are equal.In the second sample, there's no way to make all the elements equal.
2 3 0 2 2 4 2 3 1 10
YES NO
1 second
256 megabytes
['bitmasks', 'brute force', 'dp', 'greedy', '*1500']
A. Tit for Tattime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a of length n, you can do at most k operations of the following type on it: choose 2 different elements in the array, add 1 to the first, and subtract 1 from the second. However, all the elements of a have to remain non-negative after this operation. What is lexicographically the smallest array you can obtain?An array x is lexicographically smaller than an array y if there exists an index i such that x_i<y_i, and x_j=y_j for all 1 \le j < i. Less formally, at the first index i in which they differ, x_i<y_i.InputThe first line contains an integer t (1 \le t \le 20) – the number of test cases you need to solve.The first line of each test case contains 2 integers n and k (2 \le n \le 100, 1 \le k \le 10000) — the number of elements in the array and the maximum number of operations you can make.The second line contains n space-separated integers a_1, a_2, \ldots, a_{n} (0 \le a_i \le 100) — the elements of the array a.OutputFor each test case, print the lexicographically smallest array you can obtain after at most k operations.ExampleInput 2 3 1 3 1 4 2 10 1 0 Output 2 1 5 0 1 NoteIn the second test case, we start by subtracting 1 from the first element and adding 1 to the second. Then, we can't get any lexicographically smaller arrays, because we can't make any of the elements negative.
2 3 1 3 1 4 2 10 1 0
2 1 5 0 1
1 second
256 megabytes
['greedy', '*800']
I. Phoenix and Diamondstime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputPhoenix wonders what it is like to rob diamonds from a jewelry store!There are n types of diamonds. The i-th type has weight w_i and value v_i. The store initially has a_i diamonds of the i-th type.Each day, for q days, one of the following will happen: A new shipment of k_i diamonds of type d_i arrive. The store sells k_i diamonds of type d_i. Phoenix wonders what will happen if he robs the store using a bag that can fit diamonds with total weight not exceeding c_i. If he greedily takes diamonds of the largest value that fit, how much value would be taken? If there are multiple diamonds with the largest value, he will take the one with minimum weight. If, of the diamonds with the largest value, there are multiple with the same minimum weight, he will take any of them. Of course, since Phoenix is a law-abiding citizen, this is all a thought experiment and he never actually robs any diamonds from the store. This means that queries of type 3 do not affect the diamonds in the store.InputThe first line contains two integers n and q (1 \le n \le 2 \cdot 10^5; 1 \le q \le 10^5) — the number of types of diamonds and number of days, respectively.The next n lines describe each type of diamond. The i-th line will contain three integers a_i, w_i, and v_i (0 \le a_i \le 10^5; 1 \le w_i, v_i \le 10^5) — the initial number of diamonds of the i-th type, the weight of diamonds of the i-th type, and the value of diamonds of the i-th type, respectively.The next q lines contain the queries. For each query, the first integer of each line is t (1 \le t \le 3) — the type of query.If t=1, then two integers k_i, d_i follow (1 \le k_i \le 10^5; 1 \le d_i \le n). This means that a new shipment of k_i diamonds arrived, each of type d_i.If t=2, then two integers k_i, d_i follow (1 \le k_i \le 10^5; 1 \le d_i \le n). This means that the store has sold k_i diamonds, each of type d_i. It is guaranteed that the store had the diamonds before they sold them.If t=3, an integer c_i will follow (1 \le c_i \le 10^{18}) — the weight capacity of Phoenix's bag.It is guaranteed that there is at least one query where t=3.OutputPrint the answer for each query of the third type (t=3).ExampleInput 3 5 2 3 4 1 5 1 0 2 4 3 6 1 3 3 3 10 2 2 3 3 30 Output 8 16 13 NoteFor the first query where t=3, Phoenix can fit 2 diamonds of type 1, with total weight 6 and value 8.For the second query where t=3, Phoenix will first fit in 3 diamonds of type 3, then one diamond of type 1 for a total weight of 9 and a value of 16. Note that diamonds of type 3 are prioritized over type 1 because type 3 has equal value but less weight.For the final query where t=3, Phoenix can fit every diamond for a total value of 13.
3 5 2 3 4 1 5 1 0 2 4 3 6 1 3 3 3 10 2 2 3 3 30
8 16 13
5 seconds
1024 megabytes
['binary search', 'data structures', 'sortings', '*3400']
H. Phoenix and Bitstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPhoenix loves playing with bits — specifically, by using the bitwise operations AND, OR, and XOR. He has n integers a_1, a_2, \dots, a_n, and will perform q of the following queries: replace all numbers a_i where l \le a_i \le r with a_i AND x; replace all numbers a_i where l \le a_i \le r with a_i OR x; replace all numbers a_i where l \le a_i \le r with a_i XOR x; output how many distinct integers a_i where l \le a_i \le r. For each query, Phoenix is given l, r, and x. Note that he is considering the values of the numbers, not their indices.InputThe first line contains two integers n and q (1 \le n \le 2 \cdot 10^5; 1 \le q \le 10^5) — the number of integers and the number of queries, respectively.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i < 2^{20}) — the integers that Phoenix starts with.The next q lines contain the queries. For each query, the first integer of each line is t (1 \le t \le 4) — the type of query.If t \in \{1, 2, 3\}, then three integers l_i, r_i, and x_i will follow (0 \le l_i, r_i, x_i < 2^{20}; l_i \le r_i).Otherwise, if t=4, two integers l_i and r_i will follow (0 \le l_i \le r_i < 2^{20}).It is guaranteed that there is at least one query where t=4.OutputPrint the answer for each query where t=4.ExamplesInput 5 6 5 4 3 2 1 1 2 3 2 4 2 5 3 2 5 3 4 1 6 2 1 1 8 4 8 10 Output 3 2 1 Input 6 7 6 0 2 3 2 7 1 0 4 3 2 6 8 4 4 0 7 3 2 5 3 1 0 1 2 4 0 3 4 2 7 Output 5 1 2 NoteIn the first example: For the first query, 2 is replaced by 2 AND 2 = 2 and 3 is replaced with 3 AND 2 = 2. The set of numbers is \{1, 2, 4, 5\}. For the second query, there are 3 distinct numbers between 2 and 5: 2, 4, and 5. For the third query, 2 is replaced by 2 XOR 3 = 1, 4 is replaced by 4 XOR 3 = 7, and 5 is replaced by 5 XOR 3 = 6. The set of numbers is \{1, 6, 7\}. For the fourth query, there are 2 distinct numbers between 1 and 6: 1 and 6. For the fifth query, 1 is replaced by 1 OR 8 = 9. The set of numbers is \{6, 7, 9\}. For the sixth query, there is one distinct number between 8 and 10: 9.
5 6 5 4 3 2 1 1 2 3 2 4 2 5 3 2 5 3 4 1 6 2 1 1 8 4 8 10
3 2 1
4 seconds
512 megabytes
['bitmasks', 'brute force', 'data structures', 'sortings', '*3500']
G. Phoenix and Odometerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Fire City, there are n intersections and m one-way roads. The i-th road goes from intersection a_i to b_i and has length l_i miles. There are q cars that may only drive along those roads. The i-th car starts at intersection v_i and has an odometer that begins at s_i, increments for each mile driven, and resets to 0 whenever it reaches t_i. Phoenix has been tasked to drive cars along some roads (possibly none) and return them to their initial intersection with the odometer showing 0.For each car, please find if this is possible. A car may visit the same road or intersection an arbitrary number of times. The odometers don't stop counting the distance after resetting, so odometers may also be reset an arbitrary number of times.InputThe first line of the input 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 intersections and the number of roads, respectively.Each of the next m lines contain three integers a_i, b_i, and l_i (1 \le a_i, b_i \le n; a_i \neq b_i; 1 \le l_i \le 10^9) — the information about the i-th road. The graph is not necessarily connected. It is guaranteed that between any two intersections, there is at most one road for each direction.The next line contains an integer q (1 \le q \le 2 \cdot 10^5) — the number of cars.Each of the next q lines contains three integers v_i, s_i, and t_i (1 \le v_i \le n; 0 \le s_i < t_i \le 10^9) — the initial intersection of the i-th car, the initial number on the i-th odometer, and the number at which the i-th odometer resets, respectively.OutputPrint q answers. If the i-th car's odometer may be reset to 0 by driving through some roads (possibly none) and returning to its starting intersection v_i, print YES. Otherwise, print NO.ExamplesInput 4 4 1 2 1 2 3 1 3 1 2 1 4 3 3 1 1 3 1 2 4 4 0 1 Output YES NO YES Input 4 5 1 2 1 2 3 1 3 1 2 1 4 1 4 3 2 2 1 2 4 4 3 5 Output YES YES NoteThe illustration for the first example is below: In the first query, Phoenix can drive through the following cities: 1 \rightarrow 2 \rightarrow 3 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 1. The odometer will have reset 3 times, but it displays 0 at the end.In the second query, we can show that there is no way to reset the odometer to 0 and return to intersection 1.In the third query, the odometer already displays 0, so there is no need to drive through any roads.Below is the illustration for the second example:
4 4 1 2 1 2 3 1 3 1 2 1 4 3 3 1 1 3 1 2 4 4 0 1
YES NO YES
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'math', 'number theory', '*2700']