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
E. Fixed Pointstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a sequence of integers a_1, a_2, \ldots, a_n. In one move, you can select any element of the sequence and delete it. After an element is deleted, all elements to the right are shifted to the left by 1 position, so there are no empty spaces in the sequence. So after you make a move, the sequence's length decreases by 1. The indices of the elements after the move are recalculated.E. g. let the sequence be a=[3, 2, 2, 1, 5]. Let's select the element a_3=2 in a move. Then after the move the sequence will be equal to a=[3, 2, 1, 5], so the 3-rd element of the new sequence will be a_3=1 and the 4-th element will be a_4=5.You are given a sequence a_1, a_2, \ldots, a_n and a number k. You need to find the minimum number of moves you have to make so that in the resulting sequence there will be at least k elements that are equal to their indices, i. e. the resulting sequence b_1, b_2, \ldots, b_m will contain at least k indices i such that b_i = i.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.Each test case consists of two consecutive lines. The first line contains two integers n and k (1 \le k \le n \le 2000). The second line contains a sequence of integers a_1, a_2, \ldots, a_n (1 \le a_i \le n). The numbers in the sequence are not necessarily different.It is guaranteed that the sum of n over all test cases doesn't exceed 2000.OutputFor each test case output in a single line: -1 if there's no desired move sequence; otherwise, the integer x (0 \le x \le n) — the minimum number of the moves to be made so that the resulting sequence will contain at least k elements that are equal to their indices. ExampleInput 4 7 6 1 1 2 3 4 5 6 5 2 5 1 3 2 3 5 2 5 5 5 5 4 8 4 1 2 3 3 2 2 5 5 Output 1 2 -1 2 NoteIn the first test case the sequence doesn't satisfy the desired condition, but it can be provided by deleting the first element, hence the sequence will be [1, 2, 3, 4, 5, 6] and 6 elements will be equal to their indices.In the second test case there are two ways to get the desired result in 2 moves: the first one is to delete the 1-st and the 3-rd elements so that the sequence will be [1, 2, 3] and have 3 elements equal to their indices; the second way is to delete the 2-nd and the 3-rd elements to get the sequence [5, 2, 3] with 2 desired elements.
4 7 6 1 1 2 3 4 5 6 5 2 5 1 3 2 3 5 2 5 5 5 5 4 8 4 1 2 3 3 2 2 5 5
1 2 -1 2
1 second
256 megabytes
['binary search', 'brute force', 'dp', '*2000']
D2. Domino (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and D1 is that you don't have to provide the way to construct the answer in D1, but you have to do it in this problem.There's a table of n \times m cells (n rows and m columns). The value of n \cdot m is even.A domino is a figure that consists of two cells having a common side. It may be horizontal (one of the cells is to the right of the other) or vertical (one of the cells is above the other).You need to place \frac{nm}{2} dominoes on the table so that exactly k of them are horizontal and all the other dominoes are vertical. The dominoes cannot overlap and must fill the whole table.InputThe first line contains one integer t (1 \le t \le 10) — the number of test cases. Then t test cases follow.Each test case consists of a single line. The line contains three integers n, m, k (1 \le n,m \le 100, 0 \le k \le \frac{nm}{2}, n \cdot m is even) — the count of rows, columns and horizontal dominoes, respectively.OutputFor each test case: print "NO" if it's not possible to place the dominoes on the table in the described way; otherwise, print "YES" on a separate line, then print n lines so that each of them contains m lowercase letters of the Latin alphabet — the layout of the dominoes on the table. Each cell of the table must be marked by the letter so that for every two cells having a common side, they are marked by the same letters if and only if they are occupied by the same domino. I.e. both cells of the same domino must be marked with the same letter, but two dominoes that share a side must be marked with different letters. If there are multiple solutions, print any of them. ExampleInput 8 4 4 2 2 3 0 3 2 3 1 2 0 2 4 2 5 2 2 2 17 16 2 1 1 Output YES accx aegx bega bdda YES aha aha YES zz aa zz NO YES aaza bbza NO YES bbaabbaabbaabbaay ddccddccddccddccy NO
8 4 4 2 2 3 0 3 2 3 1 2 0 2 4 2 5 2 2 2 17 16 2 1 1
YES accx aegx bega bdda YES aha aha YES zz aa zz NO YES aaza bbza NO YES bbaabbaabbaabbaay ddccddccddccddccy NO
1 second
256 megabytes
['constructive algorithms', 'implementation', 'math', '*2100']
D1. Domino (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and D2 is that you don't have to provide the way to construct the answer in this problem, but you have to do it in D2.There's a table of n \times m cells (n rows and m columns). The value of n \cdot m is even.A domino is a figure that consists of two cells having a common side. It may be horizontal (one of the cells is to the right of the other) or vertical (one of the cells is above the other).You need to find out whether it is possible to place \frac{nm}{2} dominoes on the table so that exactly k of them are horizontal and all the other dominoes are vertical. The dominoes cannot overlap and must fill the whole table.InputThe first line contains one integer t (1 \le t \le 10) — the number of test cases. Then t test cases follow.Each test case consists of a single line. The line contains three integers n, m, k (1 \le n,m \le 100, 0 \le k \le \frac{nm}{2}, n \cdot m is even) — the number of rows, columns and horizontal dominoes, respectively.OutputFor each test case output "YES", if it is possible to place dominoes in the desired way, or "NO" otherwise.You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).ExampleInput 8 4 4 2 2 3 0 3 2 3 1 2 0 2 4 2 5 2 2 2 17 16 2 1 1 Output YES YES YES NO YES NO YES NO
8 4 4 2 2 3 0 3 2 3 1 2 0 2 4 2 5 2 2 2 17 16 2 1 1
YES YES YES NO YES NO YES NO
1 second
256 megabytes
['constructive algorithms', 'math', '*1700']
C. Interesting Storytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'!To compose a story, Stephen wrote out n words consisting of the first 5 lowercase letters of the Latin alphabet. He wants to select the maximum number of words to make an interesting story.Let a story be a sequence of words that are not necessarily different. A story is called interesting if there exists a letter which occurs among all words of the story more times than all other letters together.For example, the story consisting of three words "bac", "aaada", "e" is interesting (the letter 'a' occurs 5 times, all other letters occur 4 times in total). But the story consisting of two words "aba", "abcde" is not (no such letter that it occurs more than all other letters in total).You are given a sequence of n words consisting of letters 'a', 'b', 'c', 'd' and 'e'. Your task is to choose the maximum number of them to make an interesting story. If there's no way to make a non-empty story, output 0.InputThe first line contains one integer t (1 \le t \le 5000) — the number of test cases. 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 number of the words in the sequence. Then n lines follow, each of them contains a word — a non-empty string consisting of lowercase letters of the Latin alphabet. The words in the sequence may be non-distinct (i. e. duplicates are allowed). Only the letters 'a', 'b', 'c', 'd' and 'e' may occur in the words.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5; the sum of the lengths of all words over all test cases doesn't exceed 4 \cdot 10^5.OutputFor each test case, output the maximum number of words that compose an interesting story. Print 0 if there's no way to make a non-empty interesting story.ExampleInput 6 3 bac aaada e 3 aba abcde aba 2 baba baba 4 ab ab c bc 5 cbdca d a d e 3 b c ca Output 3 2 0 2 3 2 NoteIn the first test case of the example, all 3 words can be used to make an interesting story. The interesting story is "bac aaada e".In the second test case of the example, the 1-st and the 3-rd words can be used to make an interesting story. The interesting story is "aba aba". Stephen can't use all three words at the same time.In the third test case of the example, Stephen can't make a non-empty interesting story. So the answer is 0.In the fourth test case of the example, Stephen can use the 3-rd and the 4-th words to make an interesting story. The interesting story is "c bc".
6 3 bac aaada e 3 aba abcde aba 2 baba baba 4 ab ab c bc 5 cbdca d a d e 3 b c ca
3 2 0 2 3 2
4 seconds
256 megabytes
['greedy', 'sortings', 'strings', '*1500']
B2. Wonderful Coloring - 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is an extension of the problem "Wonderful Coloring - 1". It has quite many differences, so you should read this statement completely.Recently, Paul and Mary have found a new favorite sequence of integers a_1, a_2, \dots, a_n. They want to paint it using pieces of chalk of k colors. The coloring of a sequence is called wonderful if the following conditions are met: each element of the sequence is either painted in one of k colors or isn't painted; each two elements which are painted in the same color are different (i. e. there's no two equal values painted in the same color); let's calculate for each of k colors the number of elements painted in the color — all calculated numbers must be equal; the total number of painted elements of the sequence is the maximum among all colorings of the sequence which meet the first three conditions. E. g. consider a sequence a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2] and k=3. One of the wonderful colorings of the sequence is shown in the figure. The example of a wonderful coloring of the sequence a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2] and k=3. Note that one of the elements isn't painted. Help Paul and Mary to find a wonderful coloring of a given sequence a.InputThe first line contains one integer t (1 \le t \le 10000) — the number of test cases. Then t test cases follow.Each test case consists of two lines. The first one contains two integers n and k (1 \le n \le 2\cdot10^5, 1 \le k \le n) — the length of a given sequence and the number of colors, respectively. The second one contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n).It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputOutput t lines, each of them must contain a description of a wonderful coloring for the corresponding test case.Each wonderful coloring must be printed as a sequence of n integers c_1, c_2, \dots, c_n (0 \le c_i \le k) separated by spaces where c_i=0, if i-th element isn't painted; c_i>0, if i-th element is painted in the c_i-th color. Remember that you need to maximize the total count of painted elements for the wonderful coloring. If there are multiple solutions, print any one.ExampleInput 6 10 3 3 1 1 1 1 10 3 10 10 2 4 4 1 1 1 1 1 1 1 13 1 3 1 4 1 5 9 2 6 5 3 5 8 9 13 2 3 1 4 1 5 9 2 6 5 3 5 8 9 13 3 3 1 4 1 5 9 2 6 5 3 5 8 9 Output 1 1 0 2 3 2 2 1 3 3 4 2 1 3 1 0 0 1 1 0 1 1 1 0 1 1 1 0 2 1 2 2 1 1 1 1 2 1 0 2 2 1 1 3 2 1 3 3 1 2 2 3 2 0 NoteIn the first test case, the answer is shown in the figure in the statement. The red color has number 1, the blue color — 2, the green — 3.
6 10 3 3 1 1 1 1 10 3 10 10 2 4 4 1 1 1 1 1 1 1 13 1 3 1 4 1 5 9 2 6 5 3 5 8 9 13 2 3 1 4 1 5 9 2 6 5 3 5 8 9 13 3 3 1 4 1 5 9 2 6 5 3 5 8 9
1 1 0 2 3 2 2 1 3 3 4 2 1 3 1 0 0 1 1 0 1 1 1 0 1 1 1 0 2 1 2 2 1 1 1 1 2 1 0 2 2 1 1 3 2 1 3 3 1 2 2 3 2 0
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'greedy', '*1400']
B1. Wonderful Coloring - 1time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1.Paul and Mary have a favorite string s which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a string wonderful if the following conditions are met: each letter of the string is either painted in exactly one color (red or green) or isn't painted; each two letters which are painted in the same color are different; the number of letters painted in red is equal to the number of letters painted in green; the number of painted letters of this coloring is maximum among all colorings of the string which meet the first three conditions. E. g. consider a string s equal to "kzaaa". One of the wonderful colorings of the string is shown in the figure. The example of a wonderful coloring of the string "kzaaa". Paul and Mary want to learn by themselves how to find a wonderful coloring of the string. But they are very young, so they need a hint. Help them find k — the number of red (or green, these numbers are equal) letters in a wonderful coloring.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.Each test case consists of one non-empty string s which consists of lowercase letters of the Latin alphabet. The number of characters in the string doesn't exceed 50.OutputFor each test case, output a separate line containing one non-negative integer k — the number of letters which will be painted in red in a wonderful coloring.ExampleInput 5 kzaaa codeforces archive y xxxxxx Output 2 5 3 0 1 NoteThe first test case contains the string from the statement. One of the wonderful colorings is shown in the figure. There's no wonderful coloring containing 3 or more red letters because the total number of painted symbols will exceed the string's length.The string from the second test case can be painted as follows. Let's paint the first occurrence of each of the letters "c", "o", "e" in red and the second ones in green. Let's paint the letters "d", "f" in red and "r", "s" in green. So every letter will be painted in red or green, hence the answer better than 5 doesn't exist.The third test case contains the string of distinct letters, so you can paint any set of characters in red, as long as the size of this set doesn't exceed half of the size of the string and is the maximum possible.The fourth test case contains a single letter which cannot be painted in red because there will be no letter able to be painted in green.The fifth test case contains a string of identical letters, so there's no way to paint more than one letter in red.
5 kzaaa codeforces archive y xxxxxx
2 5 3 0 1
1 second
256 megabytes
['greedy', 'strings', '*800']
A. Polycarp and Coinstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp must pay exactly n burles at the checkout. He has coins of two nominal values: 1 burle and 2 burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other.Thus, Polycarp wants to minimize the difference between the count of coins of 1 burle and 2 burles being used. Help him by determining two non-negative integer values c_1 and c_2 which are the number of coins of 1 burle and 2 burles, respectively, so that the total value of that number of coins is exactly n (i. e. c_1 + 2 \cdot c_2 = n), and the absolute value of the difference between c_1 and c_2 is as little as possible (i. e. you must minimize |c_1-c_2|).InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case consists of one line. This line contains one integer n (1 \le n \le 10^9) — the number of burles to be paid by Polycarp.OutputFor each test case, output a separate line containing two integers c_1 and c_2 (c_1, c_2 \ge 0) separated by a space where c_1 is the number of coins of 1 burle and c_2 is the number of coins of 2 burles. If there are multiple optimal solutions, print any one.ExampleInput 6 1000 30 1 32 1000000000 5 Output 334 333 10 10 1 0 10 11 333333334 333333333 1 2 NoteThe answer for the first test case is "334 333". The sum of the nominal values of all coins is 334 \cdot 1 + 333 \cdot 2 = 1000, whereas |334 - 333| = 1. One can't get the better value because if |c_1 - c_2| = 0, then c_1 = c_2 and c_1 \cdot 1 + c_1 \cdot 2 = 1000, but then the value of c_1 isn't an integer.The answer for the second test case is "10 10". The sum of the nominal values is 10 \cdot 1 + 10 \cdot 2 = 30 and |10 - 10| = 0, whereas there's no number having an absolute value less than 0.
6 1000 30 1 32 1000000000 5
334 333 10 10 1 0 10 11 333333334 333333333 1 2
1 second
256 megabytes
['greedy', 'math', '*800']
F. Jumping Aroundtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an infinite pond that can be represented with a number line. There are n rocks in the pond, numbered from 1 to n. The i-th rock is located at an integer coordinate a_i. The coordinates of the rocks are pairwise distinct. The rocks are numbered in the increasing order of the coordinate, so a_1 < a_2 < \dots < a_n.A robot frog sits on the rock number s. The frog is programmable. It has a base jumping distance parameter d. There also is a setting for the jumping distance range. If the jumping distance range is set to some integer k, then the frog can jump from some rock to any rock at a distance from d - k to d + k inclusive in any direction. The distance between two rocks is an absolute difference between their coordinates.You are assigned a task to implement a feature for the frog. Given two integers i and k determine if the frog can reach a rock number i from a rock number s performing a sequence of jumps with the jumping distance range set to k. The sequence can be arbitrarily long or empty.You will be given q testcases for that feature, the j-th testcase consists of two integers i and k. Print "Yes" if the i-th rock is reachable and "No" otherwise.You can output "YES" and "NO" in any case (for example, strings "yEs", "yes", "Yes" and 'YES"' will be recognized as a positive answer).InputThe first line contains four integers n, q, s and d (1 \le n, q \le 2 \cdot 10^5; 1 \le s \le n; 1 \le d \le 10^6) — the number of rocks, the number of testcases, the starting rock and the base jumping distance parameter.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6) — the coordinates of the rocks. The coordinates of the rocks are pairwise distinct. The rocks are numbered in the increasing order of distance from the land, so a_1 < a_2 < \dots < a_n.Each of the next q lines contains two integers i and k (1 \le i \le n; 1 \le k \le 10^6) — the parameters to the testcase.OutputFor each of the testcases print an answer. If there is a sequence of jumps from a rock number s to a rock number i with the jumping distance range set to k, then print "Yes". Otherwise, print "No".ExamplesInput 7 4 4 5 1 5 10 13 20 22 28 4 1 7 2 7 3 3 2 Output Yes No Yes Yes Input 10 8 6 11 1 2 4 7 8 9 11 13 19 20 2 13 5 8 8 1 6 15 1 15 2 7 7 6 8 9 Output Yes Yes No Yes Yes Yes Yes Yes Input 6 9 6 6 1 2 4 9 18 19 2 17 1 18 5 4 2 11 5 17 6 8 4 3 3 3 6 6 Output Yes Yes Yes Yes Yes Yes No No Yes Input 4 1 1 10 1 8 10 19 2 1 Output Yes NoteExplanation of the first example:In the first testcase the destination rock is the same as the starting rock, thus no jumps are required to reach it.In the second testcase the frog can jump any distance in the range [5 - 2; 5 + 2]. Thus, it can reach rock number 5 (by jumping 7 to the right) and rock number 3 (by jumping 3 to the left). From rock number 3 it can reach rock number 2 (by jumping 5 to the left). From rock number 2 it can reach rock number 1 (by jumping 4 to the left). However, there is no way to reach rock number 7.In the third testcase the frog can jump any distance in the range [5 - 3; 5 + 3]. Thus, it can reach rock number 7 by jumping to rock 5 first and to 7 afterwards.The fourth testcase is shown in the explanation for the second testcase.
7 4 4 5 1 5 10 13 20 22 28 4 1 7 2 7 3 3 2
Yes No Yes Yes
5 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'dp', 'dsu', 'graphs', 'shortest paths', '*2700']
E. Stringforcestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.The value of a string s is the minimum value among f_i for all i from 1 to k.What is the maximum value the string can have?InputThe first line contains two integers n and k (1 \le n \le 2 \cdot 10^5; 1 \le k \le 17) — the length of the string and the number of first Latin letters used.The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.OutputPrint a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.ExamplesInput 10 2 a??ab????b Output 4 Input 9 4 ????????? Output 2 Input 2 3 ?? Output 0 Input 15 3 ??b?babbc??b?aa Output 3 Input 4 4 cabd Output 1 NoteIn the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.In the second example one of the possible strings is "aabbccdda".In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
10 2 a??ab????b
4
3 seconds
256 megabytes
['binary search', 'bitmasks', 'brute force', 'dp', 'strings', 'two pointers', '*2500']
D. Excellent Arraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an integer array a_1, a_2, \dots, a_n good if a_i \neq i for each i.Let F(a) be the number of pairs (i, j) (1 \le i < j \le n) such that a_i + a_j = i + j.Let's say that an array a_1, a_2, \dots, a_n is excellent if: a is good; l \le a_i \le r for each i; F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7.InputThe first line contains a 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 n, l, and r (2 \le n \le 2 \cdot 10^5; -10^9 \le l \le 1; n \le r \le 10^9).It's guaranteed that the sum of n doesn't exceed 2 \cdot 10^5.OutputFor each test case, print the number of excellent arrays modulo 10^9 + 7.ExampleInput 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 NoteIn the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: [2, 1, 2]; [0, 3, 2]; [2, 3, 2]; [3, 0, 1].
4 3 0 3 4 -3 5 42 -33 55 69 -42 146
4 10 143922563 698570404
2 seconds
256 megabytes
['binary search', 'combinatorics', 'constructive algorithms', 'implementation', 'math', 'sortings', 'two pointers', '*2300']
C. Manhattan Subarraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|.Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r).Let's say that an array b_1, b_2, \dots, b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple.You are given an array a_1, a_2, \dots, a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, \dots, a_r for some 1 \le l \le r \le n.Note that, according to the definition, subarrays of length 1 and 2 are good.InputThe first line contains one integer t (1 \le t \le 5000) — the number of test cases.The first line of each test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of array a.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).It's guaranteed that the sum of n doesn't exceed 2 \cdot 10^5.OutputFor each test case, print the number of good subarrays of array a.ExampleInput 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 NoteIn the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)).
3 4 2 4 1 3 5 6 9 1 9 6 2 13 37
10 12 3
2 seconds
256 megabytes
['brute force', 'geometry', 'greedy', 'implementation', '*1700']
B. Maximum Cost Deletiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length l, you get a \cdot l + b points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.InputThe first line contains a single integer t (1 \le t \le 2000) — the number of testcases.The first line of each testcase contains three integers n, a and b (1 \le n \le 100; -100 \le a, b \le 100) — the length of the string s and the parameters a and b.The second line contains the string s. The string s consists only of the characters 0 and 1.OutputFor each testcase, print a single integer — the maximum number of points that you can score.ExampleInput 3 3 2 0 000 5 -2 5 11001 6 1 -4 100111 Output 6 15 -2 NoteIn the first example, it is enough to delete the entire string, then we will get 2 \cdot 3 + 0 = 6 points.In the second example, if we delete characters one by one, then for each deleted character we will get (-2) \cdot 1 + 5 = 3 points, i. e. 15 points in total.In the third example, we can delete the substring 00 from the string 100111, we get 1 \cdot 2 + (-4) = -2 points, and the string will be equal to 1111, removing it entirely we get 1 \cdot 4 + (-4) = 0 points. In total, we got -2 points for 2 operations.
3 3 2 0 000 5 -2 5 11001 6 1 -4 100111
6 15 -2
2 seconds
256 megabytes
['greedy', 'math', '*1000']
A. Find The Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an array a consisting of n positive (greater than 0) integers beautiful if the following condition is held for every i from 1 to n: either a_i = 1, or at least one of the numbers a_i - 1 and a_i - 2 exists in the array as well.For example: the array [5, 3, 1] is beautiful: for a_1, the number a_1 - 2 = 3 exists in the array; for a_2, the number a_2 - 2 = 1 exists in the array; for a_3, the condition a_3 = 1 holds; the array [1, 2, 2, 2, 2] is beautiful: for a_1, the condition a_1 = 1 holds; for every other number a_i, the number a_i - 1 = 1 exists in the array; the array [1, 4] is not beautiful: for a_2, neither a_2 - 2 = 2 nor a_2 - 1 = 3 exists in the array, and a_2 \ne 1; the array [2] is not beautiful: for a_1, neither a_1 - 1 = 1 nor a_1 - 2 = 0 exists in the array, and a_1 \ne 1; the array [2, 1, 3] is beautiful: for a_1, the number a_1 - 1 = 1 exists in the array; for a_2, the condition a_2 = 1 holds; for a_3, the number a_3 - 2 = 1 exists in the array. You are given a positive integer s. Find the minimum possible size of a beautiful array with the sum of elements equal to s.InputThe first line contains one integer t (1 \le t \le 5000) — the number of test cases.Then t lines follow, the i-th line contains one integer s (1 \le s \le 5000) for the i-th test case.OutputPrint t integers, the i-th integer should be the answer for the i-th testcase: the minimum possible size of a beautiful array with the sum of elements equal to s.ExampleInput 4 1 8 7 42 Output 1 3 3 7 NoteConsider the example test: in the first test case, the array [1] meets all conditions; in the second test case, the array [3, 4, 1] meets all conditions; in the third test case, the array [1, 2, 4] meets all conditions; in the fourth test case, the array [1, 4, 6, 8, 10, 2, 11] meets all conditions.
4 1 8 7 42
1 3 3 7
1 second
256 megabytes
['greedy', 'math', '*800']
B. Gregor and the Pawn Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a chessboard of size n by n. The square in the i-th row from top and j-th column from the left is labelled (i,j).Currently, Gregor has some pawns in the n-th row. There are also enemy pawns in the 1-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from (i,j) to (i-1,j)) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from (i,j) to either (i-1,j-1) or (i-1,j+1)) if and only if there is an enemy pawn in that square. The enemy pawn is also removed.Gregor wants to know what is the maximum number of his pawns that can reach row 1?Note that only Gregor takes turns in this game, and the enemy pawns never move. Also, when Gregor's pawn reaches row 1, it is stuck and cannot make any further moves.InputThe first line of the input contains one integer t (1\le t\le 2\cdot 10^4) — the number of test cases. Then t test cases follow.Each test case consists of three lines. The first line contains a single integer n (2\le n\le 2\cdot{10}^{5}) — the size of the chessboard.The second line consists of a string of binary digits of length n, where a 1 in the i-th position corresponds to an enemy pawn in the i-th cell from the left, and 0 corresponds to an empty cell.The third line consists of a string of binary digits of length n, where a 1 in the i-th position corresponds to a Gregor's pawn in the i-th cell from the left, and 0 corresponds to an empty cell.It is guaranteed that the sum of n across all test cases is less than 2\cdot{10}^{5}.OutputFor each test case, print one integer: the maximum number of Gregor's pawns which can reach the 1-st row.ExampleInput 4 3 000 111 4 1111 1111 3 010 010 5 11001 00000 Output 3 4 0 0 NoteIn the first example, Gregor can simply advance all 3 of his pawns forward. Thus, the answer is 3.In the second example, Gregor can guarantee that all 4 of his pawns reach the enemy row, by following the colored paths as demonstrated in the diagram below. Remember, only Gregor takes turns in this "game"! In the third example, Gregor's only pawn is stuck behind the enemy pawn, and cannot reach the end.In the fourth example, Gregor has no pawns, so the answer is clearly 0.
4 3 000 111 4 1111 1111 3 010 010 5 11001 00000
3 4 0 0
1 second
256 megabytes
['dfs and similar', 'dp', 'flows', 'graph matchings', 'graphs', 'greedy', 'implementation', '*800']
A. Gregor and Cryptographytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them.Gregor's favorite prime number is P. Gregor wants to find two bases of P. Formally, Gregor is looking for two integers a and b which satisfy both of the following properties. P \bmod a = P \bmod b, where x \bmod y denotes the remainder when x is divided by y, and 2 \le a < b \le P. Help Gregor find two bases of his favorite prime number!InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000).Each subsequent line contains the integer P (5 \le P \le {10}^9), with P guaranteed to be prime.OutputYour output should consist of t lines. Each line should consist of two integers a and b (2 \le a < b \le P). If there are multiple possible solutions, print any.ExampleInput 2 17 5 Output 3 5 2 4NoteThe first query is P=17. a=3 and b=5 are valid bases in this case, because 17 \bmod 3 = 17 \bmod 5 = 2. There are other pairs which work as well.In the second query, with P=5, the only solution is a=2 and b=4.
2 17 5
3 5 2 4
1 second
256 megabytes
['math', 'number theory', '*800']
E. Gregor and the Two Painterstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo painters, Amin and Benj, are repainting Gregor's living room ceiling! The ceiling can be modeled as an n \times m grid.For each i between 1 and n, inclusive, painter Amin applies a_i layers of paint to the entire i-th row. For each j between 1 and m, inclusive, painter Benj applies b_j layers of paint to the entire j-th column. Therefore, the cell (i,j) ends up with a_i+b_j layers of paint.Gregor considers the cell (i,j) to be badly painted if a_i+b_j \le x. Define a badly painted region to be a maximal connected component of badly painted cells, i. e. a connected component of badly painted cells such that all adjacent to the component cells are not badly painted. Two cells are considered adjacent if they share a side.Gregor is appalled by the state of the finished ceiling, and wants to know the number of badly painted regions.InputThe first line contains three integers n, m and x (1 \le n,m \le 2\cdot 10^5, 1 \le x \le 2\cdot 10^5) — the dimensions of Gregor's ceiling, and the maximum number of paint layers in a badly painted cell.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 2\cdot 10^5), the number of paint layers Amin applies to each row.The third line contains m integers b_1, b_2, \ldots, b_m (1 \le b_j \le 2\cdot 10^5), the number of paint layers Benj applies to each column.OutputPrint a single integer, the number of badly painted regions.ExamplesInput 3 4 11 9 8 5 10 6 7 2 Output 2 Input 3 4 12 9 8 5 10 6 7 2 Output 1 Input 3 3 2 1 2 1 1 2 1 Output 4 Input 5 23 6 1 4 3 5 2 2 3 1 6 1 5 5 6 1 3 2 6 2 3 1 6 1 4 1 6 1 5 5 Output 6 NoteThe diagram below represents the first example. The numbers to the left of each row represent the list a, and the numbers above each column represent the list b. The numbers inside each cell represent the number of paint layers in that cell.The colored cells correspond to badly painted cells. The red and blue cells respectively form 2 badly painted regions.
3 4 11 9 8 5 10 6 7 2
2
4 seconds
256 megabytes
['data structures', 'divide and conquer', 'graphs', 'greedy', 'math', '*3400']
D2. Gregor and the Odd Cows (Hard)time limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference from the easy version is that in this version the coordinates can be both odd and even.There are n fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line.There are an infinite number of cows on the plane, one at every point with integer coordinates.Gregor is a member of the Illuminati, and wants to build a triangular fence, connecting 3 distinct existing fence posts. A cow strictly inside the fence is said to be enclosed. If there are an odd number of enclosed cows and the area of the fence is an integer, the fence is said to be interesting.Find the number of interesting fences.InputThe first line contains the integer n (3 \le n \le 6000), the number of fence posts which Gregor can choose to form the vertices of a fence.Each of the next n line contains two integers x and y (0 \le x,y \le 10^7, where (x,y) is the coordinate of a fence post. All fence posts lie at distinct coordinates. No three fence posts are on the same line.OutputPrint a single integer, the number of interesting fences. Two fences are considered different if they are constructed with a different set of three fence posts.ExamplesInput 3 0 0 2 0 0 4 Output 1 Input 4 1 8 0 6 5 2 5 6 Output 1 Input 10 170 59 129 54 5 98 129 37 58 193 154 58 24 3 13 138 136 144 174 150 Output 29 NoteIn the first example, there is only 1 fence. That fence is interesting since its area is 4 and there is 1 enclosed cow, marked in red. In the second example, there are 4 possible fences. Only one of them is interesting however. That fence has an area of 8 and 5 enclosed cows.
3 0 0 2 0 0 4
1
6 seconds
256 megabytes
['brute force', 'geometry', 'math', 'number theory', '*3300']
D1. Gregor and the Odd Cows (Easy)time limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference from the hard version is that in this version all coordinates are even.There are n fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line.There are an infinite number of cows on the plane, one at every point with integer coordinates.Gregor is a member of the Illuminati, and wants to build a triangular fence, connecting 3 distinct existing fence posts. A cow strictly inside the fence is said to be enclosed. If there are an odd number of enclosed cows and the area of the fence is an integer, the fence is said to be interesting.Find the number of interesting fences.InputThe first line contains the integer n (3 \le n \le 6000), the number of fence posts which Gregor can choose to form the vertices of a fence.Each of the next n line contains two integers x and y (0 \le x,y \le 10^7, x and y are even), where (x,y) is the coordinate of a fence post. All fence posts lie at distinct coordinates. No three fence posts are on the same line.OutputPrint a single integer, the number of interesting fences. Two fences are considered different if they are constructed with a different set of three fence posts.ExamplesInput 3 0 0 2 0 0 4 Output 1 Input 5 0 0 2 16 30 14 4 6 2 10 Output 3 NoteIn the first example, there is only 1 fence. That fence is interesting since its area is 4 and there is 1 enclosed cow, marked in red. In the second example, there are 3 interesting fences. (0,0) — (30,14) — (2,10) (2,16) — (30,14) — (2,10) (30,14) — (4,6) — (2,10)
3 0 0 2 0 0 4
1
6 seconds
256 megabytes
['bitmasks', 'geometry', 'math', 'number theory', '*2300']
C. The Three Little Pigstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThree little pigs from all over the world are meeting for a convention! Every minute, a triple of 3 new pigs arrives on the convention floor. After the n-th minute, the convention ends.The big bad wolf has learned about this convention, and he has an attack plan. At some minute in the convention, he will arrive and eat exactly x pigs. Then he will get away.The wolf wants Gregor to help him figure out the number of possible attack plans that involve eating exactly x pigs for various values of x (1 \le x \le 3n). Two attack plans are considered different, if they occur at different times or if the sets of little pigs to eat are different.Note that all queries are independent, that is, the wolf does not eat the little pigs, he only makes plans!InputThe first line of input contains two integers n and q (1 \le n \le 10^6, 1 \le q \le 2\cdot 10^5), the number of minutes the convention lasts and the number of queries the wolf asks.Each of the next q lines contains a single integer x_i (1 \le x_i \le 3n), the number of pigs the wolf will eat in the i-th query.OutputYou should print q lines, with line i representing the number of attack plans if the wolf wants to eat x_i pigs. Since each query answer can be large, output each answer modulo 10^9+7.ExamplesInput 2 3 1 5 6 Output 9 6 1 Input 5 4 2 4 6 8 Output 225 2001 6014 6939 NoteIn the example test, n=2. Thus, there are 3 pigs at minute 1, and 6 pigs at minute 2. There are three queries: x=1, x=5, and x=6.If the wolf wants to eat 1 pig, he can do so in 3+6=9 possible attack plans, depending on whether he arrives at minute 1 or 2.If the wolf wants to eat 5 pigs, the wolf cannot arrive at minute 1, since there aren't enough pigs at that time. Therefore, the wolf has to arrive at minute 2, and there are 6 possible attack plans.If the wolf wants to eat 6 pigs, his only plan is to arrive at the end of the convention and devour everybody.Remember to output your answers modulo 10^9+7!
2 3 1 5 6
9 6 1
1 second
512 megabytes
['combinatorics', 'dp', 'fft', 'math', '*2500']
B. Integers Have Friendstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBritish mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that "every positive integer was one of his personal friends."It turns out that positive integers can also be friends with each other! You are given an array a of distinct positive integers. Define a subarray a_i, a_{i+1}, \ldots, a_j to be a friend group if and only if there exists an integer m \ge 2 such that a_i \bmod m = a_{i+1} \bmod m = \ldots = a_j \bmod m, where x \bmod y denotes the remainder when x is divided by y.Your friend Gregor wants to know the size of the largest friend group in a.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 2\cdot 10^4). Each test case begins with a line containing the integer n (1 \le n \le 2 \cdot 10^5), the size of the array a.The next line contains n positive integers a_1, a_2, \ldots, a_n (1 \le a_i \le {10}^{18}), representing the contents of the array a. It is guaranteed that all the numbers in a are distinct.It is guaranteed that the sum of n over all test cases is less than 2\cdot 10^5.OutputYour output should consist of t lines. Each line should consist of a single integer, the size of the largest friend group in a.ExampleInput 4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78 Output 3 3 2 6 NoteIn the first test case, the array is [1,5,2,4,6]. The largest friend group is [2,4,6], since all those numbers are congruent to 0 modulo 2, so m=2.In the second test case, the array is [8,2,5,10]. The largest friend group is [8,2,5], since all those numbers are congruent to 2 modulo 3, so m=3.In the third case, the largest friend group is [1000,2000]. There are clearly many possible values of m that work.
4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78
3 3 2 6
2 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'math', 'number theory', 'two pointers', '*1800']
A. Web of Liestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen you play the game of thrones, you win, or you die. There is no middle ground.Cersei Lannister, A Game of Thrones by George R. R. MartinThere are n nobles, numbered from 1 to n. Noble i has a power of i. There are also m "friendships". A friendship between nobles a and b is always mutual.A noble is defined to be vulnerable if both of the following conditions are satisfied: the noble has at least one friend, and all of that noble's friends have a higher power. You will have to process the following three types of queries. Add a friendship between nobles u and v. Remove a friendship between nobles u and v. Calculate the answer to the following process. The process: all vulnerable nobles are simultaneously killed, and all their friendships end. Then, it is possible that new nobles become vulnerable. The process repeats itself until no nobles are vulnerable. It can be proven that the process will end in finite time. After the process is complete, you need to calculate the number of remaining nobles.Note that the results of the process are not carried over between queries, that is, every process starts with all nobles being alive!InputThe first line contains the integers n and m (1 \le n \le 2\cdot 10^5, 0 \le m \le 2\cdot 10^5) — the number of nobles and number of original friendships respectively.The next m lines each contain the integers u and v (1 \le u,v \le n, u \ne v), describing a friendship. No friendship is listed twice.The next line contains the integer q (1 \le q \le 2\cdot {10}^{5}) — the number of queries. The next q lines contain the queries themselves, each query has one of the following three formats. 1 u v (1 \le u,v \le n, u \ne v) — add a friendship between u and v. It is guaranteed that u and v are not friends at this moment. 2 u v (1 \le u,v \le n, u \ne v) — remove a friendship between u and v. It is guaranteed that u and v are friends at this moment. 3 — print the answer to the process described in the statement. OutputFor each type 3 query print one integer to a new line. It is guaranteed that there will be at least one type 3 query.ExamplesInput 4 3 2 1 1 3 3 4 4 3 1 2 3 2 3 1 3 Output 2 1 Input 4 3 2 3 3 4 4 1 1 3 Output 1 NoteConsider the first example. In the first type 3 query, we have the diagram below.In the first round of the process, noble 1 is weaker than all of his friends (2 and 3), and is thus killed. No other noble is vulnerable in round 1. In round 2, noble 3 is weaker than his only friend, noble 4, and is therefore killed. At this point, the process ends, and the answer is 2. In the second type 3 query, the only surviving noble is 4.    The second example consists of only one type 3 query. In the first round, two nobles are killed, and in the second round, one noble is killed. The final answer is 1, since only one noble survives.
4 3 2 1 1 3 3 4 4 3 1 2 3 2 3 1 3
2 1
2 seconds
256 megabytes
['brute force', 'graphs', 'greedy', '*1400']
G. How Many Paths?time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n.A path from u to v is a sequence of edges such that: vertex u is the start of the first edge in the path; vertex v is the end of the last edge in the path; for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u.For each vertex v output one of four values: 0, if there are no paths from 1 to v; 1, if there is only one path from 1 to v; 2, if there is more than one path from 1 to v and the number of paths is finite; -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. Then: the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); the answer for vertex 2 is 0: there are no paths from 1 to 2; the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). InputThe first contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.The first line of the test case contains two integers n and m (1 \le n \le 4 \cdot 10^5, 0 \le m \le 4 \cdot 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 \le a_i, b_i \le n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i \ne j).The sum of n over all test cases does not exceed 4 \cdot 10^5. Similarly, the sum of m over all test cases does not exceed 4 \cdot 10^5.OutputOutput t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2.ExampleInput 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3
1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
4 seconds
512 megabytes
['dfs and similar', 'dp', 'graphs', 'trees', '*2100']
F. Array Stabilization (GCD version)time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array of positive integers a = [a_0, a_1, \dots, a_{n - 1}] (n \ge 2).In one step, the array a is replaced with another array of length n, in which each element is the greatest common divisor (GCD) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).Formally speaking, a new array b = [b_0, b_1, \dots, b_{n - 1}] is being built from array a = [a_0, a_1, \dots, a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) \mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x \mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = \dots = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.InputThe first line contains an integer t (1 \le t \le 10^4). Then t test cases follow.Each test case contains two lines. The first line contains an integer n (2 \le n \le 2 \cdot 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, \dots, a_{n - 1} (1 \le a_i \le 10^6).It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputPrint t numbers — answers for each test case.ExampleInput 5 4 16 24 10 5 4 42 42 42 42 3 4 6 4 5 1 2 3 4 5 6 9 9 27 9 9 63 Output 3 0 2 1 1
5 4 16 24 10 5 4 42 42 42 42 3 4 6 4 5 1 2 3 4 5 6 9 9 27 9 9 63
3 0 2 1 1
4 seconds
512 megabytes
['binary search', 'brute force', 'data structures', 'divide and conquer', 'number theory', 'two pointers', '*1900']
E. Air Conditionerstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOn a strip of land of length n there are k air conditioners: the i-th air conditioner is placed in cell a_i (1 \le a_i \le n). Two or more air conditioners cannot be placed in the same cell (i.e. all a_i are distinct).Each air conditioner is characterized by one parameter: temperature. The i-th air conditioner is set to the temperature t_i. Example of strip of length n=6, where k=2, a=[2,5] and t=[14,16]. For each cell i (1 \le i \le n) find it's temperature, that can be calculated by the formula \min_{1 \le j \le k}(t_j + |a_j - i|),where |a_j - i| denotes absolute value of the difference a_j - i.In other words, the temperature in cell i is equal to the minimum among the temperatures of air conditioners, increased by the distance from it to the cell i.Let's look at an example. Consider that n=6, k=2, the first air conditioner is placed in cell a_1=2 and is set to the temperature t_1=14 and the second air conditioner is placed in cell a_2=5 and is set to the temperature t_2=16. In that case temperatures in cells are: temperature in cell 1 is: \min(14 + |2 - 1|, 16 + |5 - 1|)=\min(14 + 1, 16 + 4)=\min(15, 20)=15; temperature in cell 2 is: \min(14 + |2 - 2|, 16 + |5 - 2|)=\min(14 + 0, 16 + 3)=\min(14, 19)=14; temperature in cell 3 is: \min(14 + |2 - 3|, 16 + |5 - 3|)=\min(14 + 1, 16 + 2)=\min(15, 18)=15; temperature in cell 4 is: \min(14 + |2 - 4|, 16 + |5 - 4|)=\min(14 + 2, 16 + 1)=\min(16, 17)=16; temperature in cell 5 is: \min(14 + |2 - 5|, 16 + |5 - 5|)=\min(14 + 3, 16 + 0)=\min(17, 16)=16; temperature in cell 6 is: \min(14 + |2 - 6|, 16 + |5 - 6|)=\min(14 + 4, 16 + 1)=\min(18, 17)=17. For each cell from 1 to n find the temperature in it.InputThe first line contains one integer q (1 \le q \le 10^4) — the number of test cases in the input. Then test cases follow. Before each test case, there is an empty line.Each test case contains three lines. The first line contains two integers n (1 \le n \le 3 \cdot 10^5) and k (1 \le k \le n) — the length of the strip of land and the number of air conditioners respectively.The second line contains k integers a_1, a_2, \ldots, a_k (1 \le a_i \le n) — positions of air conditioners on the strip of land.The third line contains k integers t_1, t_2, \ldots, t_k (1 \le t_i \le 10^9) — temperatures of air conditioners.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case output n integers separated by space: temperatures of air in cells.ExampleInput 5 6 2 2 5 14 16 10 1 7 30 5 5 3 1 4 2 5 3 1 4 2 5 7 1 1 1000000000 6 3 6 1 3 5 5 5 Output 15 14 15 16 16 17 36 35 34 33 32 31 30 31 32 33 1 2 3 4 5 1000000000 1000000001 1000000002 1000000003 1000000004 1000000005 1000000006 5 6 5 6 6 5
5 6 2 2 5 14 16 10 1 7 30 5 5 3 1 4 2 5 3 1 4 2 5 7 1 1 1000000000 6 3 6 1 3 5 5 5
15 14 15 16 16 17 36 35 34 33 32 31 30 31 32 33 1 2 3 4 5 1000000000 1000000001 1000000002 1000000003 1000000004 1000000005 1000000006 5 6 5 6 6 5
2 seconds
512 megabytes
['data structures', 'dp', 'implementation', 'shortest paths', 'sortings', 'two pointers', '*1500']
D. Co-growing Sequencetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA sequence of non-negative integers a_1, a_2, \dots, a_n is called growing if for all i from 1 to n - 1 all ones (of binary representation) in a_i are in the places of ones (of binary representation) in a_{i + 1} (in other words, a_i \:\&\: a_{i + 1} = a_i, where \& denotes bitwise AND). If n = 1 then the sequence is considered growing as well.For example, the following four sequences are growing: [2, 3, 15, 175] — in binary it's [10_2, 11_2, 1111_2, 10101111_2]; [5] — in binary it's [101_2]; [1, 3, 7, 15] — in binary it's [1_2, 11_2, 111_2, 1111_2]; [0, 0, 0] — in binary it's [0_2, 0_2, 0_2]. The following three sequences are non-growing: [3, 4, 5] — in binary it's [11_2, 100_2, 101_2]; [5, 4, 3] — in binary it's [101_2, 100_2, 011_2]; [1, 2, 4, 8] — in binary it's [0001_2, 0010_2, 0100_2, 1000_2]. Consider two sequences of non-negative integers x_1, x_2, \dots, x_n and y_1, y_2, \dots, y_n. Let's call this pair of sequences co-growing if the sequence x_1 \oplus y_1, x_2 \oplus y_2, \dots, x_n \oplus y_n is growing where \oplus denotes bitwise XOR.You are given a sequence of integers x_1, x_2, \dots, x_n. Find the lexicographically minimal sequence y_1, y_2, \dots, y_n such that sequences x_i and y_i are co-growing.The sequence a_1, a_2, \dots, a_n is lexicographically smaller than the sequence b_1, b_2, \dots, b_n if there exists 1 \le k \le n such that a_i = b_i for any 1 \le i < k but a_k < b_k.InputThe first line contains an integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains an integer n (1 \le n \le 2 \cdot 10^5) — length of the sequence x_i.The second line contains n integers x_1, x_2, \dots, x_n (0 \le x_i < 2^{30}) — elements of the sequence x_i.It is guaranteed that the sum of n overall all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print n integers y_1, y_2, \dots, y_n (0 \le y_i < 2^{30}) — lexicographically minimal sequence such that such that it's co-growing with given sequence x_i.ExampleInput 5 4 1 3 7 15 4 1 2 4 8 5 1 2 3 4 5 4 11 13 15 1 1 0 Output 0 0 0 0 0 1 3 7 0 1 0 3 2 0 2 0 14 0
5 4 1 3 7 15 4 1 2 4 8 5 1 2 3 4 5 4 11 13 15 1 1 0
0 0 0 0 0 1 3 7 0 1 0 3 2 0 2 0 14 0
2 seconds
512 megabytes
['bitmasks', 'constructive algorithms', 'greedy', '*1300']
C. Pair Programmingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, \dots, a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, \dots, b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.Restore their common sequence of actions of length n + m such that all actions would be correct — there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, \dots, a_n] and Polycarp's — subsequence [b_1, b_2, \dots, b_m]. They can replace each other at the computer any number of times.Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.InputThe first line contains an integer t (1 \le t \le 1000). Then t test cases follow. Before each test case, there is an empty line.Each test case contains three lines. The first line contains three integers k, n, m (0 \le k \le 100, 1 \le n, m \le 100) — the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 300).The third line contains m integers b_1, b_2, \dots, b_m (0 \le b_j \le 300).OutputFor each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.ExampleInput 5 3 2 2 2 0 0 5 4 3 2 2 0 5 0 6 0 2 2 1 0 2 3 5 4 4 6 0 8 0 0 7 0 9 5 4 1 8 7 8 0 0 Output 2 0 0 5 0 2 0 6 5 -1 0 6 0 7 0 8 0 9 -1
5 3 2 2 2 0 0 5 4 3 2 2 0 5 0 6 0 2 2 1 0 2 3 5 4 4 6 0 8 0 0 7 0 9 5 4 1 8 7 8 0 0
2 0 0 5 0 2 0 6 5 -1 0 6 0 7 0 8 0 9 -1
2 seconds
512 megabytes
['greedy', 'two pointers', '*1100']
B. Alphabetical Stringstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA string s of length n (1 \le n \le 26) is called alphabetical if it can be obtained using the following algorithm: first, write an empty string to s (i.e. perform the assignment s := ""); then perform the next step n times; at the i-th step take i-th lowercase letter of the Latin alphabet and write it either to the left of the string s or to the right of the string s (i.e. perform the assignment s := c+s or s := s+c, where c is the i-th letter of the Latin alphabet). In other words, iterate over the n first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string s or append a letter to the right of the string s. Strings that can be obtained in that way are alphabetical.For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba".From the given string, determine if it is alphabetical.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case is written on a separate line that contains one string s. String s consists of lowercase letters of the Latin alphabet and has a length between 1 and 26, inclusive.OutputOutput t lines, each of them must contain the answer to the corresponding test case. Output YES if the given string s is alphabetical and NO otherwise.You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer).ExampleInput 11 a ba ab bac ihfcbadeg z aa ca acb xyz ddcba Output YES YES YES YES YES NO NO NO NO NO NO NoteThe example contains test cases from the main part of the condition.
11 a ba ab bac ihfcbadeg z aa ca acb xyz ddcba
YES YES YES YES YES NO NO NO NO NO NO
2 seconds
512 megabytes
['greedy', 'implementation', 'strings', '*800']
A. Shortest Path with Obstacletime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if: in one move you can go to any of the four adjacent cells sharing a side; visiting the cell F is forbidden (it is an obstacle). 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. Before each test case, there is an empty line.Each test case contains three lines. The first one contains two integers x_A, y_A (1 \le x_A, y_A \le 1000) — coordinates of the start cell A. The second one contains two integers x_B, y_B (1 \le x_B, y_B \le 1000) — coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 \le x_F, y_F \le 1000) — coordinates of the forbidden cell F. All cells are distinct.Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).OutputOutput t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.ExampleInput 7 1 1 3 3 2 2 2 5 2 1 2 3 1000 42 1000 1 1000 1000 1 10 3 10 2 10 3 8 7 8 3 7 2 1 4 1 1 1 1 344 1 10 1 1 Output 4 6 41 4 4 2 334 Note An example of a possible shortest path for the first test case. An example of a possible shortest path for the second test case.
7 1 1 3 3 2 2 2 5 2 1 2 3 1000 42 1000 1 1000 1000 1 10 3 10 2 10 3 8 7 8 3 7 2 1 4 1 1 1 1 344 1 10 1 1
4 6 41 4 4 2 334
2 seconds
512 megabytes
['implementation', 'math', '*800']
B. AquaMoon and Stolen Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAquaMoon had n strings of length m each. n is an odd number.When AquaMoon was gone, Cirno tried to pair these n strings together. After making \frac{n-1}{2} pairs, she found out that there was exactly one string without the pair!In her rage, she disrupted each pair of strings. For each pair, she selected some positions (at least 1 and at most m) and swapped the letters in the two strings of this pair at the selected positions.For example, if m = 6 and two strings "abcdef" and "xyzklm" are in one pair and Cirno selected positions 2, 3 and 6 she will swap 'b' with 'y', 'c' with 'z' and 'f' with 'm'. The resulting strings will be "ayzdem" and "xbcklf".Cirno then stole away the string without pair and shuffled all remaining strings in arbitrary order.AquaMoon found the remaining n-1 strings in complete disarray. Also, she remembers the initial n strings. She wants to know which string was stolen, but she is not good at programming. Can you help her?InputThis problem is made as interactive. It means, that your solution will read the input, given by the interactor. But the interactor will give you the full input at the beginning and after that, you should print the answer. So you should solve the problem, like as you solve the usual, non-interactive problem because you won't have any interaction process. The only thing you should not forget is to flush the output buffer, after printing the answer. Otherwise, you can get an "Idleness limit exceeded" verdict. Refer to the interactive problems guide for the detailed information about flushing the output buffer.The input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains two integers n, m (1 \leq n \leq 10^5, 1 \leq m \leq 10^5) — the number of strings and the length of each string, respectively.The next n lines each contain a string with length m, describing the original n strings. All string consists of lowercase Latin letters.The next n-1 lines each contain a string with length m, describing the strings after Cirno exchanged and reordered them.It is guaranteed that n is odd and that the sum of n \cdot m over all test cases does not exceed 10^5.Hack format:The first line should contain a single integer t. After that t test cases should follow in the following format:The first line should contain two integers n and m.The following n lines should contain n strings of length m, describing the original strings.The following \frac{n-1}{2} lines should describe the pairs. They should contain, in the following order: the index of the first string i (1 \leq i \leq n), the index of the second string j (1 \leq j \leq n, i \neq j), the number of exchanged positions k (1 \leq k \leq m), and the list of k positions that are exchanged (k distinct indices from 1 to m in any order).The final line should contain a permutation of integers from 1 to n, describing the way the strings should be reordered. The strings will be placed in the order indices placed in this permutation, the stolen string index will be ignored.OutputFor each test case print a single line with the stolen string.ExampleInput 3 3 5 aaaaa bbbbb ccccc aaaaa bbbbb 3 4 aaaa bbbb cccc aabb bbaa 5 6 abcdef uuuuuu kekeke ekekek xyzklm xbcklf eueueu ayzdem ukukuk Output ccccc cccc kekeke NoteIn the first test case, "aaaaa" and "bbbbb" exchanged all positions, and "ccccc" is the stolen string.In the second test case, "aaaa" and "bbbb" exchanged two first positions, and "cccc" is the stolen string.This is the first test in the hack format: 33 5aaaaabbbbbccccc1 2 5 1 2 3 4 52 1 33 4aaaabbbbcccc1 2 2 1 22 1 35 6abcdefuuuuuukekekeekekekxyzklm1 5 3 2 3 62 4 3 2 4 65 4 1 2 3
3 3 5 aaaaa bbbbb ccccc aaaaa bbbbb 3 4 aaaa bbbb cccc aabb bbaa 5 6 abcdef uuuuuu kekeke ekekek xyzklm xbcklf eueueu ayzdem ukukuk
ccccc cccc kekeke
1 second
256 megabytes
['interactive', 'math', '*1200']
A. AquaMoon and Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): She chooses two indices i and j (1 \le i, j \le n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 \leq i \leq n.Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal.Please note, that you don't have to minimize the number of operations.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 100).The second line of each test case contains n integers a_1, a_2, \dots, a_n (0 \leq a_i \leq 100). The sum of all a_i does not exceed 100.The third line of each test case contains n integers b_1, b_2, \dots, b_n (0 \leq b_i \leq 100). The sum of all b_i does not exceed 100.OutputFor each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations.Otherwise, print an integer m (0 \leq m \leq 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation.It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m \leq 100.If there are multiple possible solutions, you can print any.ExampleInput 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 NoteIn the first example, we do the following operations: i = 2, j = 1: [1, 2, 3, 4] \rightarrow [2, 1, 3, 4]; i = 3, j = 1: [2, 1, 3, 4] \rightarrow [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal.
4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4
2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5
1 second
256 megabytes
['brute force', 'greedy', '*800']
F. AquaMoon and Potatoestime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAquaMoon has three integer arrays a, b, c of length n, where 1 \leq a_i, b_i, c_i \leq n for all i.In order to accelerate her potato farming, she organizes her farm in a manner based on these three arrays. She is now going to complete m operations to count how many potatoes she can get. Each operation will have one of the two types: AquaMoon reorganizes their farm and makes the k-th element of the array a equal to x. In other words, perform the assignment a_k := x. Given a positive integer r, AquaMoon receives a potato for each triplet (i,j,k), such that 1\le i<j<k\le r, and b_{a_i}=a_j=c_{a_k}. Count the number of such triplets. As AquaMoon is busy finding the library, help her complete all of their operations.InputThe first line contains two integers n, m (1\le n\le 2\cdot10^5, 1\le m\le 5\cdot10^4).The second line contains n integers a_1, a_2, \dots,a_n (1\le a_i\le n).The third line contains n integers b_1, b_2, \dots,b_n (1\le b_i\le n).The fourth line contains n integers c_1, c_2, \dots,c_n (1\le c_i\le n).The next m lines describe operations, the i-th line describes the i-th operation in one of these two formats: "1\ k\ x" (1\le k,x\le n), representing an operation of the first type. "2\ r" (1\le r\le n), representing an operation of the second type. It is guaranteed that there is at least one operation of the second type.OutputFor each operation of the second type print the answer.ExampleInput 5 4 1 2 3 4 5 2 3 4 5 1 5 1 2 3 4 2 5 1 2 3 2 4 2 5 Output 3 0 2 NoteFor the first operation, the triplets are: i=1, j=2, k=3 i=2, j=3, k=4 i=3, j=4, k=5 There is no satisfying triplet for the third operation.For the fourth operation, the triplets are: i=2, j=4, k=5 i=3, j=4, k=5
5 4 1 2 3 4 5 2 3 4 5 1 5 1 2 3 4 2 5 1 2 3 2 4 2 5
3 0 2
7 seconds
512 megabytes
['brute force', 'data structures', 'dp', '*3500']
E2. AquaMoon and Time Stop (hard version)time limit per test7 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputNote that the differences between easy and hard versions are the constraints on n and the time limit. You can make hacks only if both versions are solved.AquaMoon knew through foresight that some ghosts wanted to curse tourists on a pedestrian street. But unfortunately, this time, these ghosts were hiding in a barrier, and she couldn't enter this barrier in a short time and destroy them. Therefore, all that can be done is to save any unfortunate person on the street from the ghosts.The pedestrian street can be represented as a one-dimensional coordinate system. There is one person hanging out on the pedestrian street. At the time 0 he is at coordinate x, moving with a speed of 1 unit per second. In particular, at time i the person will be at coordinate x+i.The ghosts are going to cast n curses on the street. The i-th curse will last from time tl_i-1+10^{-18} to time tr_i+1-10^{-18} (exclusively) and will kill people with coordinates from l_i-1+10^{-18} to r_i+1-10^{-18} (exclusively). Formally that means, that the person, whose coordinate is between (l_i-1+10^{-18},r_i+1-10^{-18}) in the time range (tl_i-1+10^{-18},tr_i+1-10^{-18}) will die.To save the person on the street, AquaMoon can stop time at any moment t, and then move the person from his current coordinate x to any coordinate y (t, x and y are not necessarily integers). The movement costs AquaMoon |x-y| energy. The movement is continuous, so if there exists some cursed area between points x and y at time t, the person will die too.AquaMoon wants to know what is the minimum amount of energy she needs to spend in order to save the person on the street from all n curses. But she is not good at programming. As her friend, can you help her?InputThe first line contains a single integer n (1\le n\le 2 \cdot 10^5) — the number of curses.The next line contains a single integer x (1\le x\le 10^6) — the initial coordinate of the person.The following n lines contain four integers tl_i, tr_i, l_i, r_i each (1\le tl_i\le tr_i\le 10^6, 1\le l_i\le r_i\le 10^6).OutputPrint a single integer — the minimum energy which AquaMoon needs to spent, rounded up to the nearest integer (in case there are two nearest integers you should round the answer to the highest of them).ExamplesInput 2 1 1 2 1 2 2 3 2 3 Output 2Input 3 4 1 4 1 2 1 4 4 15 6 7 1 4 Output 8Input 4 3 1 5 1 1 4 10 1 4 1 2 3 13 1 10 7 19 Output 14Input 7 5 78 96 76 91 6 16 18 37 53 63 40 56 83 88 21 38 72 75 17 24 63 63 53 60 34 46 60 60 Output 20
2 1 1 2 1 2 2 3 2 3
2
7 seconds
1024 megabytes
['data structures', 'dp', '*3500']
E1. AquaMoon and Time Stop (easy version)time limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputNote that the differences between easy and hard versions are the constraints on n and the time limit. You can make hacks only if both versions are solved.AquaMoon knew through foresight that some ghosts wanted to curse tourists on a pedestrian street. But unfortunately, this time, these ghosts were hiding in a barrier, and she couldn't enter this barrier in a short time and destroy them. Therefore, all that can be done is to save any unfortunate person on the street from the ghosts.The pedestrian street can be represented as a one-dimensional coordinate system. There is one person hanging out on the pedestrian street. At the time 0 he is at coordinate x, moving with a speed of 1 unit per second. In particular, at time i the person will be at coordinate x+i.The ghosts are going to cast n curses on the street. The i-th curse will last from time tl_i-1+10^{-18} to time tr_i+1-10^{-18} (exclusively) and will kill people with coordinates from l_i-1+10^{-18} to r_i+1-10^{-18} (exclusively). Formally that means, that the person, whose coordinate is between (l_i-1+10^{-18},r_i+1-10^{-18}) in the time range (tl_i-1+10^{-18},tr_i+1-10^{-18}) will die.To save the person on the street, AquaMoon can stop time at any moment t, and then move the person from his current coordinate x to any coordinate y (t, x and y are not necessarily integers). The movement costs AquaMoon |x-y| energy. The movement is continuous, so if there exists some cursed area between points x and y at time t, the person will die too.AquaMoon wants to know what is the minimum amount of energy she needs to spend in order to save the person on the street from all n curses. But she is not good at programming. As her friend, can you help her?InputThe first line contains a single integer n (1\le n\le 2000) — the number of curses.The next line contains a single integer x (1\le x\le 10^6) — the initial coordinate of the person.The following n lines contain four integers tl_i, tr_i, l_i, r_i each (1\le tl_i\le tr_i\le 10^6, 1\le l_i\le r_i\le 10^6).OutputPrint a single integer — the minimum energy which AquaMoon needs to spent, rounded up to the nearest integer (in case there are two nearest integers you should round the answer to the highest of them).ExamplesInput 2 1 1 2 1 2 2 3 2 3 Output 2Input 3 4 1 4 1 2 1 4 4 15 6 7 1 4 Output 8Input 4 3 1 5 1 1 4 10 1 4 1 2 3 13 1 10 7 19 Output 14Input 7 5 78 96 76 91 6 16 18 37 53 63 40 56 83 88 21 38 72 75 17 24 63 63 53 60 34 46 60 60 Output 20
2 1 1 2 1 2 2 3 2 3
2
3 seconds
1024 megabytes
['data structures', 'dp', '*3500']
D. AquaMoon and Wrong Coordinatetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCirno gives AquaMoon a problem. There are m people numbered from 0 to m - 1. They are standing on a coordinate axis in points with positive integer coordinates. They are facing right (i.e. in the direction of the coordinate increase). At this moment everyone will start running with the constant speed in the direction of coordinate increasing. The initial coordinate of the i-th person on the line is x_i, and the speed of the i-th person is v_i. So the coordinate of the i-th person at the moment t will be x_i + t \cdot v_i.Cirno captured the coordinates of m people in k consecutive integer moments from 0 to k - 1. In every moment, the coordinates of m people were recorded in arbitrary order.To make the problem more funny, Cirno modified one coordinate at the moment y (0 < y < k-1) to a different integer.AquaMoon wants to find the moment y and the original coordinate p before the modification. Actually, she is not a programmer at all. So she wasn't able to solve it. Can you help her?InputThis problem is made as interactive. It means, that your solution will read the input, given by the interactor. But the interactor will give you the full input at the beginning and after that, you should print the answer. So you should solve the problem, like as you solve the usual, non-interactive problem because you won't have any interaction process. The only thing you should not forget is to flush the output buffer, after printing the answer. Otherwise, you can get an "Idleness limit exceeded" verdict. Refer to the interactive problems guide for the detailed information about flushing the output buffer.The first line contains two integers m and k (5 \leq m \leq 1000, 7 \leq k \leq 1000) — the number of people and the number of recorded moments. The next k lines contain captured positions. i-th of these lines contains m integers between 1 and 10^6 (inclusive), representing positions captured by Cirno at the moment i-1.The input is guaranteed to be valid (i.e. only one integer was modified to a different value according to the problem statement). Also, it is guaranteed, that 1 \le v_i \le 1000 for all 1 \leq i \leq m.Hack format:The first line should contain two integers m and k (5 \leq m \leq 1000, 7 \leq k \leq 1000) — the number of people and the number of moments. In the second line, there should be m integers x_0, x_1, \dots,x_{m - 1} (1 \le x_i \le 10^6), where x_i is the initial coordinate of the i-th person.In the third line, there should be m integers v_0, v_1, \dots,v_{m - 1} (1 \le v_i \le 1000), where v_i is the speed of the i-th person. It should be true that x_i + (k-1) v_i \leq 10^6 for each 0 \leq i < m.In the next k lines, each line should contain m integers. i-th line should contain m distinct integers p_0, p_1, \ldots, p_{m-1} (0 \leq p_j < m). The meaning of these numbers: j-th integer in the input in the i-th moment is the coordinate of the p_{j}-th person.In the last line, there should be three integers y, i, c. Cirno modified the coordinate of the i-th person at the moment y to c (1 \leq y \leq k-2, 0 \leq i \leq m - 1, 1 \leq c \leq 10^6, c \neq x_i + y \cdot v_i).OutputPrint a single line with two integers y, p — the moment that contains the modified coordinate and the original coordinate.ExampleInput 5 7 6 9 9 6 9 10 7 10 8 10 11 11 11 10 8 12 12 12 12 9 14 13 12 10 13 11 14 16 14 14 12 15 18 15 15 Output 4 13 NoteIn the first test the initial coordinates of people are 9, 6, 6, 9, 9 and their speeds are 1, 2, 1, 1, 1. So, it's easy to see, that at the moment 4 one coordinate was modified from 13 to 12.This is the first test in the hack format:5 79 6 6 9 91 2 1 1 12 3 4 1 00 2 3 1 44 3 0 1 21 3 4 0 21 4 0 2 32 4 1 3 02 4 1 3 04 0 12
5 7 6 9 9 6 9 10 7 10 8 10 11 11 11 10 8 12 12 12 12 9 14 13 12 10 13 11 14 16 14 14 12 15 18 15 15
4 13
2 seconds
256 megabytes
['constructive algorithms', 'interactive', 'math', '*3000']
C. AquaMoon and Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCirno has prepared n arrays of length n each. Each array is a permutation of n integers from 1 to n. These arrays are special: for all 1 \leq i \leq n, if we take the i-th element of each array and form another array of length n with these elements, the resultant array is also a permutation of n integers from 1 to n. In the other words, if you put these n arrays under each other to form a matrix with n rows and n columns, this matrix is a Latin square.Afterwards, Cirno added additional n arrays, each array is a permutation of n integers from 1 to n. For all 1 \leq i \leq n, there exists at least one position 1 \leq k \leq n, such that for the i-th array and the (n + i)-th array, the k-th element of both arrays is the same. Notice that the arrays indexed from n + 1 to 2n don't have to form a Latin square. Also, Cirno made sure that for all 2n arrays, no two arrays are completely equal, i. e. for all pair of indices 1 \leq i < j \leq 2n, there exists at least one position 1 \leq k \leq n, such that the k-th elements of the i-th and j-th array are different.Finally, Cirno arbitrarily changed the order of 2n arrays.AquaMoon calls a subset of all 2n arrays of size n good if these arrays from a Latin square.AquaMoon wants to know how many good subsets exist. Because this number may be particularly large, find it modulo 998\,244\,353. Also, she wants to find any good subset. Can you help her?InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains a single integer n (5 \leq n \leq 500).Then 2n lines followed. The i-th of these lines contains n integers, representing the i-th array.It is guaranteed, that the sum of n over all test cases does not exceed 500.OutputFor each test case print two lines.In the first line, print the number of good subsets by modulo 998\,244\,353.In the second line, print n indices from 1 to 2n — indices of the n arrays that form a good subset (you can print them in any order). If there are several possible answers — print any of them.ExampleInput 3 7 1 2 3 4 5 6 7 2 3 4 5 6 7 1 3 4 5 6 7 1 2 4 5 6 7 1 2 3 5 6 7 1 2 3 4 6 7 1 2 3 4 5 7 1 2 3 4 5 6 1 2 3 4 5 7 6 1 3 4 5 6 7 2 1 4 5 6 7 3 2 1 5 6 7 4 2 3 1 6 7 5 2 3 4 1 7 6 2 3 4 5 1 7 2 3 4 5 6 5 4 5 1 2 3 3 5 2 4 1 1 2 3 4 5 5 2 4 1 3 3 4 5 1 2 2 3 4 5 1 1 3 5 2 4 4 1 3 5 2 2 4 1 3 5 5 1 2 3 4 6 2 3 4 5 6 1 3 1 2 6 4 5 6 1 2 3 4 5 5 6 1 3 2 4 4 3 6 5 2 1 5 6 1 2 3 4 4 5 6 1 2 3 3 4 5 6 1 2 1 2 3 4 5 6 2 5 4 1 6 3 3 2 5 4 1 6 1 4 3 6 5 2 Output 1 1 2 3 4 5 6 7 2 1 3 5 6 10 4 1 3 6 7 8 9 NoteIn the first test case, the number of good subsets is 1. The only such subset is the set of arrays with indices 1, 2, 3, 4, 5, 6, 7.In the second test case, the number of good subsets is 2. They are 1, 3, 5, 6, 10 or 2, 4, 7, 8, 9.
3 7 1 2 3 4 5 6 7 2 3 4 5 6 7 1 3 4 5 6 7 1 2 4 5 6 7 1 2 3 5 6 7 1 2 3 4 6 7 1 2 3 4 5 7 1 2 3 4 5 6 1 2 3 4 5 7 6 1 3 4 5 6 7 2 1 4 5 6 7 3 2 1 5 6 7 4 2 3 1 6 7 5 2 3 4 1 7 6 2 3 4 5 1 7 2 3 4 5 6 5 4 5 1 2 3 3 5 2 4 1 1 2 3 4 5 5 2 4 1 3 3 4 5 1 2 2 3 4 5 1 1 3 5 2 4 4 1 3 5 2 2 4 1 3 5 5 1 2 3 4 6 2 3 4 5 6 1 3 1 2 6 4 5 6 1 2 3 4 5 5 6 1 3 2 4 4 3 6 5 2 1 5 6 1 2 3 4 4 5 6 1 2 3 3 4 5 6 1 2 1 2 3 4 5 6 2 5 4 1 6 3 3 2 5 4 1 6 1 4 3 6 5 2
1 1 2 3 4 5 6 7 2 1 3 5 6 10 4 1 3 6 7 8 9
2 seconds
256 megabytes
['2-sat', 'brute force', 'combinatorics', 'constructive algorithms', 'graph matchings', 'graphs', '*2800']
B. AquaMoon and Chesstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCirno gave AquaMoon a chessboard of size 1 \times n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied.In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): Move pawn from it to the (i+2)-th cell, if i+2 \leq n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. Move pawn from it to the (i-2)-th cell, if i-2 \geq 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998\,244\,353.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10\,000) — the number of test cases.The first line contains a single integer n (1 \leq n \leq 10^5) — the size of the chessboard.The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998\,244\,353.ExampleInput 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 NoteIn the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010
3 6 1 1287 1287 715
1 second
256 megabytes
['combinatorics', 'math', '*1900']
A. AquaMoon and Strange Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 50) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 10^5) — the number of Aquamoon's friends.The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^5) — the numbers, written on the T-shirts.It is guaranteed that the sum of n for all test cases does not exceed 10^5.OutputFor each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).You can print each letter in any case (upper or lower).ExampleInput 3 4 4 3 2 5 4 3 3 2 2 5 1 2 3 5 4 Output YES YES NO NoteThe possible list of operations in the first test case: Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
3 4 4 3 2 5 4 3 3 2 2 5 1 2 3 5 4
YES YES NO
1 second
256 megabytes
['sortings', '*1500']
E. The Final Pursuittime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFinally, you have defeated Razor and now, you are the Most Wanted street racer. Sergeant Cross has sent the full police force after you in a deadly pursuit. Fortunately, you have found a hiding spot but you fear that Cross and his force will eventually find you. To increase your chances of survival, you want to tune and repaint your BMW M3 GTR.The car can be imagined as a permuted n-dimensional hypercube. A simple n-dimensional hypercube is an undirected unweighted graph built recursively as follows: Take two simple (n-1)-dimensional hypercubes one having vertices numbered from 0 to 2^{n-1}-1 and the other having vertices numbered from 2^{n-1} to 2^{n}-1. A simple 0-dimensional Hypercube is just a single vertex. Add an edge between the vertices i and i+2^{n-1} for each 0\leq i < 2^{n-1}. A permuted n-dimensional hypercube is formed by permuting the vertex numbers of a simple n-dimensional hypercube in any arbitrary manner.Examples of a simple and permuted 3-dimensional hypercubes are given below: Note that a permuted n-dimensional hypercube has the following properties: There are exactly 2^n vertices. There are exactly n\cdot 2^{n-1} edges. Each vertex is connected to exactly n other vertices. There are no self-loops or duplicate edges. Let's denote the permutation used to generate the permuted n-dimensional hypercube, representing your car, from a simple n-dimensional hypercube by P. Before messing up the functionalities of the car, you want to find this permutation so that you can restore the car if anything goes wrong. But the job isn't done yet.You have n different colours numbered from 0 to n-1. You want to colour the vertices of this permuted n-dimensional hypercube in such a way that for each and every vertex u satisfying 0\leq u < 2^n and for each and every colour c satisfying 0\leq c < n, there is at least one vertex v adjacent to u having a colour c. In other words, from each and every vertex, it must be possible to reach a vertex of any colour by just moving to an adjacent vertex. Given the permuted n-dimensional hypercube, find any valid permutation P and colouring.InputThe first line of input contains a single integer t (1\leq t\leq 4096) — the number of test cases.For each test case, the first line contains a single integer n (1\leq n\leq 16).Each of the next n\cdot 2^{n-1} lines contain two integers u and v (0\leq u, v < 2^n) denoting that there is an edge between the vertices numbered u and v.It is guaranteed that the graph described in the input is a permuted n-dimensional hypercube.Additionally, it is guaranteed that the sum of 2^n over all test cases does not exceed 2^{16}=65\,536.OutputFor each test case, print two lines.In the first line, output any permutation P of length 2^n that can be used to transform a simple n-dimensional hypercube to the permuted n-dimensional hypercube given in the input. Two permuted hypercubes are considered the same if they have the same set of edges. If there are multiple answers, output any of them.In the second line, print the colouring. If there is no way to colour the vertices satisfying the conditions, output -1. Otherwise, output a single line containing 2^n space separated integers. The i-th integer must be the colour of the vertex numbered (i-1) in the permuted n-dimensional hypercube. If there are multiple answers, output any of them.ExampleInput 3 1 0 1 2 0 1 1 2 2 3 3 0 3 0 1 0 5 0 7 1 2 1 4 2 5 2 6 3 5 3 6 3 7 4 6 4 7 Output 0 1 0 0 0 1 3 2 0 0 1 1 5 3 0 7 2 6 1 4 -1 NoteThe colouring and the permuted hypercube for the first test case is shown below: The colouring and the permuted hypercube for the second test case is shown below: The permuted hypercube for the third test case is given in the problem statement. However, it can be shown that there exists no way to colour that cube satifying all the conditions. Note that some other permutations like [0, 5, 7, 3, 1, 2, 4, 6] and [0, 1, 5, 2, 7, 4, 3, 6] will also give the same permuted hypercube.
3 1 0 1 2 0 1 1 2 2 3 3 0 3 0 1 0 5 0 7 1 2 1 4 2 5 2 6 3 5 3 6 3 7 4 6 4 7
0 1 0 0 0 1 3 2 0 0 1 1 5 3 0 7 2 6 1 4 -1
3 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'divide and conquer', 'graphs', 'greedy', 'math', '*2700']
D2. RPD and Rap Sheet (Hard Version)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is that here 2\leq k\leq 100. You can make hacks only if both the versions of the problem are solved.This is an interactive problem!Every decimal number has a base k equivalent. The individual digits of a base k number are called k-its. Let's define the k-itwise XOR of two k-its a and b as (a + b)\bmod k.The k-itwise XOR of two base k numbers is equal to the new number formed by taking the k-itwise XOR of their corresponding k-its. The k-itwise XOR of two decimal numbers a and b is denoted by a\oplus_{k} b and is equal to the decimal representation of the k-itwise XOR of the base k representations of a and b. All further numbers used in the statement below are in decimal unless specified.You have hacked the criminal database of Rockport Police Department (RPD), also known as the Rap Sheet. But in order to access it, you require a password. You don't know it, but you are quite sure that it lies between 0 and n-1 inclusive. So, you have decided to guess it. Luckily, you can try at most n times without being blocked by the system. But the system is adaptive. Each time you make an incorrect guess, it changes the password. Specifically, if the password before the guess was x, and you guess a different number y, then the system changes the password to a number z such that x\oplus_{k} z=y. Guess the password and break into the system.InputThe first line of input contains a single integer t (1\leq t\leq 10\,000) denoting the number of test cases. t test cases follow.The first line of each test case contains two integers n (1\leq n\leq 2\cdot 10^5) and k (2\leq k\leq 100).It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.InteractionFor each test case, first read two integers n and k. Then you may ask up to n queries.For each query, print a single integer y (0\leq y\leq 2\cdot 10^7). Let the current password be x. After that, read an integer r.If x=y, you will read r=1 and the test case is solved. You must then continue solving the remaining test cases.Else, you will read r=0. At this moment the password is changed to a number z such that x\oplus_{k} z=y.After printing a query, do not forget to output the end of line and flush the output. Otherwise, you will get the 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. If you ask an invalid query or exceed n queries, you will read r=-1 and you will receive the Wrong Answer verdict. Make sure to exit immediately to avoid unexpected verdicts.Note that the interactor is adaptive. That is, the original password is not fixed in the beginning and may depend on your queries. But it is guaranteed that at any moment there is at least one initial password such that all the answers to the queries are consistent.Hacks:To use hacks, use the following format of tests:The first line should contain a single integer t (1\leq t\leq 10\,000) — the number of test cases.The first and only line of each test case should contain two integers n (1\leq n\leq 2\cdot 10^5) and k (2\leq k\leq 100) denoting the number of queries and the base respectively. The optimal original password is automatically decided by the adaptive interactor.You must ensure that the sum of n over all test cases does not exceed 2\cdot 10^5.ExampleInput 2 5 2 0 0 1 5 3 0 0 1 Output 3 4 5 1 4 6 NoteTest Case 1:In this case, the hidden password is 2.The first query is 3. It is not equal to the current password. So, 0 is returned, and the password is changed to 1 since 2\oplus_2 1=3.The second query is 4. It is not equal to the current password. So, 0 is returned, and the password is changed to 5 since 1\oplus_2 5=4.The third query is 5. It is equal to the current password. So, 1 is returned, and the job is done.Test Case 2:In this case, the hidden password is 3.The first query is 1. It is not equal to the current password. So, 0 is returned, and the password is changed to 7 since 3\oplus_3 7=1. [3=(10)_3, 7=(21)_3, 1=(01)_3 and (10)_3\oplus_3 (21)_3 = (01)_3].The second query is 4. It is not equal to the current password. So, 0 is returned, and the password is changed to 6 since 7\oplus_3 6=4. [7=(21)_3, 6=(20)_3, 4=(11)_3 and (21)_3\oplus_3 (20)_3 = (11)_3].The third query is 6. It is equal to the current password. So, 1 is returned, and the job is done.Note that these initial passwords are taken just for the sake of explanation. In reality, the grader might behave differently because it is adaptive.
2 5 2 0 0 1 5 3 0 0 1
3 4 5 1 4 6
5 seconds
256 megabytes
['brute force', 'constructive algorithms', 'interactive', 'math', '*2200']
D1. RPD and Rap Sheet (Easy Version)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is that here k=2. You can make hacks only if both the versions of the problem are solved.This is an interactive problem.Every decimal number has a base k equivalent. The individual digits of a base k number are called k-its. Let's define the k-itwise XOR of two k-its a and b as (a + b)\bmod k.The k-itwise XOR of two base k numbers is equal to the new number formed by taking the k-itwise XOR of their corresponding k-its. The k-itwise XOR of two decimal numbers a and b is denoted by a\oplus_{k} b and is equal to the decimal representation of the k-itwise XOR of the base k representations of a and b. All further numbers used in the statement below are in decimal unless specified. When k = 2 (it is always true in this version), the k-itwise XOR is the same as the bitwise XOR.You have hacked the criminal database of Rockport Police Department (RPD), also known as the Rap Sheet. But in order to access it, you require a password. You don't know it, but you are quite sure that it lies between 0 and n-1 inclusive. So, you have decided to guess it. Luckily, you can try at most n times without being blocked by the system. But the system is adaptive. Each time you make an incorrect guess, it changes the password. Specifically, if the password before the guess was x, and you guess a different number y, then the system changes the password to a number z such that x\oplus_{k} z=y. Guess the password and break into the system.InputThe first line of input contains a single integer t (1\leq t\leq 10\,000) denoting the number of test cases. t test cases follow.The first line of each test case contains two integers n (1\leq n\leq 2\cdot 10^5) and k (k=2).It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.InteractionFor each test case, first read two integers n and k. Then you may ask up to n queries.For each query, print a single integer y (0\leq y\leq 2\cdot 10^7). Let the current password be x. After that, read an integer r.If x=y, you will read r=1 and the test case is solved. You must then continue solving the remaining test cases.Else, you will read r=0. At this moment the password is changed to a number z such that x\oplus_{k} z=y.After printing a query, do not forget to output the end of line and flush the output. Otherwise, you will get the 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. If you ask an invalid query or exceed n queries, you will read r=-1 and you will receive the Wrong Answer verdict. Make sure to exit immediately to avoid unexpected verdicts.Note that the interactor is adaptive. That is, the original password is not fixed in the beginning and may depend on your queries. But it is guaranteed that at any moment there is at least one initial password such that all the answers to the queries are consistent.Hacks:To use hacks, use the following format of tests:The first line should contain a single integer t (1\leq t\leq 10\,000) — the number of test cases.The first and only line of each test case should contain two integers n (1\leq n\leq 2\cdot 10^5) and k (k=2) denoting the number of queries and the base respectively. The optimal original password is automatically decided by the adaptive interactor.You must ensure that the sum of n over all test cases does not exceed 2\cdot 10^5.ExampleInput 1 5 2 0 0 1 Output 3 4 5 NoteIn the example test case, the hidden password is 2.The first query is 3. It is not equal to the current password. So, 0 is returned, and the password is changed to 1 since 2\oplus_2 1=3.The second query is 4. It is not equal to the current password. So, 0 is returned, and the password is changed to 5 since 1\oplus_2 5=4.The third query is 5. It is equal to the current password. So, 1 is returned, and the job is done.Note that this initial password is taken just for the sake of explanation. When you submit, the interactor might behave differently because it is adaptive.
1 5 2 0 0 1
3 4 5
5 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'interactive', 'math', '*1700']
C. Need for Pink Slipstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter defeating a Blacklist Rival, you get a chance to draw 1 reward slip out of x hidden valid slips. Initially, x=3 and these hidden valid slips are Cash Slip, Impound Strike Release Marker and Pink Slip of Rival's Car. Initially, the probability of drawing these in a random guess are c, m, and p, respectively. There is also a volatility factor v. You can play any number of Rival Races as long as you don't draw a Pink Slip. Assume that you win each race and get a chance to draw a reward slip. In each draw, you draw one of the x valid items with their respective probabilities. Suppose you draw a particular item and its probability of drawing before the draw was a. Then, If the item was a Pink Slip, the quest is over, and you will not play any more races. Otherwise, If a\leq v, the probability of the item drawn becomes 0 and the item is no longer a valid item for all the further draws, reducing x by 1. Moreover, the reduced probability a is distributed equally among the other remaining valid items. If a > v, the probability of the item drawn reduces by v and the reduced probability is distributed equally among the other valid items. For example, If (c,m,p)=(0.2,0.1,0.7) and v=0.1, after drawing Cash, the new probabilities will be (0.1,0.15,0.75). If (c,m,p)=(0.1,0.2,0.7) and v=0.2, after drawing Cash, the new probabilities will be (Invalid,0.25,0.75). If (c,m,p)=(0.2,Invalid,0.8) and v=0.1, after drawing Cash, the new probabilities will be (0.1,Invalid,0.9). If (c,m,p)=(0.1,Invalid,0.9) and v=0.2, after drawing Cash, the new probabilities will be (Invalid,Invalid,1.0). You need the cars of Rivals. So, you need to find the expected number of races that you must play in order to draw a pink slip.InputThe first line of input contains a single integer t (1\leq t\leq 10)  — the number of test cases.The first and the only line of each test case contains four real numbers c, m, p and v (0 < c,m,p < 1, c+m+p=1, 0.1\leq v\leq 0.9).Additionally, it is guaranteed that each of c, m, p and v have at most 4 decimal places.OutputFor each test case, output a single line containing a single real number — the expected number of races that you must play in order to draw a Pink Slip.Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}.ExampleInput 4 0.2 0.2 0.6 0.2 0.4 0.2 0.4 0.8 0.4998 0.4998 0.0004 0.1666 0.3125 0.6561 0.0314 0.2048 Output 1.532000000000 1.860000000000 5.005050776521 4.260163673896 NoteFor the first test case, the possible drawing sequences are: P with a probability of 0.6; CP with a probability of 0.2\cdot 0.7 = 0.14; CMP with a probability of 0.2\cdot 0.3\cdot 0.9 = 0.054; CMMP with a probability of 0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006; MP with a probability of 0.2\cdot 0.7 = 0.14; MCP with a probability of 0.2\cdot 0.3\cdot 0.9 = 0.054; MCCP with a probability of 0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006. So, the expected number of races is equal to 1\cdot 0.6 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 = 1.532.For the second test case, the possible drawing sequences are: P with a probability of 0.4; CP with a probability of 0.4\cdot 0.6 = 0.24; CMP with a probability of 0.4\cdot 0.4\cdot 1 = 0.16; MP with a probability of 0.2\cdot 0.5 = 0.1; MCP with a probability of 0.2\cdot 0.5\cdot 1 = 0.1. So, the expected number of races is equal to 1\cdot 0.4 + 2\cdot 0.24 + 3\cdot 0.16 + 2\cdot 0.1 + 3\cdot 0.1 = 1.86.
4 0.2 0.2 0.6 0.2 0.4 0.2 0.4 0.8 0.4998 0.4998 0.0004 0.1666 0.3125 0.6561 0.0314 0.2048
1.532000000000 1.860000000000 5.005050776521 4.260163673896
1 second
256 megabytes
['bitmasks', 'brute force', 'dfs and similar', 'implementation', 'math', 'probabilities', '*1900']
B. Customising the Tracktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHighway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into n sub-tracks. You are given an array a where a_i represents the number of traffic cars in the i-th sub-track. You define the inconvenience of the track as \sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert, where |x| is the absolute value of x. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.Find the minimum inconvenience you can achieve.InputThe first line of input contains a single integer t (1\leq t\leq 10\,000) — the number of test cases.The first line of each test case contains a single integer n (1\leq n\leq 2\cdot 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0\leq a_i\leq 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times.ExampleInput 3 3 1 2 3 4 0 1 1 0 10 8 3 6 11 5 2 1 7 10 4 Output 0 4 21 NoteFor the first test case, you can move a car from the 3-rd sub-track to the 1-st sub-track to obtain 0 inconvenience.For the second test case, moving any car won't decrease the inconvenience of the track.
3 3 1 2 3 4 0 1 1 0 10 8 3 6 11 5 2 1 7 10 4
0 4 21
1 second
256 megabytes
['combinatorics', 'greedy', 'math', '*900']
A. Exciting Betstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWelcome to Rockport City!It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet a dollars and Ronnie has bet b dollars. But the fans seem to be disappointed. The excitement of the fans is given by gcd(a,b), where gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y. To make the race more exciting, you can perform two types of operations: Increase both a and b by 1. Decrease both a and b by 1. This operation can only be performed if both a and b are greater than 0. In one move, you can perform any one of these operations. You can perform arbitrary (possibly zero) number of moves. Determine the maximum excitement the fans can get and the minimum number of moves required to achieve it.Note that gcd(x,0)=x for any x \ge 0.InputThe first line of input contains a single integer t (1\leq t\leq 5\cdot 10^3) — the number of test cases.The first and the only line of each test case contains two integers a and b (0\leq a, b\leq 10^{18}).OutputFor each test case, print a single line containing two integers. If the fans can get infinite excitement, print 0 0.Otherwise, the first integer must be the maximum excitement the fans can get, and the second integer must be the minimum number of moves required to achieve that excitement.ExampleInput 4 8 5 1 2 4 4 3 9 Output 3 1 1 0 0 0 6 3 NoteFor the first test case, you can apply the first operation 1 time to get a=9 and b=6. It can be shown that 3 is the maximum excitement possible.For the second test case, no matter how many operations you apply, the fans will always have an excitement equal to 1. Since the initial excitement is also 1, you don't need to apply any operation.For the third case, the fans can get infinite excitement by applying the first operation an infinite amount of times.For the fourth test case, you can apply the second operation 3 times to get a=0 and b=6. Since, gcd(0,6)=6, the fans will get an excitement of 6.
4 8 5 1 2 4 4 3 9
3 1 1 0 0 0 6 3
1 second
256 megabytes
['greedy', 'math', 'number theory', '*900']
E2. Abnormal Permutation Pairs (hard version)time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between the easy version and the hard version is the constraints on n. You can only make hacks if both versions are solved.A permutation of 1, 2, \ldots, n is a sequence of n integers, where each integer from 1 to n appears exactly once. For example, [2,3,1,4] is a permutation of 1, 2, 3, 4, but [1,4,2,2] isn't because 2 appears twice in it.Recall that the number of inversions in a permutation a_1, a_2, \ldots, a_n is the number of pairs of indices (i, j) such that i < j and a_i > a_j.Let p and q be two permutations of 1, 2, \ldots, n. Find the number of permutation pairs (p,q) that satisfy the following conditions: p is lexicographically smaller than q. the number of inversions in p is greater than the number of inversions in q. Print the number of such pairs modulo mod. Note that mod may not be a prime.InputThe only line contains two integers n and mod (1\le n\le 500, 1\le mod\le 10^9).OutputPrint one integer, which is the answer modulo mod.ExampleInput 4 403458273 Output 17NoteThe following are all valid pairs (p,q) when n=4. p=[1,3,4,2], q=[2,1,3,4], p=[1,4,2,3], q=[2,1,3,4], p=[1,4,3,2], q=[2,1,3,4], p=[1,4,3,2], q=[2,1,4,3], p=[1,4,3,2], q=[2,3,1,4], p=[1,4,3,2], q=[3,1,2,4], p=[2,3,4,1], q=[3,1,2,4], p=[2,4,1,3], q=[3,1,2,4], p=[2,4,3,1], q=[3,1,2,4], p=[2,4,3,1], q=[3,1,4,2], p=[2,4,3,1], q=[3,2,1,4], p=[2,4,3,1], q=[4,1,2,3], p=[3,2,4,1], q=[4,1,2,3], p=[3,4,1,2], q=[4,1,2,3], p=[3,4,2,1], q=[4,1,2,3], p=[3,4,2,1], q=[4,1,3,2], p=[3,4,2,1], q=[4,2,1,3].
4 403458273
17
4 seconds
512 megabytes
['combinatorics', 'dp', 'fft', 'math', '*2700']
E1. Abnormal Permutation Pairs (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between the easy version and the hard version is the constraints on n. You can only make hacks if both versions are solved.A permutation of 1, 2, \ldots, n is a sequence of n integers, where each integer from 1 to n appears exactly once. For example, [2,3,1,4] is a permutation of 1, 2, 3, 4, but [1,4,2,2] isn't because 2 appears twice in it.Recall that the number of inversions in a permutation a_1, a_2, \ldots, a_n is the number of pairs of indices (i, j) such that i < j and a_i > a_j.Let p and q be two permutations of 1, 2, \ldots, n. Find the number of permutation pairs (p,q) that satisfy the following conditions: p is lexicographically smaller than q. the number of inversions in p is greater than the number of inversions in q. Print the number of such pairs modulo mod. Note that mod may not be a prime.InputThe only line contains two integers n and mod (1\le n\le 50, 1\le mod\le 10^9).OutputPrint one integer, which is the answer modulo mod.ExampleInput 4 403458273 Output 17NoteThe following are all valid pairs (p,q) when n=4. p=[1,3,4,2], q=[2,1,3,4], p=[1,4,2,3], q=[2,1,3,4], p=[1,4,3,2], q=[2,1,3,4], p=[1,4,3,2], q=[2,1,4,3], p=[1,4,3,2], q=[2,3,1,4], p=[1,4,3,2], q=[3,1,2,4], p=[2,3,4,1], q=[3,1,2,4], p=[2,4,1,3], q=[3,1,2,4], p=[2,4,3,1], q=[3,1,2,4], p=[2,4,3,1], q=[3,1,4,2], p=[2,4,3,1], q=[3,2,1,4], p=[2,4,3,1], q=[4,1,2,3], p=[3,2,4,1], q=[4,1,2,3], p=[3,4,1,2], q=[4,1,2,3], p=[3,4,2,1], q=[4,1,2,3], p=[3,4,2,1], q=[4,1,3,2], p=[3,4,2,1], q=[4,2,1,3].
4 403458273
17
1 second
512 megabytes
['combinatorics', 'dp', 'fft', 'math', '*2400']
D. Priority Queuetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a sequence A, where its elements are either in the form + x or -, where x is an integer.For such a sequence S where its elements are either in the form + x or -, define f(S) as follows: iterate through S's elements from the first one to the last one, and maintain a multiset T as you iterate through it. for each element, if it's in the form + x, add x to T; otherwise, erase the smallest element from T (if T is empty, do nothing). after iterating through all S's elements, compute the sum of all elements in T. f(S) is defined as the sum. The sequence b is a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For all A's subsequences B, compute the sum of f(B), modulo 998\,244\,353.InputThe first line contains an integer n (1\leq n\leq 500) — the length of A.Each of the next n lines begins with an operator + or -. If the operator is +, then it's followed by an integer x (1\le x<998\,244\,353). The i-th line of those n lines describes the i-th element in A.OutputPrint one integer, which is the answer to the problem, modulo 998\,244\,353.ExamplesInput 4 - + 1 + 2 - Output 16Input 15 + 2432543 - + 4567886 + 65638788 - + 578943 - - + 62356680 - + 711111 - + 998244352 - - Output 750759115NoteIn the first example, the following are all possible pairs of B and f(B): B= {}, f(B)=0. B= {-}, f(B)=0. B= {+ 1, -}, f(B)=0. B= {-, + 1, -}, f(B)=0. B= {+ 2, -}, f(B)=0. B= {-, + 2, -}, f(B)=0. B= {-}, f(B)=0. B= {-, -}, f(B)=0. B= {+ 1, + 2}, f(B)=3. B= {+ 1, + 2, -}, f(B)=2. B= {-, + 1, + 2}, f(B)=3. B= {-, + 1, + 2, -}, f(B)=2. B= {-, + 1}, f(B)=1. B= {+ 1}, f(B)=1. B= {-, + 2}, f(B)=2. B= {+ 2}, f(B)=2. The sum of these values is 16.
4 - + 1 + 2 -
16
3 seconds
512 megabytes
['combinatorics', 'dp', 'implementation', 'math', 'ternary search', '*2200']
C. Strange Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet f(i) denote the minimum positive integer x such that x is not a divisor of i.Compute \sum_{i=1}^n f(i) modulo 10^9+7. In other words, compute f(1)+f(2)+\dots+f(n) modulo 10^9+7.InputThe first line contains a single integer t (1\leq t\leq 10^4), the number of test cases. Then t cases follow.The only line of each test case contains a single integer n (1\leq n\leq 10^{16}).OutputFor each test case, output a single integer ans, where ans=\sum_{i=1}^n f(i) modulo 10^9+7.ExampleInput 6 1 2 3 4 10 10000000000000000 Output 2 5 7 10 26 366580019 NoteIn the fourth test case n=4, so ans=f(1)+f(2)+f(3)+f(4). 1 is a divisor of 1 but 2 isn't, so 2 is the minimum positive integer that isn't a divisor of 1. Thus, f(1)=2. 1 and 2 are divisors of 2 but 3 isn't, so 3 is the minimum positive integer that isn't a divisor of 2. Thus, f(2)=3. 1 is a divisor of 3 but 2 isn't, so 2 is the minimum positive integer that isn't a divisor of 3. Thus, f(3)=2. 1 and 2 are divisors of 4 but 3 isn't, so 3 is the minimum positive integer that isn't a divisor of 4. Thus, f(4)=3. Therefore, ans=f(1)+f(2)+f(3)+f(4)=2+3+2+3=10.
6 1 2 3 4 10 10000000000000000
2 5 7 10 26 366580019
1 second
256 megabytes
['math', 'number theory', '*1600']
B. Plus and Multiplytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is an infinite set generated as follows: 1 is in this set. If x is in this set, x \cdot a and x+b both are in this set. For example, when a=3 and b=6, the five smallest elements of the set are: 1, 3 (1 is in this set, so 1\cdot a=3 is in this set), 7 (1 is in this set, so 1+b=7 is in this set), 9 (3 is in this set, so 3\cdot a=9 is in this set), 13 (7 is in this set, so 7+b=13 is in this set). Given positive integers a, b, n, determine if n is in this set.InputThe input consists of multiple test cases. The first line contains an integer t (1\leq t\leq 10^5) — the number of test cases. The description of the test cases follows.The only line describing each test case contains three integers n, a, b (1\leq n,a,b\leq 10^9) separated by a single space.OutputFor each test case, print "Yes" if n is in this set, and "No" otherwise. You can print each letter in any case.ExampleInput 5 24 3 5 10 3 6 2345 1 4 19260817 394 485 19260817 233 264 Output Yes No Yes No Yes NoteIn the first test case, 24 is generated as follows: 1 is in this set, so 3 and 6 are in this set; 3 is in this set, so 9 and 8 are in this set; 8 is in this set, so 24 and 13 are in this set. Thus we can see 24 is in this set.The five smallest elements of the set in the second test case is described in statements. We can see that 10 isn't among them.
5 24 3 5 10 3 6 2345 1 4 19260817 394 485 19260817 233 264
Yes No Yes No Yes
3 seconds
512 megabytes
['constructive algorithms', 'math', 'number theory', '*1500']
A. Odd Settime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a multiset (i. e. a set that can contain multiple equal integers) containing 2n integers. Determine if you can split it into exactly n pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by 2, the remainder is 1).InputThe input consists of multiple test cases. The first line contains an integer t (1\leq t\leq 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\leq n\leq 100).The second line of each test case contains 2n integers a_1,a_2,\dots, a_{2n} (0\leq a_i\leq 100) — the numbers in the set.OutputFor each test case, print "Yes" if it can be split into exactly n pairs so that the sum of the two elements in each pair is odd, and "No" otherwise. You can print each letter in any case.ExampleInput 5 2 2 3 4 5 3 2 3 4 5 5 5 1 2 4 1 2 3 4 1 5 3 2 6 7 3 4 Output Yes No No Yes No NoteIn the first test case, a possible way of splitting the set is (2,3), (4,5).In the second, third and fifth test case, we can prove that there isn't any possible way.In the fourth test case, a possible way of splitting the set is (2,3).
5 2 2 3 4 5 3 2 3 4 5 5 5 1 2 4 1 2 3 4 1 5 3 2 6 7 3 4
Yes No No Yes No
1 second
256 megabytes
['math', '*800']
B. Pleasant Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n consisting of n distinct integers. Count the number of pairs of indices (i, j) such that i < j and a_i \cdot a_j = i + j.InputThe first line contains one integer t (1 \leq t \leq 10^4) — the number of test cases. Then t cases follow.The first line of each test case contains one integer n (2 \leq n \leq 10^5) — the length of array a.The second line of each test case contains n space separated integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 2 \cdot n) — the array a. It is guaranteed that all elements are distinct.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_i \cdot a_j = i + j.ExampleInput 3 2 3 1 3 6 1 5 5 3 1 5 9 2 Output 1 1 3 NoteFor the first test case, the only pair that satisfies the constraints is (1, 2), as a_1 \cdot a_2 = 1 + 2 = 3For the second test case, the only pair that satisfies the constraints is (2, 3).For the third test case, the pairs that satisfy the constraints are (1, 2), (1, 5), and (2, 3).
3 2 3 1 3 6 1 5 5 3 1 5 9 2
1 1 3
2 seconds
256 megabytes
['brute force', 'implementation', 'math', 'number theory', '*1200']
A. Pretty Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. Then t test cases follow.The first and only line of each test case contains one integer n (2 \leq n \leq 100) — the number of cats.It can be proven that under the constraints of the problem, an answer always exist. OutputOutput t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.ExampleInput 2 2 3 Output 2 1 3 1 2 NoteFor the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].The second test case was described in the statement. Another possible answer is [2, 3, 1].
2 2 3
2 1 3 1 2
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*800']
E. Tasty Dishestime limit per test10 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputNote that the memory limit is unusual.There are n chefs numbered 1, 2, \ldots, n that must prepare dishes for a king. Chef i has skill i and initially has a dish of tastiness a_i where |a_i| \leq i. Each chef has a list of other chefs that he is allowed to copy from. To stop chefs from learning bad habits, the king makes sure that chef i can only copy from chefs of larger skill.There are a sequence of days that pass during which the chefs can work on their dish. During each day, there are two stages during which a chef can change the tastiness of their dish. At the beginning of each day, each chef can choose to work (or not work) on their own dish, thereby multiplying the tastiness of their dish of their skill (a_i := i \cdot a_i) (or doing nothing). After all chefs (who wanted) worked on their own dishes, each start observing the other chefs. In particular, for each chef j on chef i's list, chef i can choose to copy (or not copy) j's dish, thereby adding the tastiness of the j's dish to i's dish (a_i := a_i + a_j) (or doing nothing). It can be assumed that all copying occurs simultaneously. Namely, if chef i chooses to copy from chef j he will copy the tastiness of chef j's dish at the end of stage 1.All chefs work to maximize the tastiness of their own dish in order to please the king.Finally, you are given q queries. Each query is one of two types. 1 k l r — find the sum of tastiness a_l, a_{l+1}, \ldots, a_{r} after the k-th day. Because this value can be large, find it modulo 10^9 + 7. 2 i x — the king adds x tastiness to the i-th chef's dish before the 1-st day begins (a_i := a_i + x). Note that, because the king wants to see tastier dishes, he only adds positive tastiness (x > 0). Note that queries of type 1 are independent of each all other queries. Specifically, each query of type 1 is a scenario and does not change the initial tastiness a_i of any dish for future queries. Note that queries of type 2 are cumulative and only change the initial tastiness a_i of a dish. See notes for an example of queries.InputThe first line contains a single integer n (1 \le n \le 300) — the number of chefs.The second line contains n integers a_1, a_2, \ldots, a_n (-i \le a_i \le i).The next n lines each begin with a integer c_i (0 \le c_i < n), denoting the number of chefs the i-th chef can copy from. This number is followed by c_i distinct integers d (i < d \le n), signifying that chef i is allowed to copy from chef d during stage 2 of each day.The next line contains a single integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Each of the next q lines contains a query of one of two types: 1 k l r (1 \le l \le r \le n; 1 \le k \le 1000); 2 i x (1 \le i \le n; 1 \le x \le 1000). It is guaranteed that there is at least one query of the first type.OutputFor each query of the first type, print a single integer — the answer to the query.ExampleInput 5 1 0 -2 -2 4 4 2 3 4 5 1 3 1 4 1 5 0 7 1 1 1 5 2 4 3 1 1 1 5 2 3 2 1 2 2 4 2 5 1 1 981 4 5 Output 57 71 316 278497818 NoteBelow is the set of chefs that each chef is allowed to copy from: 1: \{2, 3, 4, 5\} 2: \{3\} 3: \{4\} 4: \{5\} 5: \emptyset (no other chefs)Following is a description of the sample.For the first query of type 1, the initial tastiness values are [1, 0, -2, -2, 4].The final result of the first day is shown below: [1, 0, -2, -2, 20] (chef 5 works on his dish). [21, 0, -2, 18, 20] (chef 1 and chef 4 copy from chef 5). So, the answer for the 1-st query is 21 + 0 - 2 + 18 + 20 = 57.For the 5-th query (3-rd of type 1). The initial tastiness values are now [1, 0, 0, 1, 4].Day 1 [1, 0, 0, 4, 20] (chefs 4 and 5 work on their dishes). [25,0, 4, 24, 20] (chef 1 copies from chefs 4 and 5, chef 3 copies from chef 4, chef 4 copies from chef 5). Day 2 [25, 0, 12, 96, 100] (all chefs but chef 2 work on their dish). [233, 12, 108, 196, 100] (chef 1 copies from chefs 3, 4 and 5, chef 2 from 3, chef 3 from 4, chef 4 from chef 5).So, the answer for the 5-th query is 12+108+196=316. It can be shown that, in each step we described, all chefs moved optimally.
5 1 0 -2 -2 4 4 2 3 4 5 1 3 1 4 1 5 0 7 1 1 1 5 2 4 3 1 1 1 5 2 3 2 1 2 2 4 2 5 1 1 981 4 5
57 71 316 278497818
10 seconds
64 megabytes
['math', 'matrices', '*3500']
D. Inverse Inversionstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou were playing with permutation p of length n, but you lost it in Blair, Alabama!Luckily, you remember some information about the permutation. More specifically, you remember an array b of length n, where b_i is the number of indices j such that j < i and p_j > p_i.You have the array b, and you want to find the permutation p. However, your memory isn't perfect, and you constantly change the values of b as you learn more. For the next q seconds, one of the following things happen: 1 i x — you realize that b_i is equal to x; 2 i — you need to find the value of p_i. If there's more than one answer, print any. It can be proven that there's always at least one possible answer under the constraints of the problem. Answer the queries, so you can remember the array!InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the size of permutation.The second line contains n integers b_1, b_2 \ldots, b_n (0 \leq b_i < i) — your initial memory of the array b.The third line contains a single integer q (1 \leq q \leq 10^5) — the number of queries.The next q lines contain the queries, each with one of the following formats: 1 i x (0 \leq x < i \leq n), representing a query of type 1. 2 i (1 \leq i \leq n), representing a query of type 2. It is guaranteed that there's at least one query of type 2.OutputFor each query of type 2, print one integer — the answer to the query.ExamplesInput 3 0 0 0 7 2 1 2 2 2 3 1 2 1 2 1 2 2 2 3 Output 1 2 3 2 1 3 Input 5 0 1 2 3 4 15 2 1 2 2 1 2 1 2 2 2 3 2 5 1 3 0 1 4 0 2 3 2 4 2 5 1 4 1 2 3 2 4 2 5 Output 5 4 4 3 1 4 5 1 5 4 1 NoteFor the first sample, there's initially only one possible permutation that satisfies the constraints: [1, 2, 3], as it must have 0 inversions.After the query of type 1, the array b is [0, 1, 0]. The only permutation p that produces this array is [2, 1, 3]. With this permutation, b_2 is equal to 1 as p_1 > p_2.
3 0 0 0 7 2 1 2 2 2 3 1 2 1 2 1 2 2 2 3
1 2 3 2 1 3
5 seconds
512 megabytes
['binary search', 'brute force', 'data structures', '*3200']
C2. Converging Array (Hard Version)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is that in this version 1 \le q \le 10^5. You can make hacks only if both versions of the problem are solved.There is a process that takes place on arrays a and b of length n and length n-1 respectively. The process is an infinite sequence of operations. Each operation is as follows: First, choose a random integer i (1 \le i \le n-1). Then, simultaneously set a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer). See notes for an example of an operation.It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 \leq a_i \leq c_i for 1 \leq i \leq n.Your task is to count the number of good arrays a where F(a, b) \geq x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.InputThe first line contains a single integer n (2 \le n \le 100).The second line contains n integers c_1, c_2 \ldots, c_n (0 \le c_i \le 100).The third line contains n-1 integers b_1, b_2, \ldots, b_{n-1} (0 \le b_i \le 100).The fourth line contains a single integer q (1 \le q \le 10^5).The fifth line contains q space separated integers x_1, x_2, \ldots, x_q (-10^5 \le x_i \le 10^5).OutputOutput q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) \geq x_i modulo 10^9+7.ExampleInput 3 2 3 4 2 1 5 -1 0 1 -100000 100000 Output 56 28 4 60 0 NoteThe following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).Examples of arrays a that are not good: a = [3, 2, 3] is not good because a_1 > c_1; a = [0, -1, 3] is not good because a_2 < 0. One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = \min(\frac{0+1-2}{2}, 0) and a_2 = \max(\frac{0+1+2}{2}, 1). So, after a single operation with i = 1, a becomes equal to [-\frac{1}{2}, \frac{3}{2}, 4]. We can show that no operation has any effect on this array, so F(a, b) = -\frac{1}{2}.
3 2 3 4 2 1 5 -1 0 1 -100000 100000
56 28 4 60 0
5 seconds
256 megabytes
['dp', 'math', '*2900']
C1. Converging Array (Easy Version)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.There is a process that takes place on arrays a and b of length n and length n-1 respectively. The process is an infinite sequence of operations. Each operation is as follows: First, choose a random integer i (1 \le i \le n-1). Then, simultaneously set a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer). See notes for an example of an operation.It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 \leq a_i \leq c_i for 1 \leq i \leq n.Your task is to count the number of good arrays a where F(a, b) \geq x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.InputThe first line contains a single integer n (2 \le n \le 100).The second line contains n integers c_1, c_2 \ldots, c_n (0 \le c_i \le 100).The third line contains n-1 integers b_1, b_2, \ldots, b_{n-1} (0 \le b_i \le 100).The fourth line contains a single integer q (q=1).The fifth line contains q space separated integers x_1, x_2, \ldots, x_q (-10^5 \le x_i \le 10^5).OutputOutput q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) \geq x_i modulo 10^9+7.ExampleInput 3 2 3 4 2 1 1 -1 Output 56 NoteThe following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).Examples of arrays a that are not good: a = [3, 2, 3] is not good because a_1 > c_1; a = [0, -1, 3] is not good because a_2 < 0. One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = \min(\frac{0+1-2}{2}, 0) and a_2 = \max(\frac{0+1+2}{2}, 1). So, after a single operation with i = 1, a becomes equal to [-\frac{1}{2}, \frac{3}{2}, 4]. We can show that no operation has any effect on this array, so F(a, b) = -\frac{1}{2}.
3 2 3 4 2 1 1 -1
56
5 seconds
256 megabytes
['dp', 'math', '*2700']
B. Tree Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array a is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).InputThe first line contains a single integer n (2 \le n \le 200) — the number of nodes in the tree.The next n - 1 lines each contains two integers x and y (1 \le x, y \le n; x \neq y), denoting an edge between node x and y.It's guaranteed that the given edges form a tree.OutputOutput the expected number of inversions in the generated array 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}.ExamplesInput 3 1 2 1 3 Output 166666669 Input 6 2 1 2 3 6 1 1 4 2 5 Output 500000009 Input 5 1 2 1 3 1 4 2 5 Output 500000007 NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is \frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}. 166666669 \cdot 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.This is the tree from the second sample: This is the tree from the third sample:
3 1 2 1 3
166666669
2 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'graphs', 'math', 'probabilities', 'trees', '*2300']
A. Great Graphstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John has a farm that consists of n pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array d, where d_i is the smallest amount of time it took the cows to reach the i-th pasture from pasture 1 using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.InputThe first line contains one integer t (1 \leq t \leq 10^4) — the number of test cases. Then t cases follow.The first line of each test case contains a single integer n (1 \leq n \leq 10^5) — the number of pastures.The second line of each test case contains n space separated integers d_1, d_2, \ldots, d_n (0 \leq d_i \leq 10^9) — the array d. It is guaranteed that d_1 = 0.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.ExampleInput 3 3 0 2 3 2 0 1000000000 1 0 Output -3 0 0 NoteIn the first test case, you can add roads from pasture 1 to pasture 2 with a time of 2, from pasture 2 to pasture 3 with a time of 1, from pasture 3 to pasture 1 with a time of -3, from pasture 3 to pasture 2 with a time of -1, from pasture 2 to pasture 1 with a time of -2. The total cost is 2 + 1 + -3 + -1 + -2 = -3.In the second test case, you can add a road from pasture 1 to pasture 2 with cost 1000000000 and a road from pasture 2 to pasture 1 with cost -1000000000. The total cost is 1000000000 + -1000000000 = 0.In the third test case, you can't add any roads. The total cost is 0.
3 3 0 2 3 2 0 1000000000 1 0
-3 0 0
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'greedy', 'shortest paths', 'sortings', '*1400']
F. Strange Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has an array of n integers a_1, a_2, \ldots, a_n. Vasya thinks that all numbers in his array are strange for some reason. To calculate how strange the i-th number is, Vasya created the following algorithm.He chooses a subsegment a_l, a_{l+1}, \ldots, a_r, such that 1 \le l \le i \le r \le n, sort its elements in increasing order in his head (he can arrange equal elements arbitrary). After that he finds the center of the segment. The center of a segment is the element at position (l + r) / 2, if the length of the segment is odd, and at position (l + r + 1) / 2 otherwise. Now Vasya finds the element that was at position i before the sorting, and calculates the distance between its current position and the center of the subsegment (the distance between the elements with indices j and k is |j - k|).The strangeness of the number at position i is the maximum distance among all suitable choices of l and r. Vasya wants to calculate the strangeness of each number in his array. Help him to do it. InputThe first line contains a single integer n (1 \le n \le 200\,000) — the size of the array.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — Vasya's array.OutputPrint a single line with n numbers. The i-th of them must be equal to the strangeness of the i-th element of the array.ExamplesInput 5 5 4 3 2 1 Output 2 1 1 2 2 Input 7 3 6 5 6 2 1 3 Output 2 3 1 3 2 3 1 NoteIn the first example: For the first position we choose the segment from 1 to 5. After sorting, it looks like [1, 2, 3, 4, 5], the center is 3. The distance from the center to 5 is 2. For the second position we choose the segment from 2 to 4. For the third position we choose the segment from 3 to 5. For the fourth position we choose the segment from 1 to 4. After sorting, it looks like [2, 3, 4, 5], the center is 4. The distance from the center to 2 is 2. For the fifth position we choose the segment from 1 to 5.
5 5 4 3 2 1
2 1 1 2 2
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*2600']
E. Game with Cardstime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Alice's computer is broken, so she can't play her favorite card game now. To help Alice, Bob wants to answer n her questions. Initially, Bob holds one card with number 0 in the left hand and one in the right hand. In the i-th question, Alice asks Bob to replace a card in the left or right hand with a card with number k_i (Bob chooses which of two cards he changes, Bob must replace exactly one card).After this action, Alice wants the numbers on the left and right cards to belong to given segments (segments for left and right cards can be different). Formally, let the number on the left card be x, and on the right card be y. Then after the i-th swap the following conditions must be satisfied: a_{l, i} \le x \le b_{l, i}, and a_{r, i} \le y \le b_{r,i}.Please determine if Bob can answer all requests. If it is possible, find a way to do it.InputThe first line contains two integers n and m (2 \le n \le 100\,000, 2 \le m \le 10^9) — the number of questions and the maximum possible value on the card.Then n queries are described. Every description contains 3 lines.The first line of the description of the i-th query contains a single integer k_i (0 \le k_i \le m) — the number on a new card.The second line of the description of the i-th query contains two integers a_{l, i} and b_{l, i} (0 \le a_{l, i} \le b_{l, i} \le m) — the minimum and maximum values of the card at the left hand after the replacement.The third line of the description of the i-th query contains two integers a_{r, i} and b_{r,i} (0 \le a_{r, i} \le b_{r,i} \le m) — the minimum and maximum values of the card at the right hand after the replacement.OutputAt the first line, print "Yes", if Bob can answer all queries, and "No" otherwise.If Bob can answer all n queries, then at the second line print n numbers: a way to satisfy all requirements. If in i-th query Bob needs to replace the card in the left hand, print 0, otherwise print 1. If there are multiple answers, print any.ExamplesInput 2 10 3 0 3 0 2 2 0 4 0 2 Output Yes 0 1 Input 2 10 3 0 3 0 2 2 3 4 0 1 Output NoInput 5 10 3 0 3 0 3 7 4 7 1 3 2 2 3 3 7 8 1 8 1 8 6 1 6 7 10 Output Yes 1 0 0 1 0
2 10 3 0 3 0 2 2 0 4 0 2
Yes 0 1
2.5 seconds
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'dp', 'greedy', 'implementation', '*2500']
D. PriceFixedtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLena is the most economical girl in Moscow. So, when her dad asks her to buy some food for a trip to the country, she goes to the best store  — "PriceFixed". Here are some rules of that store: The store has an infinite number of items of every product. All products have the same price: 2 rubles per item. For every product i there is a discount for experienced buyers: if you buy b_i items of products (of any type, not necessarily type i), then for all future purchases of the i-th product there is a 50\% discount (so you can buy an item of the i-th product for 1 ruble!). Lena needs to buy n products: she must purchase at least a_i items of the i-th product. Help Lena to calculate the minimum amount of money she needs to spend if she optimally chooses the order of purchasing. Note that if she wants, she can buy more items of some product than needed.InputThe first line contains a single integer n (1 \leq n \leq 100\,000) — the number of products.Each of next n lines contains a product description. Each description consists of two integers a_i and b_i (1 \leq a_i \leq 10^{14}, 1 \leq b_i \leq 10^{14}) — the required number of the i-th product and how many products you need to buy to get the discount on the i-th product. The sum of all a_i does not exceed 10^{14}.OutputOutput the minimum sum that Lena needs to make all purchases. ExamplesInput 3 3 4 1 3 1 5 Output 8 Input 5 2 7 2 8 1 2 2 4 1 8 Output 12 NoteIn the first example, Lena can purchase the products in the following way: one item of product 3 for 2 rubles, one item of product 1 for 2 rubles, one item of product 1 for 2 rubles, one item of product 2 for 1 ruble (she can use the discount because 3 items are already purchased), one item of product 1 for 1 ruble (she can use the discount because 4 items are already purchased). In total, she spends 8 rubles. It can be proved that it is impossible to spend less.In the second example Lena can purchase the products in the following way: one item of product 1 for 2 rubles, two items of product 2 for 2 rubles for each, one item of product 5 for 2 rubles, one item of product 3 for 1 ruble, two items of product 4 for 1 ruble for each, one item of product 1 for 1 ruble. In total, she spends 12 rubles.
3 3 4 1 3 1 5
8
1 second
256 megabytes
['binary search', 'greedy', 'implementation', 'sortings', 'two pointers', '*1600']
C. Stable Groupstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.For example, if x = 4, then the group with levels [1, 10, 8, 4, 4] is stable (because 4 - 1 \le x, 4 - 4 \le x, 8 - 4 \le x, 10 - 8 \le x), while the group with levels [2, 10, 10, 7] is not stable (7 - 2 = 5 > x).Apart from the n given students, teachers can invite at most k additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).For example, if there are two students with levels 1 and 5; x = 2; and k \ge 1, then you can invite a new student with level 3 and put all the students in one stable group.InputThe first line contains three integers n, k, x (1 \le n \le 200\,000, 0 \le k \le 10^{18}, 1 \le x \le 10^{18}) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{18}) — the students levels.OutputIn the only line print a single integer: the minimum number of stable groups you can split the students into.ExamplesInput 8 2 3 1 1 5 8 12 13 20 22 Output 2Input 13 0 37 20 20 80 70 70 70 420 5 1 5 1 60 90 Output 3NoteIn the first example you can invite two students with levels 2 and 11. Then you can split the students into two stable groups: [1, 1, 2, 5, 8, 11, 12, 13], [20, 22]. In the second example you are not allowed to invite new students, so you need 3 groups: [1, 1, 5, 5, 20, 20] [60, 70, 70, 70, 80, 90] [420]
8 2 3 1 1 5 8 12 13 20 22
2
1 second
256 megabytes
['greedy', 'sortings', '*1200']
B. Love Songtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.InputThe first line contains two integers n and q (1\leq n\leq 100\,000, 1\leq q \leq 100\,000) — the length of the song and the number of questions. The second line contains one string s — the song, consisting of n lowercase letters of English letters.Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 \leq l \leq r \leq n) — the bounds of the question.OutputPrint q lines: for each question print the length of the string obtained by Vasya.ExamplesInput 7 3 abacaba 1 3 2 5 1 7 Output 4 7 11 Input 7 4 abbabaa 1 3 5 7 6 6 2 4 Output 5 4 1 5 Input 13 7 sonoshikumiwo 1 5 2 10 7 7 1 13 4 8 2 5 3 9 Output 82 125 9 191 62 63 97 NoteIn the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
7 3 abacaba 1 3 2 5 1 7
4 7 11
2 seconds
256 megabytes
['dp', 'implementation', 'strings', '*800']
A. Contest Starttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people participating in some contest, they start participating in x minutes intervals. That means the first participant starts at time 0, the second participant starts at time x, the third — at time 2 \cdot x, and so on.Duration of contest is t minutes for each participant, so the first participant finishes the contest at time t, the second — at time t + x, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants.InputThe first line contains a single integer k (1 \le k \le 1000) — the number of test cases.Each of the next k lines contains three integers n, x, t (1 \le n, x, t \le 2 \cdot 10^9) — the number of participants, the start interval and the contest duration.OutputPrint k lines, in the i-th line print the total dissatisfaction of participants in the i-th test case.ExampleInput 4 4 2 5 3 1 2 3 3 10 2000000000 1 2000000000 Output 5 3 3 1999999999000000000 NoteIn the first example the first participant starts at 0 and finishes at time 5. By that time the second and the third participants start, so the dissatisfaction of the first participant is 2. The second participant starts at time 2 and finishes at time 7. By that time the third the fourth participants start, so the dissatisfaction of the second participant is 2. The third participant starts at 4 and finishes at 9. By that time the fourth participant starts, so the dissatisfaction of the third participant is 1.The fourth participant starts at 6 and finishes at 11. By time 11 everyone finishes the contest, so the dissatisfaction of the fourth participant is 0.In the second example the first participant starts at 0 and finishes at time 2. By that time the second participants starts, and the third starts at exactly time 2. So the dissatisfaction of the first participant is 2. The second participant starts at time 1 and finishes at time 3. At that time the third participant is solving the contest.
4 4 2 5 3 1 2 3 3 10 2000000000 1 2000000000
5 3 3 1999999999000000000
1 second
256 megabytes
['combinatorics', 'geometry', 'greedy', 'math', '*1000']
G. Gift Settime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has x of red and y of blue candies. Using them, he wants to make gift sets. Each gift set contains either a red candies and b blue candies, or a blue candies and b red candies. Any candy can belong to at most one gift set.Help Polycarp to find the largest number of gift sets he can create.For example, if x = 10, y = 12, a = 5, and b = 2, then Polycarp can make three gift sets: In the first set there will be 5 red candies and 2 blue candies; In the second set there will be 5 blue candies and 2 red candies; In the third set will be 5 blue candies and 2 red candies. Note that in this example there is one red candy that Polycarp does not use in any gift set.InputThe first line contains an integer t (1 \le t \le 10^4). Then t test cases follow.Each test case consists of a single string containing four integers x, y, a, and b (1 \le x, y, a, b \le 10^9).OutputFor each test case, output one number — the maximum number of gift sets that Polycarp can make.ExampleInput 9 10 12 2 5 1 1 2 2 52 311 13 27 1000000000 1000000000 1 1 1000000000 1 1 1000000000 1 1000000000 1000000000 1 1 2 1 1 7 8 1 2 4 1 2 3 Output 3 0 4 1000000000 1 1 1 5 0
9 10 12 2 5 1 1 2 2 52 311 13 27 1000000000 1000000000 1 1 1000000000 1 1 1000000000 1 1000000000 1000000000 1 1 2 1 1 7 8 1 2 4 1 2 3
3 0 4 1000000000 1 1 1 5 0
2 seconds
256 megabytes
['binary search', 'greedy', 'math', 'ternary search', '*2100']
F. Interesting Functiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers l and r, where l < r. We will add 1 to l until the result is equal to r. Thus, there will be exactly r-l additions performed. For each such addition, let's look at the number of digits that will be changed after it.For example: if l=909, then adding one will result in 910 and 2 digits will be changed; if you add one to l=9, the result will be 10 and 2 digits will also be changed; if you add one to l=489999, the result will be 490000 and 5 digits will be changed. Changed digits always form a suffix of the result written in the decimal system.Output the total number of changed digits, if you want to get r from l, adding 1 each time.InputThe first line contains an integer t (1 \le t \le 10^4). Then t test cases follow.Each test case is characterized by two integers l and r (1 \le l < r \le 10^9).OutputFor each test case, calculate the total number of changed digits if you want to get r from l, adding one each time.ExampleInput 4 1 9 9 10 10 20 1 1000000000 Output 8 2 11 1111111110
4 1 9 9 10 10 20 1 1000000000
8 2 11 1111111110
2 seconds
256 megabytes
['binary search', 'dp', 'math', 'number theory', '*1500']
E. Funny Substringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp came up with a new programming language. There are only two types of statements in it: "x := s": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a variable. Between the variable name, the := operator and the string contains exactly one space each. "x = a + b": assign the variable named x the concatenation of values of two variables a and b. For example, if the program consists of three statements a := hello, b := world, c = a + b, then the variable c will contain the string helloworld. It is guaranteed that the program is correct and the variables a and b were previously defined. There is exactly one space between the variable names and the = and + operators. All variable names and strings only consist of lowercase letters of the English alphabet and do not exceed 5 characters.The result of the program is the number of occurrences of string haha in the string that was written to the variable in the last statement.Polycarp was very tired while inventing that language. He asks you to implement it. Your task is — for given program statements calculate the number of occurrences of string haha in the last assigned variable.InputThe first line contains an 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 50) — the number of statements in the program. All variable names and strings are guaranteed to consist only of lowercase letters of the English alphabet and do not exceed 5 characters.This is followed by n lines describing the statements in the format described above. It is guaranteed that the program is correct.OutputFor each set of input data, output the number of occurrences of the haha substring in the string that was written to the variable in the last statement.ExampleInput 4 6 a := h b := aha c = a + b c = c + c e = c + c d = a + c 15 x := haha x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x 1 haha := hah 5 haahh := aaaha ahhhh = haahh + haahh haahh = haahh + haahh ahhhh = ahhhh + haahh ahhaa = haahh + ahhhh Output 3 32767 0 0 NoteIn the first test case the resulting value of d is hhahahaha.
4 6 a := h b := aha c = a + b c = c + c e = c + c d = a + c 15 x := haha x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x 1 haha := hah 5 haahh := aaaha ahhhh = haahh + haahh haahh = haahh + haahh ahhhh = ahhhh + haahh ahhaa = haahh + ahhhh
3 32767 0 0
2 seconds
256 megabytes
['data structures', 'hashing', 'implementation', 'matrices', 'strings', '*2100']
D. Another Problem About Dividing Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers a and b. In one turn, you can do one of the following operations: Take an integer c (c > 1 and a should be divisible by c) and replace a with \frac{a}{c}; Take an integer c (c > 1 and b should be divisible by c) and replace b with \frac{b}{c}. Your goal is to make a equal to b using exactly k turns.For example, the numbers a=36 and b=48 can be made equal in 4 moves: c=6, divide b by c \Rightarrow a=36, b=8; c=2, divide a by c \Rightarrow a=18, b=8; c=9, divide a by c \Rightarrow a=2, b=8; c=4, divide b by c \Rightarrow a=2, b=2. For the given numbers a and b, determine whether it is possible to make them equal using exactly k turns.InputThe first line contains one integer t (1 \le t \le 10^4). Then t test cases follow.Each test case is contains three integers a, b and k (1 \le a, b, k \le 10^9).OutputFor each test case output: "Yes", if it is possible to make the numbers a and b equal in exactly k turns; "No" otherwise. The strings "Yes" and "No" can be output in any case.ExampleInput 8 36 48 2 36 48 3 36 48 4 2 8 1 2 8 2 1000000000 1000000000 1000000000 1 2 1 2 2 1 Output YES YES YES YES YES NO YES NO
8 36 48 2 36 48 3 36 48 4 2 8 1 2 8 2 1000000000 1000000000 1000000000 1 2 1 2 2 1
YES YES YES YES YES NO YES NO
2 seconds
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1700']
C. Number of Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers. Find the number of pairs (i, j) (1 \le i < j \le n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l \le a_i + a_j \le r).For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: i=1 and j=2 (4 \le 5 + 1 \le 7); i=1 and j=3 (4 \le 5 + 2 \le 7). InputThe first line contains an integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains three integers n, l, r (1 \le n \le 2 \cdot 10^5, 1 \le l \le r \le 10^9) — the length of the array and the limits on the sum in the pair.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 overall test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l \le a_i + a_j \le r.ExampleInput 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 Output 2 7 0 1
4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1
2 7 0 1
2 seconds
256 megabytes
['binary search', 'data structures', 'math', 'two pointers', '*1300']
B. Friends and Candiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has n friends, the i-th of his friends has a_i candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all a_i to be the same. To solve this, Polycarp performs the following set of actions exactly once: Polycarp chooses k (0 \le k \le n) arbitrary friends (let's say he chooses friends with indices i_1, i_2, \ldots, i_k); Polycarp distributes their a_{i_1} + a_{i_2} + \ldots + a_{i_k} candies among all n friends. During distribution for each of a_{i_1} + a_{i_2} + \ldots + a_{i_k} candies he chooses new owner. That can be any of n friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number k is not fixed in advance and can be arbitrary. Your task is to find the minimum value of k.For example, if n=4 and a=[4, 5, 2, 5], then Polycarp could make the following distribution of the candies: Polycarp chooses k=2 friends with indices i=[2, 4] and distributes a_2 + a_4 = 10 candies to make a=[4, 4, 4, 4] (two candies go to person 3). Note that in this example Polycarp cannot choose k=1 friend so that he can redistribute candies so that in the end all a_i are equal.For the data n and a, determine the minimum value k. With this value k, Polycarp should be able to select k friends and redistribute their candies so that everyone will end up with the same number of candies.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 contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^4).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 minimum value of k, such that Polycarp can choose exactly k friends so that he can redistribute the candies in the desired way; "-1" if no such value k exists. ExampleInput 5 4 4 5 2 5 2 0 4 5 10 8 5 1 4 1 10000 7 1 1 1 1 1 1 1 Output 2 1 -1 0 0
5 4 4 5 2 5 2 0 4 5 10 8 5 1 4 1 10000 7 1 1 1 1 1 1 1
2 1 -1 0 0
2 seconds
256 megabytes
['greedy', 'math', '*800']
A. Stone Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is playing a new computer game. This game has n stones in a row. The stone on the position i has integer power a_i. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if n = 5 and a = [1, 5, 4, 3, 2], then Polycarp could make the following moves: Destroy the leftmost stone. After this move a = [5, 4, 3, 2]; Destroy the rightmost stone. After this move a = [5, 4, 3]; Destroy the leftmost stone. After this move a = [4, 3]. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example: Destroy the leftmost stone. After this move a = [5, 4, 3, 2]; Destroy the leftmost stone. After this move a = [4, 3, 2]. Polycarp destroyed the stones with the greatest and least power, so he can end the game. InputThe first line contains an integer t (1 \le t \le 100). Then t test cases follow.The first line of each test case contains one integer n (2 \le n \le 100) — the number of stones.The second line contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the power of the stones.OutputFor each test case, output the minimum number of moves required to destroy the stones with the greatest and the lowest power.ExampleInput 5 5 1 5 4 3 2 8 2 1 3 4 5 6 8 7 8 4 2 3 1 8 6 7 5 4 3 4 2 1 4 2 3 1 4 Output 2 4 5 3 2
5 5 1 5 4 3 2 8 2 1 3 4 5 6 8 7 8 4 2 3 1 8 6 7 5 4 3 4 2 1 4 2 3 1 4
2 4 5 3 2
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', '*800']
F. Figure Fixingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a connected undirected graph made of n nodes and m edges. The i-th node has a value v_i and a target value t_i.In an operation, you can choose an edge (i, j) and add k to both v_i and v_j, where k can be any integer. In particular, k can be negative.Your task to determine if it is possible that by doing some finite number of operations (possibly zero), you can achieve for every node i, v_i = t_i.InputThe first line contains a single integer t (1 \leq t \leq 1000), the number of test cases. Then the test cases follow.The first line of each test case contains two integers n, m (2 \leq n \leq 2\cdot 10^5, n-1\leq m\leq \min(2\cdot 10^5, \frac{n(n-1)}{2})) — the number of nodes and edges respectively.The second line contains n integers v_1\ldots, v_n (-10^9 \leq v_i \leq 10^9) — initial values of nodes.The third line contains n integers t_1\ldots, t_n (-10^9 \leq t_i \leq 10^9) — target values of nodes.Each of the next m lines contains two integers i and j representing an edge between node i and node j (1 \leq i, j \leq n, i\ne j).It is guaranteed that the graph is connected and there is at most one edge between the same pair of nodes.It is guaranteed that the sum of n over all testcases does not exceed 2 \cdot 10^5 and the sum of m over all testcases does not exceed 2 \cdot 10^5.OutputFor each test case, if it is possible for every node to reach its target after some number of operations, print "YES". Otherwise, print "NO".ExampleInput 2 4 4 5 1 2 -3 3 3 10 1 1 2 1 4 3 2 3 4 4 4 5 8 6 6 -3 1 15 4 1 2 1 4 3 2 3 4 Output YES NO NoteHere is a visualization of the first test case (the orange values denote the initial values and the blue ones the desired values): One possible order of operations to obtain the desired values for each node is the following: Operation 1: Add 2 to nodes 2 and 3. Operation 2: Add -2 to nodes 1 and 4. Operation 3: Add 6 to nodes 3 and 4. Now we can see that in total we added -2 to node 1, 2 to node 2, 8 to node 3 and 4 to node 4 which brings each node exactly to it's desired value.For the graph from the second test case it's impossible to get the target values.
2 4 4 5 1 2 -3 3 3 10 1 1 2 1 4 3 2 3 4 4 4 5 8 6 6 -3 1 15 4 1 2 1 4 3 2 3 4
YES NO
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'math', '*2200']
E2. Erase and Extend (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is the constraints on n and k. You can make hacks only if all versions of the problem are solved.You have a string s, and you can do two types of operations on it: Delete the last character of the string. Duplicate the string: s:=s+s, where + denotes concatenation. You can use each operation any number of times (possibly none).Your task is to find the lexicographically smallest string of length exactly k that can be obtained by doing these operations on string s.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a\ne b; In the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. InputThe first line contains two integers n, k (1 \leq n, k \leq 5\cdot 10^5) — the length of the original string s and the length of the desired string.The second line contains the string s, consisting of n lowercase English letters.OutputPrint the lexicographically smallest string of length k that can be obtained by doing the operations on string s.ExamplesInput 8 16 dbcadabc Output dbcadabcdbcadabc Input 4 5 abcd Output aaaaa NoteIn the first test, it is optimal to make one duplication: "dbcadabc" \to "dbcadabcdbcadabc".In the second test it is optimal to delete the last 3 characters, then duplicate the string 3 times, then delete the last 3 characters to make the string have length k."abcd" \to "abc" \to "ab" \to "a" \to "aa" \to "aaaa" \to "aaaaaaaa" \to "aaaaaaa" \to "aaaaaa" \to "aaaaa".
8 16 dbcadabc
dbcadabcdbcadabc
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'hashing', 'string suffix structures', 'strings', 'two pointers', '*2200']
E1. Erase and Extend (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is the constraints on n and k. You can make hacks only if all versions of the problem are solved.You have a string s, and you can do two types of operations on it: Delete the last character of the string. Duplicate the string: s:=s+s, where + denotes concatenation. You can use each operation any number of times (possibly none).Your task is to find the lexicographically smallest string of length exactly k that can be obtained by doing these operations on string s.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a\ne b; In the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. InputThe first line contains two integers n, k (1 \leq n, k \leq 5000) — the length of the original string s and the length of the desired string.The second line contains the string s, consisting of n lowercase English letters.OutputPrint the lexicographically smallest string of length k that can be obtained by doing the operations on string s.ExamplesInput 8 16 dbcadabc Output dbcadabcdbcadabc Input 4 5 abcd Output aaaaa NoteIn the first test, it is optimal to make one duplication: "dbcadabc" \to "dbcadabcdbcadabc".In the second test it is optimal to delete the last 3 characters, then duplicate the string 3 times, then delete the last 3 characters to make the string have length k."abcd" \to "abc" \to "ab" \to "a" \to "aa" \to "aaaa" \to "aaaaaaaa" \to "aaaaaaa" \to "aaaaaa" \to "aaaaa".
8 16 dbcadabc
dbcadabcdbcadabc
2 seconds
256 megabytes
['binary search', 'brute force', 'dp', 'greedy', 'hashing', 'implementation', 'string suffix structures', 'strings', 'two pointers', '*1600']
D. Deleting Divisorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game. They start with a positive integer n and take alternating turns doing operations on it. Each turn a player can subtract from n one of its divisors that isn't 1 or n. The player who cannot make a move on his/her turn loses. Alice always moves first.Note that they subtract a divisor of the current number in each turn.You are asked to find out who will win the game if both players play optimally.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Then t test cases follow.Each test case contains a single integer n (1 \leq n \leq 10^9) — the initial number.OutputFor each test case output "Alice" if Alice will win the game or "Bob" if Bob will win, if both players play optimally.ExampleInput 4 1 4 12 69 Output Bob Alice Alice Bob NoteIn the first test case, the game ends immediately because Alice cannot make a move.In the second test case, Alice can subtract 2 making n = 2, then Bob cannot make a move so Alice wins.In the third test case, Alice can subtract 3 so that n = 9. Bob's only move is to subtract 3 and make n = 6. Now, Alice can subtract 3 again and n = 3. Then Bob cannot make a move, so Alice wins.
4 1 4 12 69
Bob Alice Alice Bob
2 seconds
256 megabytes
['games', 'math', 'number theory', '*1700']
C. Challenging Cliffstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a game designer and want to make an obstacle course. The player will walk from left to right. You have n heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible. In addition, you want to make the game difficult, and since walking uphill or flat is harder than walking downhill, the difficulty of the level will be the number of mountains i (1 \leq i < n) such that h_i \leq h_{i+1} where h_i is the height of the i-th mountain. You don't want to waste any of the mountains you modelled, so you have to use all of them. From all the arrangements that minimize |h_1-h_n|, find one that is the most difficult. If there are multiple orders that satisfy these requirements, you may find any.InputThe first line will contain a single integer t (1 \leq t \leq 100) — the number of test cases. Then t test cases follow.The first line of each test case contains a single integer n (2 \leq n \leq 2 \cdot 10^5) — the number of mountains.The second line of each test case contains n integers h_1,\ldots,h_n (1 \leq h_i \leq 10^9), where h_i is the height of the i-th mountain.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output n integers — the given heights in an order that maximizes the difficulty score among all orders that minimize |h_1-h_n|.If there are multiple orders that satisfy these requirements, you may output any.ExampleInput 2 4 4 2 1 2 2 3 1 Output 2 4 1 2 1 3 NoteIn the first test case:The player begins at height 2, next going up to height 4 increasing the difficulty by 1. After that he will go down to height 1 and the difficulty doesn't change because he is going downhill. Finally the player will go up to height 2 and the difficulty will increase by 1. The absolute difference between the starting height and the end height is equal to 0 and it's minimal. The difficulty is maximal.In the second test case:The player begins at height 1, next going up to height 3 increasing the difficulty by 1. The absolute difference between the starting height and the end height is equal to 2 and it's minimal as they are the only heights. The difficulty is maximal.
2 4 4 2 1 2 2 3 1
2 4 1 2 1 3
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*1200']
B. Bad Boytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRiley is a very bad boy, but at the same time, he is a yo-yo master. So, he decided to use his yo-yo skills to annoy his friend Anton.Anton's room can be represented as a grid with n rows and m columns. Let (i, j) denote the cell in row i and column j. Anton is currently standing at position (i, j) in his room. To annoy Anton, Riley decided to throw exactly two yo-yos in cells of the room (they can be in the same cell).Because Anton doesn't like yo-yos thrown on the floor, he has to pick up both of them and return back to the initial position. The distance travelled by Anton is the shortest path that goes through the positions of both yo-yos and returns back to (i, j) by travelling only to adjacent by side cells. That is, if he is in cell (x, y) then he can travel to the cells (x + 1, y), (x - 1, y), (x, y + 1) and (x, y - 1) in one step (if a cell with those coordinates exists).Riley is wondering where he should throw these two yo-yos so that the distance travelled by Anton is maximized. But because he is very busy, he asked you to tell him.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Then t test cases follow.The only line of each test case contains four integers n, m, i, j (1 \leq n, m \leq 10^9, 1\le i\le n, 1\le j\le m) — the dimensions of the room, and the cell at which Anton is currently standing.OutputFor each test case, print four integers x_1, y_1, x_2, y_2 (1 \leq x_1, x_2 \leq n, 1\le y_1, y_2\le m) — the coordinates of where the two yo-yos should be thrown. They will be thrown at coordinates (x_1,y_1) and (x_2,y_2).If there are multiple answers, you may print any.ExampleInput 7 2 3 1 1 4 4 1 2 3 5 2 2 5 1 2 1 3 1 3 1 1 1 1 1 1000000000 1000000000 1000000000 50 Output 1 2 2 3 4 1 4 4 3 1 1 5 5 1 1 1 1 1 2 1 1 1 1 1 50 1 1 1000000000 NoteHere is a visualization of the first test case.
7 2 3 1 1 4 4 1 2 3 5 2 2 5 1 2 1 3 1 3 1 1 1 1 1 1000000000 1000000000 1000000000 50
1 2 2 3 4 1 4 4 3 1 1 5 5 1 1 1 1 1 2 1 1 1 1 1 50 1 1 1000000000
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*900']
A. Arithmetic Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array b of length k is called good if its arithmetic mean is equal to 1. More formally, if \frac{b_1 + \cdots + b_k}{k}=1.Note that the value \frac{b_1+\cdots+b_k}{k} is not rounded up or down. For example, the array [1,1,1,2] has an arithmetic mean of 1.25, which is not equal to 1.You are given an integer array a of length n. In an operation, you can append a non-negative integer to the end of the array. What's the minimum number of operations required to make the array good?We have a proof that it is always possible with finitely many operations.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases. Then t test cases follow.The first line of each test case contains a single integer n (1 \leq n \leq 50) — the length of the initial array a.The second line of each test case contains n integers a_1,\ldots,a_n (-10^4\leq a_i \leq 10^4), the elements of the array.OutputFor each test case, output a single integer — the minimum number of non-negative integers you have to append to the array so that the arithmetic mean of the array will be exactly 1.ExampleInput 4 3 1 1 1 2 1 2 4 8 4 6 2 1 -2 Output 0 1 16 1 NoteIn the first test case, we don't need to add any element because the arithmetic mean of the array is already 1, so the answer is 0.In the second test case, the arithmetic mean is not 1 initially so we need to add at least one more number. If we add 0 then the arithmetic mean of the whole array becomes 1, so the answer is 1.In the third test case, the minimum number of elements that need to be added is 16 since only non-negative integers can be added.In the fourth test case, we can add a single integer 4. The arithmetic mean becomes \frac{-2+4}{2} which is equal to 1.
4 3 1 1 1 2 1 2 4 8 4 6 2 1 -2
0 1 16 1
1 second
256 megabytes
['greedy', 'math', '*800']
F. Omkar and Akmartime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOmkar and Akmar are playing a game on a circular board with n (2 \leq n \leq 10^6) cells. The cells are numbered from 1 to n so that for each i (1 \leq i \leq n-1) cell i is adjacent to cell i+1 and cell 1 is adjacent to cell n. Initially, each cell is empty.Omkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter. A player loses when it is their turn and there are no more valid moves.Output the number of possible distinct games where both players play optimally modulo 10^9+7. Note that we only consider games where some player has lost and there are no more valid moves.Two games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different.A move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move.InputThe only line will contain an integer n (2 \leq n \leq 10^6) — the number of cells on the board.OutputOutput a single integer — the number of possible distinct games where both players play optimally modulo 10^9+7.ExamplesInput 2 Output 4 Input 69420 Output 629909355 Input 42069 Output 675837193 NoteFor the first sample case, the first player has 4 possible moves. No matter what the first player plays, the second player only has 1 possible move, so there are 4 possible games.
2
4
3 seconds
256 megabytes
['chinese remainder theorem', 'combinatorics', 'constructive algorithms', 'fft', 'games', 'geometry', 'math', 'meet-in-the-middle', 'string suffix structures', '*2600']
E. Omkar and Foresttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOmkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an n by m grid (1 \leq n, m \leq 2000) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions: For any two adjacent (sharing a side) cells, the absolute value of the difference of numbers in them is at most 1. If the number in some cell is strictly larger than 0, it should be strictly greater than the number in at least one of the cells adjacent to it. Unfortunately, Ajit is not fully worthy of Omkar's powers yet. He sees each cell as a "0" or a "#". If a cell is labeled as "0", then the number in it must equal 0. Otherwise, the number in it can be any nonnegative integer.Determine how many different assignments of elements exist such that these special conditions are satisfied. Two assignments are considered different if there exists at least one cell such that the numbers written in it in these assignments are different. Since the answer may be enormous, find the answer modulo 10^9+7.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 100). Description of the test cases follows.The first line of each test case contains two integers n and m (1 \leq n, m \leq 2000, nm \geq 2) – the dimensions of the forest.n lines follow, each consisting of one string of m characters. Each of these characters is either a "0" or a "#".It is guaranteed that the sum of n over all test cases does not exceed 2000 and the sum of m over all test cases does not exceed 2000.OutputFor each test case, print one integer: the number of valid configurations modulo 10^9+7.ExampleInput 4 3 4 0000 00#0 0000 2 1 # # 1 2 ## 6 29 ############################# #000##0###0##0#0####0####000# #0#0##00#00##00####0#0###0#0# #0#0##0#0#0##00###00000##00## #000##0###0##0#0##0###0##0#0# ############################# Output 2 3 3 319908071 NoteFor the first test case, the two valid assignments are0000\\ 0000\\ 0000and0000\\ 0010\\ 0000
4 3 4 0000 00#0 0000 2 1 # # 1 2 ## 6 29 ############################# #000##0###0##0#0####0####000# #0#0##00#00##00####0#0###0#0# #0#0##0#0#0##00###00000##00## #000##0###0##0#0##0###0##0#0# #############################
2 3 3 319908071
2 seconds
256 megabytes
['combinatorics', 'graphs', 'math', 'shortest paths', '*2300']
D. Omkar and Medianstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, \ldots, a_{2k-1}, is the array b with elements b_1, b_2, \ldots, b_{k} such that b_i is equal to the median of a_1, a_2, \ldots, a_{2i-1} for all i. Omkar has found an array b of size n (1 \leq n \leq 2 \cdot 10^5, -10^9 \leq b_i \leq 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray?The median of a set of numbers a_1, a_2, \ldots, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, \ldots, c_{2i-1} represents a_1, a_2, \ldots, a_{2i-1} sorted in nondecreasing order. InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the array b.The second line contains n integers b_1, b_2, \ldots, b_n (-10^9 \leq b_i \leq 10^9) — the elements of b.It is guaranteed the sum of n across all test cases does not exceed 2 \cdot 10^5. OutputFor each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, \dots, a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted).ExamplesInput 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO NoteIn the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4.In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3.In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as the median of 2 is 2 the median of 0, 1, 2 is 1 the median of 0, 1, 2, 3, 4 is 2 and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as the median of 1 is 1 the median of 0, 1, 4 is 1 the median of 0, 1, 3, 4, 5 is 3 the median of -2, -2, 0, 1, 3, 4, 5 is 1 the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3
NO YES NO YES YES
2 seconds
256 megabytes
['data structures', 'greedy', 'implementation', '*2000']
C. Diluc and Kaeyatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if a\cdot d = b\cdot c. For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' — 2:1, for 'DKK' — 1:2, and for 'KKKKDD' — 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.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 an integer n (1 \leq n \leq 5 \cdot 10^5) — the length of the wood.The second line of each test case contains a string s of length n. Every character of s will be either 'D' or 'K'.It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, output n space separated integers. The i-th of these numbers should equal the answer for the prefix s_{1},s_{2},\dots,s_{i}.ExampleInput 5 3 DDK 6 DDDDDD 4 DKDK 1 D 9 DKDKDDDDK Output 1 2 1 1 2 3 4 5 6 1 1 1 2 1 1 1 1 2 1 2 1 1 3 NoteFor the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.For the second test case, you can split each prefix of length i into i blocks 'D'.
5 3 DDK 6 DDDDDD 4 DKDK 1 D 9 DKDKDDDDK
1 2 1 1 2 3 4 5 6 1 1 1 2 1 1 1 1 2 1 2 1 1 3
2 seconds
256 megabytes
['data structures', 'dp', 'hashing', 'number theory', '*1500']
B. Prinzessin der Verurteilungtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputI, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying?You are given a string of n lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Find out what the MEX of the string is!InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 1000). Description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 1000) — the length of the word. The second line for each test case contains a single string of n lowercase Latin letters.The sum of n over all test cases will not exceed 1000.OutputFor each test case, output the MEX of the string on a new line.ExampleInput 3 28 qaabzwsxedcrfvtgbyhnujmiklop 13 cleanairactbd 10 aannttoonn Output ac f b
3 28 qaabzwsxedcrfvtgbyhnujmiklop 13 cleanairactbd 10 aannttoonn
ac f b
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'strings', '*1200']
A. Omkar and Bad Storytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOmkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array a = [a_1, a_2, \ldots, a_n] of n distinct integers. An array b = [b_1, b_2, \ldots, b_k] is called nice if for any two distinct elements b_i, b_j of b, |b_i-b_j| appears in b at least once. In addition, all elements in b must be distinct. Can you add several (maybe, 0) integers to a to create a nice array b of size at most 300? If a is already nice, you don't have to add any elements.For example, array [3, 6, 9] is nice, as |6-3|=|9-6| = 3, which appears in the array, and |9-3| = 6, which appears in the array, while array [4, 2, 0, 6, 9] is not nice, as |9-4| = 5 is not present in the array.For integers x and y, |x-y| = x-y if x > y and |x-y| = y-x otherwise.InputEach test contains multiple test cases. The first line contains t (1 \leq t \leq 50), the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 100) — the length of the array a.The second line of each test case contains n distinct integers a_1, a_2, \cdots, a_n (-100 \leq a_i \leq 100) — the elements of the array a.OutputFor each test case, output one line containing YES if Omkar can create a nice array b by adding elements to a and NO otherwise. The case of each letter does not matter, so yEs and nO will also be accepted.If the first line is YES, output a second line containing a single integer k (n \leq k \leq 300). Then output one line containing k distinct integers b_1, b_2, \cdots, b_k (-10^9 \leq b_i \leq 10^9), the elements of the nice array b. b_1, b_2, \cdots, b_k can be in any order. For each a_i in a, a_i must appear at least once in b.It can be proved that if Omkar can create such an array b, then he can also do so in a way that satisfies the above constraints.If multiple solutions exist, you can print any. ExampleInput 4 3 3 0 9 2 3 4 5 -7 3 13 -2 8 4 4 8 12 6 Output yes 4 6 0 3 9 yEs 5 5 3 1 2 4 NO Yes 6 8 12 6 2 4 10 NoteFor the first case, you can add integers to a to receive the array b = [6, 0, 3, 9]. Note that |6-3| = |9-6| = |3-0| = 3 and 3 is in b, |6-0| = |9-3| = 6 and 6 is in b, and |9-0| = 9 is in b, so b is nice.For the second case, you can add integers to a to receive the array b = [5, 3, 1, 2, 4]. We have that |2-1| = |3-2| = |4-3| = |5-4| = 1 is in b, |3-1| = |4-2| = |5-3| = 2 is in b, |4-1| = |5-2| = 3 is in b, and |5-1| = 4 is in b, so b is nice.For the fourth case, you can add integers to a to receive the array b = [8, 12, 6, 2, 4, 10]. We have that |4-2| = |6-4| = |8-6| = |10-8| = |12-10| = 2 is in b, |6-2| = |8-4| = |10-6| = |12-8| = 4 is in b, |8-2| = |10-4| = |12-6| = 6 is in b, |10-2| = |12-4| = 8 is in b, and |12-2| = 10 is in b, so b is nice.It can be proven that for all other test cases it is impossible to create a nice array b.
4 3 3 0 9 2 3 4 5 -7 3 13 -2 8 4 4 8 12 6
yes 4 6 0 3 9 yEs 5 5 3 1 2 4 NO Yes 6 8 12 6 2 4 10
2 seconds
256 megabytes
['brute force', 'constructive algorithms', '*800']
F. String Distancetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputSuppose you are given two strings a and b. You can apply the following operation any number of times: choose any contiguous substring of a or b, and sort the characters in it in non-descending order. Let f(a, b) the minimum number of operations you have to apply in order to make them equal (or f(a, b) = 1337 if it is impossible to make a and b equal using these operations).For example: f(\text{ab}, \text{ab}) = 0; f(\text{ba}, \text{ab}) = 1 (in one operation, we can sort the whole first string); f(\text{ebcda}, \text{ecdba}) = 1 (in one operation, we can sort the substring of the second string starting from the 2-nd character and ending with the 4-th character); f(\text{a}, \text{b}) = 1337. You are given n strings s_1, s_2, \dots, s_k having equal length. Calculate \sum \limits_{i = 1}^{n} \sum\limits_{j = i + 1}^{n} f(s_i, s_j).InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of strings.Then n lines follow, each line contains one of the strings s_i, consisting of lowercase Latin letters. |s_1| = |s_2| = \ldots = |s_n|, and n \cdot |s_1| \le 2 \cdot 10^5. All these strings are pairwise distinct.OutputPrint one integer: \sum \limits_{i = 1}^{n} \sum\limits_{j = i + 1}^{n} f(s_i, s_j).ExamplesInput 4 zzz bac abc acb Output 4015 Input 2 a b Output 1337
4 zzz bac abc acb
4015
2 seconds
1024 megabytes
['binary search', 'brute force', 'data structures', 'hashing', 'implementation', 'strings', '*3000']
E. Gold Transfertime limit per test4.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree. Each vertex contains a_i tons of gold, which costs c_i per one ton. Initially, the tree consists only a root numbered 0 with a_0 tons of gold and price c_0 per ton.There are q queries. Each query has one of two types: Add vertex i (where i is an index of query) as a son to some vertex p_i; vertex i will have a_i tons of gold with c_i per ton. It's guaranteed that c_i > c_{p_i}. For a given vertex v_i consider the simple path from v_i to the root. We need to purchase w_i tons of gold from vertices on this path, spending the minimum amount of money. If there isn't enough gold on the path, we buy all we can. If we buy x tons of gold in some vertex v the remaining amount of gold in it decreases by x (of course, we can't buy more gold that vertex has at the moment). For each query of the second type, calculate the resulting amount of gold we bought and the amount of money we should spend.Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query, so don't forget to flush output after printing answers. You can use functions like fflush(stdout) in C++ and BufferedWriter.flush in Java or similar after each writing in your program. In standard (if you don't tweak I/O), endl flushes cout in C++ and System.out.println in Java (or println in Kotlin) makes automatic flush as well. InputThe first line contains three integers q, a_0 and c_0 (1 \le q \le 3 \cdot 10^5; 1 \le a_0, c_0 < 10^6) — the number of queries, the amount of gold in the root and its price.Next q lines contain descriptions of queries; The i-th query has one of two types: "1 p_i a_i c_i" (0 \le p_i < i; 1 \le a_i, c_i < 10^6): add vertex i as a son to vertex p_i. The vertex i will have a_i tons of gold with price c_i per one ton. It's guaranteed that p_i exists and c_i > c_{p_i}. "2 v_i w_i" (0 \le v_i < i; 1 \le w_i < 10^6): buy w_i tons of gold from vertices on path from v_i to 0 spending the minimum amount of money. If there isn't enough gold, we buy as much as we can. It's guaranteed that vertex v_i exist. It's guaranteed that there is at least one query of the second type.OutputFor each query of the second type, print the resulting amount of gold we bought and the minimum amount of money we should spend.ExampleInput 5 5 2 2 0 2 1 0 3 4 2 2 4 1 0 1 3 2 4 2 Output 2 4 4 10 1 3 NoteExplanation of the sample:At the first query, the tree consist of root, so we purchase 2 tons of gold and pay 2 \cdot 2 = 4. 3 tons remain in the root.At the second query, we add vertex 2 as a son of vertex 0. Vertex 2 now has 3 tons of gold with price 4 per one ton.At the third query, a path from 2 to 0 consists of only vertices 0 and 2 and since c_0 < c_2 we buy 3 remaining tons of gold in vertex 0 and 1 ton in vertex 2. So we bought 3 + 1 = 4 tons and paid 3 \cdot 2 + 1 \cdot 4 = 10. Now, in vertex 0 no gold left and 2 tons of gold remain in vertex 2.At the fourth query, we add vertex 4 as a son of vertex 0. Vertex 4 now has 1 ton of gold with price 3.At the fifth query, a path from 4 to 0 consists of only vertices 0 and 4. But since no gold left in vertex 0 and only 1 ton is in vertex 4, we buy 1 ton of gold in vertex 4 and spend 1 \cdot 3 = 3. Now, in vertex 4 no gold left.
5 5 2 2 0 2 1 0 3 4 2 2 4 1 0 1 3 2 4 2
2 4 4 10 1 3
4.5 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'greedy', 'interactive', 'trees', '*2200']
D. Playoff Tournamenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output2^k teams participate in a playoff tournament. The tournament consists of 2^k - 1 games. They are held as follows: first of all, the teams are split into pairs: team 1 plays against team 2, team 3 plays against team 4 (exactly in this order), and so on (so, 2^{k-1} games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only 2^{k-1} teams remain. If only one team remains, it is declared the champion; otherwise, 2^{k-2} games are played: in the first one of them, the winner of the game "1 vs 2" plays against the winner of the game "3 vs 4", then the winner of the game "5 vs 6" plays against the winner of the game "7 vs 8", and so on. This process repeats until only one team remains.For example, this picture describes the chronological order of games with k = 3: Let the string s consisting of 2^k - 1 characters describe the results of the games in chronological order as follows: if s_i is 0, then the team with lower index wins the i-th game; if s_i is 1, then the team with greater index wins the i-th game; if s_i is ?, then the result of the i-th game is unknown (any team could win this game). Let f(s) be the number of possible winners of the tournament described by the string s. A team i is a possible winner of the tournament if it is possible to replace every ? with either 1 or 0 in such a way that team i is the champion.You are given the initial state of the string s. You have to process q queries of the following form: p c — replace s_p with character c, and print f(s) as the result of the query. InputThe first line contains one integer k (1 \le k \le 18).The second line contains a string consisting of 2^k - 1 characters — the initial state of the string s. Each character is either ?, 0, or 1.The third line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Then q lines follow, the i-th line contains an integer p and a character c (1 \le p \le 2^k - 1; c is either ?, 0, or 1), describing the i-th query.OutputFor each query, print one integer — f(s).ExampleInput 3 0110?11 6 5 1 6 ? 7 ? 1 ? 5 ? 1 1 Output 1 2 3 3 5 4
3 0110?11 6 5 1 6 ? 7 ? 1 ? 5 ? 1 1
1 2 3 3 5 4
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'dp', 'implementation', 'trees', '*1800']
C. Unstable Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of the characters 0, 1, and ?.Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes unstable.For example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not.Calculate the number of beautiful contiguous substrings of the string s.InputThe first line contains a single integer t (1 \le t \le 10^4) — number of test cases.The first and only line of each test case contains the string s (1 \le |s| \le 2 \cdot 10^5) consisting of characters 0, 1, and ?.It is guaranteed that the sum of the string lengths over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the number of beautiful substrings of the string s.ExampleInput 3 0?10 ??? ?10??1100 Output 8 6 25
3 0?10 ??? ?10??1100
8 6 25
2 seconds
256 megabytes
['binary search', 'dp', 'greedy', 'implementation', 'strings', 'two pointers', '*1400']
B. Array Reoderingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers.Let's call a pair of indices i, j good if 1 \le i < j \le n and \gcd(a_i, 2a_j) > 1 (where \gcd(x, y) is the greatest common divisor of x and y).Find the maximum number of good index pairs if you can reorder the array a in an arbitrary way.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of the test case contains a single integer n (2 \le n \le 2000) — the number of elements in the array.The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^5).It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case, output a single integer — the maximum number of good index pairs if you can reorder the array a in an arbitrary way.ExampleInput 3 4 3 6 5 3 2 1 7 5 1 4 2 4 1 Output 4 0 9 NoteIn the first example, the array elements can be rearranged as follows: [6, 3, 5, 3].In the third example, the array elements can be rearranged as follows: [4, 4, 2, 1, 1].
3 4 3 6 5 3 2 1 7 5 1 4 2 4 1
4 0 9
2 seconds
256 megabytes
['brute force', 'greedy', 'math', 'number theory', 'sortings', '*900']
A. Fair Playofftime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFour players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament.It is known that in a match between two players, the one whose skill is greater will win. The skill of the i-th player is equal to s_i and all skill levels are pairwise different (i. e. there are no two identical values in the array s).The tournament is called fair if the two players with the highest skills meet in the finals.Determine whether the given tournament is fair.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.A single line of test case contains four integers s_1, s_2, s_3, s_4 (1 \le s_i \le 100) — skill of the players. It is guaranteed that all the numbers in the array are different.OutputFor each testcase, output YES if the tournament is fair, or NO otherwise.ExampleInput 4 3 7 9 5 4 5 6 9 5 3 8 1 6 5 3 2 Output YES NO YES NO NoteConsider the example: in the first test case, players 2 and 3 with skills 7 and 9 advance to the finals; in the second test case, players 2 and 4 with skills 5 and 9 advance to the finals. The player with skill 6 does not advance, but the player with skill 5 advances to the finals, so the tournament is not fair; in the third test case, players 1 and 3 with skills 5 and 8 advance to the finals; in the fourth test case, players 1 and 3 with skills 6 and 3 advance to the finals. The player with skill 5 does not advance, but the player with skill 3 advances to the finals, so the tournament is not fair.
4 3 7 9 5 4 5 6 9 5 3 8 1 6 5 3 2
YES NO YES NO
2 seconds
256 megabytes
['brute force', 'implementation', '*800']
H. Lost Nodestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.As he qualified for IOI this year, Little Ericyi was given a gift from all his friends: a tree of n nodes!On the flight to IOI Little Ericyi was very bored, so he decided to play a game with Little Yvonne with his new tree. First, Little Yvonne selects two (not necessarily different) nodes a and b on the tree (without telling Ericyi), and then gives him a hint f (which is some node on the path from a to b).Then, Little Ericyi is able to ask the following question repeatedly: If I rooted the tree at node r (Ericyi gets to choose r), what would be the Lowest Common Ancestor of a and b?Little Ericyi's goal is to find the nodes a and b, and report them to Little Yvonne.However, Little Yvonne thought this game was too easy, so before he gives the hint f to Little Ericyi, he also wants him to first find the maximum number of queries required to determine a and b over all possibilities of a, b, and f assuming Little Ericyi plays optimally. Little Ericyi defines an optimal strategy as one that makes the minimum number of queries. Of course, once Little Ericyi replies with the maximum number of queries, Little Yvonne will only let him use that many queries in the game.The tree, a, b, and f are all fixed before the start of the game and do not change as queries are made.InteractionFirst read a line containing the integer n (1 \le n \le 10^5), the number of nodes in the tree.The next n−1 lines describe Little Ericyi's tree. These lines contain two integers u and v (1 \le u,v \le n) denoting an edge between u and v (u \neq v). It is guaranteed that these edges form a tree.After that you should output k, the maximum number of queries needed to determine a and b over all possibilities of a, b, and f assuming Little Ericyi plays optimally. You should output end of line and flush the output after printing k.After that read a line containing the integer f (1 \le f \le n) — the hint: a node on the path from a to b, inclusive.After that, you can start making queries. You will be limited to making at most k queries, where k is the number you printed.Each query is made in the format "? r", where r is an integer 1 \le r \le n denoting the root node you want for the query.You will then receive an integer x (1 \le x \le n), the Lowest Common Ancestor of a and b if the tree was rooted at r.When your program has found the nodes a, b, report the answer in the following format: "! a b", where a and b are the two hidden nodes and terminate your program normally immediately after flushing the output stream. You may output a and b in any order.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.If at any point you make an invalid output or make more than k queries, the interaction will terminate and you will receive a Wrong Answer verdict. An invalid output is defined as either an invalid query or a value of k less than 0 or greater than n.HacksTo hack a solution, use the following format:The first line contains the integer n (1 \le n \le 10^5).The next n−1 lines contain two integers u and v (1 \le u,v \le n) denoting an edge between u and v (u \neq v). These n-1 edges must form a tree.The next line of input contains the nodes a and b (1 \le a,b \le n), separated by a space.The final line of input contains the integer f (1 \le f \le n). Node f should be on the simple path from a to b (inclusive).ExamplesInput 4 3 2 2 1 2 4 1 1 2 2 Output 3 ? 1 ? 2 ? 3 ! 4 1Input 5 3 1 1 4 4 5 4 2 1 4 1 4 Output 3 ? 4 ? 1 ? 5 ! 1 4NoteHere is the the tree from the first sample interaction. Nodes a and b are highlighted. Notice that a and b can be output in any order.Additionally, here are the answers to querying every single node 1,2,\ldots,n for your convenience: 1: 1 2: 2 3: 2 4: 4__________________________________________Here is the the tree from the second sample interaction. Again, nodes a and b are highlighted. Lastly, here are the answers to querying every single node 1,2,\ldots,n (in example 2) for your convenience: 1: 1 2: 4 3: 1 4: 4 5: 4
4 3 2 2 1 2 4 1 1 2 2
3 ? 1 ? 2 ? 3 ! 4 1
4 seconds
256 megabytes
['constructive algorithms', 'dp', 'graphs', 'interactive', 'sortings', 'trees', '*3500']
G. A New Beginningtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnnie has gotten bored of winning every coding contest and farming unlimited rating. Today, she is going to farm potatoes instead.Annie's garden is an infinite 2D plane. She has n potatoes to plant, and the i-th potato must be planted at (x_i,y_i). Starting at the point (0, 0), Annie begins walking, in one step she can travel one unit right or up (increasing her x or y coordinate by 1 respectively). At any point (X,Y) during her walk she can plant some potatoes at arbitrary points using her potato gun, consuming \max(|X-x|,|Y-y|) units of energy in order to plant a potato at (x,y). Find the minimum total energy required to plant every potato.Note that Annie may plant any number of potatoes from any point.InputThe first line contains the integer n (1 \le n \le 800\,000).The next n lines contain two integers x_i and y_i (0 \le x_i,y_i \le 10^9), representing the location of the i-th potato. It is possible that some potatoes should be planted in the same location.OutputPrint the minimum total energy to plant all potatoes.ExamplesInput 2 1 1 2 2 Output 0 Input 2 1 1 2 0 Output 1 Input 3 5 5 7 7 4 9 Output 2 Input 10 5 1 4 0 9 6 0 2 10 1 9 10 3 10 0 10 8 9 1 5 Output 19 Input 10 1 1 2 2 2 0 4 2 4 0 2 0 0 2 4 0 4 2 5 1 Output 6 NoteIn example 1, Annie can travel to each spot directly and plant a potato with no energy required.In example 2, moving to (1,0), Annie plants the second potato using 1 energy. Next, she travels to (1,1) and plants the first potato with 0 energy.
2 1 1 2 2
0
5 seconds
256 megabytes
['data structures', 'dp', 'geometry', 'sortings', '*3300']
F2. Falling Sand (Hard Version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference between the versions is the constraints on a_i. You can make hacks only if all versions of the problem are solved.Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board with n rows and m columns of cells, some empty and some filled with blocks of sand, and m non-negative integers a_1,a_2,\ldots,a_m (0 \leq a_i \leq n). In this version of the problem, a_i will always be not greater than the number of blocks of sand in column i.When a cell filled with a block of sand is disturbed, the block of sand will fall from its cell to the sand counter at the bottom of the column (each column has a sand counter). While a block of sand is falling, other blocks of sand that are adjacent at any point to the falling block of sand will also be disturbed and start to fall. Specifically, a block of sand disturbed at a cell (i,j) will pass through all cells below and including the cell (i,j) within the column, disturbing all adjacent cells along the way. Here, the cells adjacent to a cell (i,j) are defined as (i-1,j), (i,j-1), (i+1,j), and (i,j+1) (if they are within the grid). Note that the newly falling blocks can disturb other blocks.In one operation you are able to disturb any piece of sand. The puzzle is solved when there are at least a_i blocks of sand counted in the i-th sand counter for each column from 1 to m.You are now tasked with finding the minimum amount of operations in order to solve the puzzle. Note that Little Dormi will never give you a puzzle that is impossible to solve.InputThe first line consists of two space-separated positive integers n and m (1 \leq n \cdot m \leq 400\,000).Each of the next n lines contains m characters, describing each row of the board. If a character on a line is '.', the corresponding cell is empty. If it is '#', the cell contains a block of sand.The final line contains m non-negative integers a_1,a_2,\ldots,a_m (0 \leq a_i \leq n) — the minimum amount of blocks of sand that needs to fall below the board in each column. In this version of the problem, a_i will always be not greater than the number of blocks of sand in column i.OutputPrint one non-negative integer, the minimum amount of operations needed to solve the puzzle.ExamplesInput 5 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1 Output 3 Input 3 3 #.# #.. ##. 3 1 1 Output 1 Input 7 5 .#..# #.... ..##. ..##. ..### ..#.. #.##. 0 0 2 4 2 Output 1 NoteFor example 1, by disturbing both blocks of sand on the first row from the top at the first and sixth columns from the left, and the block of sand on the second row from the top and the fourth column from the left, it is possible to have all the required amounts of sand fall in each column. It can be proved that this is not possible with fewer than 3 operations, and as such the answer is 3. Here is the puzzle from the first example. For example 2, by disturbing the cell on the top row and rightmost column, one can cause all of the blocks of sand in the board to fall into the counters at the bottom. Thus, the answer is 1. Here is the puzzle from the second example. For example 3, by disturbing the cell on the top row and rightmost column, it is possible to have all the required amounts of sand fall in each column. It can be proved that this is not possible with fewer than 1 operation, and as such the answer is 1. Here is the puzzle from the third example.
5 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1
3
2 seconds
512 megabytes
['dfs and similar', 'dp', 'graphs', 'greedy', '*3000']
F1. Falling Sand (Easy Version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference between the versions is the constraints on a_i. You can make hacks only if all versions of the problem are solved.Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board with n rows and m columns of cells, some empty and some filled with blocks of sand, and m non-negative integers a_1,a_2,\ldots,a_m (0 \leq a_i \leq n). In this version of the problem, a_i will be equal to the number of blocks of sand in column i.When a cell filled with a block of sand is disturbed, the block of sand will fall from its cell to the sand counter at the bottom of the column (each column has a sand counter). While a block of sand is falling, other blocks of sand that are adjacent at any point to the falling block of sand will also be disturbed and start to fall. Specifically, a block of sand disturbed at a cell (i,j) will pass through all cells below and including the cell (i,j) within the column, disturbing all adjacent cells along the way. Here, the cells adjacent to a cell (i,j) are defined as (i-1,j), (i,j-1), (i+1,j), and (i,j+1) (if they are within the grid). Note that the newly falling blocks can disturb other blocks.In one operation you are able to disturb any piece of sand. The puzzle is solved when there are at least a_i blocks of sand counted in the i-th sand counter for each column from 1 to m.You are now tasked with finding the minimum amount of operations in order to solve the puzzle. Note that Little Dormi will never give you a puzzle that is impossible to solve.InputThe first line consists of two space-separated positive integers n and m (1 \leq n \cdot m \leq 400\,000).Each of the next n lines contains m characters, describing each row of the board. If a character on a line is '.', the corresponding cell is empty. If it is '#', the cell contains a block of sand.The final line contains m non-negative integers a_1,a_2,\ldots,a_m (0 \leq a_i \leq n) — the minimum amount of blocks of sand that needs to fall below the board in each column. In this version of the problem, a_i will be equal to the number of blocks of sand in column i.OutputPrint one non-negative integer, the minimum amount of operations needed to solve the puzzle.ExamplesInput 5 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1 Output 3 Input 3 3 #.# #.. ##. 3 1 1 Output 1 NoteFor example 1, by disturbing both blocks of sand on the first row from the top at the first and sixth columns from the left, and the block of sand on the second row from the top and the fourth column from the left, it is possible to have all the required amounts of sand fall in each column. It can be proved that this is not possible with fewer than 3 operations, and as such the answer is 3. Here is the puzzle from the first example. For example 2, by disturbing the cell on the top row and rightmost column, one can cause all of the blocks of sand in the board to fall into the counters at the bottom. Thus, the answer is 1. Here is the puzzle from the second example.
5 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1
3
2 seconds
512 megabytes
['dfs and similar', 'graphs', 'greedy', '*2500']
E. Lost Arraytime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Note: the XOR-sum of an array a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) is defined as a_1 \oplus a_2 \oplus \ldots \oplus a_n, where \oplus denotes the bitwise XOR operation.Little Dormi received an array of n integers a_1, a_2, \ldots, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, \ldots, x_k, it will output a_{x_1} \oplus a_{x_2} \oplus \ldots \oplus a_{x_k}.As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, \ldots, a_n by querying the XOR machine.Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.The array a_1, a_2, \ldots, a_n is fixed before you start querying the XOR machine and does not change with the queries.InputThe only line of input contains the integers n and k (1 \le n \le 500, 1 \le k \le n), the length of the lost array and the configured query size of the XOR machine.Elements of the original array satisfy 1 \le a_i \le 10^9.It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d \le 500.After taking n and k, begin interaction.OutputIf it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, \ldots, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, \ldots, a_n, and terminate your program normally immediately after flushing the output stream. Note that answering does not count as a query.InteractionEach query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 \le x \le 2 \cdot 10^9 will always be true.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.HacksTo hack a solution, use the following format.The first line contains the integers n and k (1 \le n \le 500, 1 \le k \le n).The second line contains the the array a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).ExamplesInput 5 3 4 0 1 Output ? 1 2 3 ? 2 3 5 ? 4 1 5 ! 7 Input 3 2 Output -1 NoteIn the first example interaction, the array a_1, a_2, \ldots, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7. The first query made asks for indices 1,2,3, so the response is a_1 \oplus a_2 \oplus a_3 = 2 \oplus 1 \oplus 7 = 4.The second query made asks for indices 2,3,5, so the response is a_2 \oplus a_3 \oplus a_5 = 1 \oplus 7 \oplus 6 = 0.The third query made asks for indices 4,1,5, so the response is a_4 \oplus a_1 \oplus a_5 = 5 \oplus 2 \oplus 6 = 1. Note that the indices may be output in any order.Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
5 3 4 0 1
? 1 2 3 ? 2 3 5 ? 4 1 5 ! 7
1.5 seconds
256 megabytes
['graphs', 'greedy', 'interactive', 'shortest paths', '*2300']
D. Lost Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n.The game master only allows him to ask one type of question: Little Dormi picks a node r (1 \le r \le n), and the game master will reply with an array d_1, d_2, \ldots, d_n, where d_i is the length of the shortest path from node r to i, for all 1 \le i \le n.Additionally, to make the game unfair challenge Little Dormi the game master will allow at most \lceil\frac{n}{2}\rceil questions, where \lceil x \rceil denotes the smallest integer greater than or equal to x.Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy!Note that the game master creates the tree before the game starts, and does not change it during the game.InputThe first line of input contains the integer n (2 \le n \le 2\,000), the number of nodes in the tree.You will then begin interaction.OutputWhen your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 \le a, b \le n). Once you are done, terminate your program normally immediately after flushing the output stream.You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query.InteractionAfter taking input, you may make at most \lceil\frac{n}{2}\rceil queries. Each query is made in the format "? r", where r is an integer 1 \le r \le n that denotes the node you want to pick for that query.You will then receive n space separated integers d_1, d_2, \ldots, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If at any point you make an invalid query or try to make more than \lceil \frac{n}{2} \rceil queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict.HacksTo hack a solution, use the following format.The first line contains the integer n (2 \le n \le 2\,000).The next n−1 lines contain two integers u and v (1 \le u,v \le n) denoting an edge between u and v (u \neq v). These n-1 edges must form a tree.ExamplesInput 4 0 1 2 2 1 0 1 1Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 NoteHere is the tree from the first example. Notice that the edges can be output in any order.Additionally, here are the answers for querying every single node in example 1: 1: [0,1,2,2] 2: [1,0,1,1] 3: [2,1,0,2] 4: [2,1,2,0]Below is the tree from the second example interaction. Lastly, here are the answers for querying every single node in example 2: 1: [0,4,1,3,2] 2: [4,0,3,1,2] 3: [1,3,0,2,1] 4: [3,1,2,0,1] 5: [2,2,1,1,0]
4 0 1 2 2 1 0 1 1
? 1 ? 2 ! 4 2 1 2 2 3
3 seconds
256 megabytes
['constructive algorithms', 'interactive', 'trees', '*1800']
C. Little Alawn's Puzzletime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 \times n grid where each row is a permutation of the numbers 1,2,3,\ldots,n.The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column.Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 4 \cdot 10^5).The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,\ldots,n and the numbers in each column and row will be pairwise distinct.It is guaranteed that the sum of n over all test cases does not exceed 4 \cdot 10^5.OutputFor each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7.The answer for each test case should be on a separate line.ExampleInput 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 NoteThe two possible puzzle configurations for example 1 are: [1,4,2,3] in the first row and [3,2,1,4] in the second; [3,2,1,4] in the first row and [1,4,2,3] in the second.
2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6
2 8
2.5 seconds
256 megabytes
['combinatorics', 'dp', 'dsu', 'graphs', 'math', '*1300']
B. Histogram Uglinesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Dormi received a histogram with n bars of height a_1, a_2, \ldots, a_n for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.To modify the histogram, Little Dormi is able to perform the following operation an arbitrary number of times: Select an index i (1 \le i \le n) where a_i>0, and assign a_i := a_i-1.Little Dormi defines the ugliness score of his histogram (after performing some number of operations) as the sum of the vertical length of its outline and the number of operations he performed on it. And to make the histogram as perfect as possible, he would like to minimize the ugliness score after modifying it with some number of operations.However, as his histogram is very large, Little Dormi is having trouble minimizing the ugliness score, so as Little Dormi's older brother, help him find the minimal ugliness.Consider the following example where the histogram has 4 columns of heights 4,8,9,6: The blue region represents the histogram, and the red lines represent the vertical portion of the outline. Currently, the vertical length of the outline is 4+4+1+3+6 = 18, so if Little Dormi does not modify the histogram at all, the ugliness would be 18.However, Little Dormi can apply the operation once on column 2 and twice on column 3, resulting in a histogram with heights 4,7,7,6: Now, as the total vertical length of the outline (red lines) is 4+3+1+6=14, the ugliness is 14+3=17 dollars. It can be proven that this is optimal.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 4 \cdot 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 4 \cdot 10^5.OutputFor each test case output one integer, the minimal ugliness Little Dormi can achieve with the histogram in that test case.ExampleInput 2 4 4 8 9 6 6 2 1 7 4 0 0 Output 17 12 NoteExample 1 is the example described in the statement.The initial histogram for example 2 is given below: The ugliness is currently 2+1+6+3+4=16.By applying the operation once on column 1, six times on column 3, and three times on column 4, we can end up with a histogram with heights 1,1,1,1,0,0: The vertical length of the outline is now 1+1=2 and Little Dormi made 1+6+3=10 operations, so the final ugliness is 2+10=12, which can be proven to be optimal.
2 4 4 8 9 6 6 2 1 7 4 0 0
17 12
2 seconds
256 megabytes
['greedy', 'implementation', 'math', '*1100']
A. Colour the Flagtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag).You are given an n \times m grid of "R", "W", and "." characters. "R" is red, "W" is white and "." is blank. The neighbours of a cell are those that share an edge with it (those that only share a corner do not count).Your job is to colour the blank cells red or white so that every red cell only has white neighbours (and no red ones) and every white cell only has red neighbours (and no white ones). You are not allowed to recolour already coloured cells.InputThe first line contains t (1 \le t \le 100), the number of test cases.In each test case, the first line will contain n (1 \le n \le 50) and m (1 \le m \le 50), the height and width of the grid respectively.The next n lines will contain the grid. Each character of the grid is either 'R', 'W', or '.'.OutputFor each test case, output "YES" if there is a valid grid or "NO" if there is not.If there is, output the grid on the next n lines. If there are multiple answers, print any.In the output, the "YES"s and "NO"s are case-insensitive, meaning that outputs such as "yEs" and "nO" are valid. However, the grid is case-sensitive.ExampleInput 3 4 6 .R.... ...... ...... .W.... 4 4 .R.W .... .... .... 5 1 R W R W R Output YES WRWRWR RWRWRW WRWRWR RWRWRW NO YES R W R W R NoteThe answer for the first example case is given in the example output, and it can be proven that no grid exists that satisfies the requirements of the second example case. In the third example all cells are initially coloured, and the colouring is valid.
3 4 6 .R.... ...... ...... .W.... 4 4 .R.W .... .... .... 5 1 R W R W R
YES WRWRWR RWRWRW WRWRWR RWRWRW NO YES R W R W R
1.5 seconds
256 megabytes
['brute force', 'implementation', '*800']
J. Pawnstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an infinite chessboard, divided into cells. The cell (x, y) is the cell on the intersection of the x_i-th row and y_i-th column. n black pawns are placed on the board, the i-th black pawn occupies the cell (x_i, y_i).You want to capture all black pawns. In order to do so, you may perform the following actions: place a white pawn into any empty cell (any cell having integer coordinates can be chosen, as long as it doesn't contain any pawns); make a move with one of the white pawns according to the chess rules. Recall that when you make a move with a white pawn in the cell (x, y), the chess rules allow you to choose exactly one of these actions: if there is a black pawn in the cell (x + 1, y - 1), you can capture it — the black pawn is removed from the board, and the white pawn moves to (x + 1, y - 1); if there is a black pawn in the cell (x + 1, y + 1), you can capture it — the black pawn is removed from the board, and the white pawn moves to (x + 1, y + 1); if the cell (x + 1, y) is empty, you can move the white pawn to that cell. You may perform any finite sequence of actions (placing white pawns and moving them). You want to capture all of the black pawns, and it can be shown that it is always possible; and you want to do it placing as few white pawns as possible.What is the minimum number of white pawns you have to place to capture all n black pawns?InputThe first line contains one integer n (1 \le n \le 5 \cdot 10^5) — the number of black pawns.Then n lines follow. The i-th line contains two integers x_i and y_i (1 \le x_i, y_i \le 5 \cdot 10^5) denoting a black pawn in the cell (x_i, y_i). No cell is occupied by two or more black pawns.OutputPrint one integer — the minimum number of white pawns you have to place to capture all n black pawns.ExamplesInput 3 1 1 5 1 2 2 Output 1 Input 3 3 2 1 3 1 1 Output 2 Input 2 1 1 2 2 Output 1
3 1 1 5 1 2 2
1
5 seconds
256 megabytes
['*special problem']
I. Excursionstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIrina works in an excursion company in Saratov. Today, she is going to organize excursions in the cities of Saratov and Engels.There are n_1 sights in Saratov and n_2 sights in Engels. The cities are separated by a river, but there are m bus routes that go along the bridges and allow tourists to go from Saratov to Engels and vice versa. The i-th bus route goes from the x_i-th sight in Saratov to the y_i-th sight in Engels, and in the opposite direction as well.Irina wants to plan excursions for the current day. The excursion trips start in Saratov in the morning, continue in Engels in the afternoon, and finish in Saratov in the evening.Each tourist starts their excursion day at some sight in Saratov, k_i tourists start at the i-th sight. Then the tour guides lead them to Engels: at each sight in Saratov, a tour guide chooses a bus route leading from this sight to Engels, and all the tourists starting from this sight transfer to Engels along this bus route. After the excursions in Engels are finished, the same thing happens: at each sight in Engels, a tour guide chooses a bus route leading from this sight to Saratov, and all the tourists at this sight transfer to Saratov along this bus route.This process can lead to a situation such that some tourists return to the same sight in Saratov where they started in the morning. Obviously, tourists don't like it; so Irina wants to choose where the tour guides take the tourists (both on the way from Saratov to Engels and on the way from Engels to Saratov), so that the minimum possible number of tourists return to the same sight where they started. Help Irina to find an optimal plan!InputThe first line contains three integers n_1, n_2 and m (1 \le n_1, n_2 \le 100; \max(n_1, n_2) \le m \le n_1 \cdot n_2) — the number of sights in Saratov, the number of sights in Engels, and the number of bus routes, respectively.The second line contains n_1 integers k_1, k_2, \dots, k_{n_1} (1 \le k_i \le 10^6), where k_i is the number of tourists starting at the i-th sight in Saratov.Then m lines follow, each describing a bus route: the i-th line contains two integers x_i and y_i (1 \le x_i \le n_1; 1 \le y_i \le n_2) meaning that the i-th bus route connects the x_i-th sight in Saratov and the y_i-th sight in Engels. All these bus routes are distinct, and each sight has at least one bus route leading to/from it.OutputPrint one integer — the minimum possible number of tourists that will return to the same sight where they started.ExamplesInput 2 1 2 10 20 1 1 2 1 Output 10 Input 3 3 6 10 20 30 1 3 3 1 2 3 2 1 3 2 1 2 Output 0
2 1 2 10 20 1 1 2 1
10
2 seconds
512 megabytes
['*special problem', 'constructive algorithms', 'dfs and similar', 'flows', 'graph matchings', 'graphs']