question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
You are given a tree with each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white and a black vertex at once.What is the minimum number of removals necessary to remove all vertices from the tree? | Input: ['4', '2', '1 1', '1 2', '4', '1 2 1 2', '1 2', '2 3', '3 4', '5', '1 1 0 1 2', '1 2', '2 3', '3 4', '3 5', '8', '1 2 1 2 2 2 1 2', '1 3', '2 3', '3 4', '4 5', '5 6', '5 7', '5 8', ''] Output:['1', '3', '2', '3', ''] | [
2,
4
] |
You are given n non-decreasing arrays of non-negative numbers. Vasya repeats the following operation k times: Selects a non-empty array. Puts the first element of the selected array in his pocket. Removes the first element from the selected array. Vasya wants to maximize the sum of the elements in his pocket. | Input: ['3 3', '2 5 10', '3 1 2 3', '2 1 20', ''] Output:['26', ''] | [
2
] |
You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1.The following actions are allowed: Token movement. To move the token from vertex u to vertex v if there is an edge u \to v in the graph. This action takes 1 second. Graph transposition. To transpose all the edges in the graph: replace each edge u \to v by an edge v \to u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998\,244\,353. | Input: ['4 4', '1 2', '2 3', '3 4', '4 1', ''] Output:['2', ''] | [
2
] |
We start with a permutation a_1, a_2, ..., a_n and with an empty array b. We apply the following operation k times.On the i-th iteration, we select an index t_i (1 <= t_i <= n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, ..., a_n to the left in order to fill in the empty space.You are given the initial permutation a_1, a_2, ..., a_n and the resulting array b_1, b_2, ..., b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, ..., t_k modulo 998\,244\,353. | Input: ['3', '5 3', '1 2 3 4 5', '3 2 5', '4 3', '4 3 2 1', '4 3 1', '7 4', '1 4 7 3 6 2 5', '3 2 4 5', ''] Output:['2', '0', '4', ''] | [
2
] |
You are given an array a of n positive integers.You can use the following operation as many times as you like: select any integer 1 <= k <= n and do one of two things: decrement by one k of the first elements of the array. decrement by one k of the last elements of the array. For example, if n=5 and a=[3,2,2,1,4], then you can apply one of the following operations to it (not all possible options are listed below): decrement from the first two elements of the array. After this operation a=[2, 1, 2, 1, 4]; decrement from the last three elements of the array. After this operation a=[3, 2, 1, 0, 3]; decrement from the first five elements of the array. After this operation a=[2, 1, 1, 0, 3]; Determine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations. | Input: ['4', '3', '1 2 1', '5', '11 7 9 6 8', '5', '1 3 1 3 1', '4', '5 2 1 10', ''] Output:['YES', 'YES', 'NO', 'YES', ''] | [
2
] |
A median of an array of integers of length n is the number standing on the \lceil {\frac{n}{2}} \rceil (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with 1. For example, a median of the array [2, 6, 4, 1, 3, 5] is equal to 3. There exist some other definitions of the median, but in this problem, we will use the described one.Given two integers n and k and non-decreasing array of nk integers. Divide all numbers into k arrays of size n, such that each number belongs to exactly one array.You want the sum of medians of all k arrays to be the maximum possible. Find this maximum possible sum. | Input: ['6', '2 4', '0 24 34 58 62 64 69 78', '2 2', '27 61 81 91', '4 3', '2 4 16 18 21 27 36 53 82 91 92 95', '3 4', '3 11 12 22 33 35 38 67 69 71 94 99', '2 1', '11 41', '3 3', '1 1 1 1 1 1 1 1 1', ''] Output:['165', '108', '145', '234', '11', '3', ''] | [
2,
3
] |
You are given four integers n, c_0, c_1 and h and a binary string s of length n.A binary string is a string consisting of characters 0 and 1.You can change any character of the string s (the string should be still binary after the change). You should pay h coins for each change.After some changes (possibly zero) you want to buy the string. To buy the string you should buy all its characters. To buy the character 0 you should pay c_0 coins, to buy the character 1 you should pay c_1 coins.Find the minimum number of coins needed to buy the string. | Input: ['6', '3 1 1 1', '100', '5 10 100 1', '01010', '5 10 1 1', '11111', '5 1 10 1', '11111', '12 2 1 10', '101110110101', '2 100 1 10', '00', ''] Output:['3', '52', '5', '10', '16', '22', ''] | [
3
] |
You are given an array a_1, a_2, ..., a_n of integers. This array is non-increasing.Let's consider a line with n shops. The shops are numbered with integers from 1 to n from left to right. The cost of a meal in the i-th shop is equal to a_i.You should process q queries of two types: 1 x y: for each shop 1 <=q i <=q x set a_{i} = max(a_{i}, y). 2 x y: let's consider a hungry man with y money. He visits the shops from x-th shop to n-th and if he can buy a meal in the current shop he buys one item of it. Find how many meals he will purchase. The man can buy a meal in the shop i if he has at least a_i money, and after it his money decreases by a_i. | Input: ['10 6', '10 10 10 6 6 5 5 5 3 1', '2 3 50', '2 4 10', '1 3 10', '2 2 36', '1 4 7', '2 2 17', ''] Output:['8', '3', '6', '2', ''] | [
2,
4
] |
This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.You are given a binary table of size n * m. This table consists of symbols 0 and 1.You can make such operation: select 3 different cells that belong to one 2 * 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).Your task is to make all symbols in the table equal to 0. You are allowed to make at most nm operations. You don't need to minimize the number of operations.It can be proved, that it is always possible. | Input: ['5', '2 2', '10', '11', '3 3', '011', '101', '110', '4 4', '1111', '0110', '0110', '1111', '5 5', '01011', '11001', '00010', '11011', '10000', '2 3', '011', '101', ''] Output:['1', '1 1 2 1 2 2', '2 ', '2 1 3 1 3 2', '1 2 1 3 2 3', '4', '1 1 1 2 2 2 ', '1 3 1 4 2 3', '3 2 4 1 4 2', '3 3 4 3 4 4', '4', '1 2 2 1 2 2 ', '1 4 1 5 2 5 ', '4 1 4 2 5 1', '4 4 4 5 3 4', '2', '1 3 2 2 2 3', '1 2 2 1 2 2', ''] | [
2
] |
Yurii is sure he can do everything. Can he solve this task, though?He has an array a consisting of n positive integers. Let's call a subarray a[l...r] good if the following conditions are simultaneously satisfied: l+1 <=q r-1, i. e. the subarray has length at least 3; (a_l \oplus a_r) = (a_{l+1}+a_{l+2}+...+a_{r-2}+a_{r-1}), where \oplus denotes the bitwise XOR operation. In other words, a subarray is good if the bitwise XOR of the two border elements is equal to the sum of the rest of the elements. Yurii wants to calculate the total number of good subarrays. What is it equal to?An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. | Input: ['8', '3 1 2 3 1 2 3 15', ''] Output:['6'] | [
0,
4
] |
Ksenia has an array a consisting of n positive integers a_1, a_2, ..., a_n. In one operation she can do the following: choose three distinct indices i, j, k, and then change all of a_i, a_j, a_k to a_i \oplus a_j \oplus a_k simultaneously, where \oplus denotes the bitwise XOR operation. She wants to make all a_i equal in at most n operations, or to determine that it is impossible to do so. She wouldn't ask for your help, but please, help her! | Input: ['5', '4 2 1 7 2', ''] Output:['YES', '1', '1 3 4'] | [
3
] |
You're given an array b of length n. Let's define another array a, also of length n, for which a_i = 2^{b_i} (1 <=q i <=q n). Valerii says that every two non-intersecting subarrays of a have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers l_1,r_1,l_2,r_2 that satisfy the following conditions: 1 <=q l_1 <=q r_1 \lt l_2 <=q r_2 <=q n; a_{l_1}+a_{l_1+1}+...+a_{r_1-1}+a_{r_1} = a_{l_2}+a_{l_2+1}+...+a_{r_2-1}+a_{r_2}. If such four integers exist, you will prove Valerii wrong. Do they exist?An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. | Input: ['2', '6', '4 3 0 1 2 0', '2', '2 5', ''] Output:['YES', 'NO', ''] | [
2
] |
n fishermen have just returned from a fishing vacation. The i-th fisherman has caught a fish of weight a_i.Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of showing fish is a permutation of integers from 1 to n). Then they show the fish they caught according to the chosen order. When a fisherman shows his fish, he might either become happy, become sad, or stay content.Suppose a fisherman shows a fish of weight x, and the maximum weight of a previously shown fish is y (y = 0 if that fisherman is the first to show his fish). Then: if x >= 2y, the fisherman becomes happy; if 2x <= y, the fisherman becomes sad; if none of these two conditions is met, the fisherman stays content. Let's call an order in which the fishermen show their fish emotional if, after all fishermen show their fish according to this order, each fisherman becomes either happy or sad. Calculate the number of emotional orders modulo 998244353. | Input: ['4', '1 1 4 9', ''] Output:['20', ''] | [
3
] |
You are given an array of n integers a_1, a_2, ..., a_n, and a set b of k distinct integers from 1 to n.In one operation, you may choose two integers i and x (1 <= i <= n, x can be any integer) and assign a_i := x. This operation can be done only if i does not belong to the set b.Calculate the minimum number of operations you should perform so the array a is increasing (that is, a_1 < a_2 < a_3 < ... < a_n), or report that it is impossible. | Input: ['7 2', '1 2 1 1 3 5 1', '3 5', ''] Output:['4', ''] | [
4
] |
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processedq = Queue()q.put(1) # place the root at the end of the queuewhile not q.empty(): k = q.pop() # retrieve the first vertex from the queue a.append(k) # append k to the end of the sequence in which vertices were visited for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order q.put(y)Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1.Help Monocarp to find any tree with given visiting order a and minimum height. | Input: ['3', '4', '1 4 3 2', '2', '1 2', '3', '1 2 3', ''] Output:['3', '1', '1', ''] | [
2
] |
Chef Monocarp has just put n dishes into an oven. He knows that the i-th dish has its optimal cooking time equal to t_i minutes.At any positive integer minute T Monocarp can put no more than one dish out of the oven. If the i-th dish is put out at some minute T, then its unpleasant value is |T - t_i| — the absolute difference between T and t_i. Once the dish is out of the oven, it can't go back in.Monocarp should put all the dishes out of the oven. What is the minimum total unpleasant value Monocarp can obtain? | Input: ['6', '6', '4 2 4 4 5 2', '7', '7 7 7 7 7 7 7', '1', '1', '5', '5 1 2 4 3', '4', '1 4 4 4', '21', '21 8 1 4 1 5 21 1 8 21 11 21 11 3 12 8 19 15 9 11 13', ''] Output:['4', '12', '0', '0', '2', '21', ''] | [
2,
3
] |
You are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's.String s has exactly \frac{n}{2} zeroes and \frac{n}{2} ones (n is even).In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string.What is the minimum number of operations you need to make string s alternating? A string is alternating if s_i \neq s_{i + 1} for all i. There are two types of alternating strings in general: 01010101... or 10101010... | Input: ['3', '2', '10', '4', '0110', '8', '11101000', ''] Output:['0', '1', '2', ''] | [
2
] |
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy strategy: he buys <=ft\lfloor \frac{x}{a} \right\rfloor packs with a discount; then he wants to buy the remaining (x \bmod a) cans one by one. <=ft\lfloor \frac{x}{a} \right\rfloor is x divided by a rounded down, x \bmod a is the remainer of x divided by a.But customers are greedy in general, so if the customer wants to buy (x \bmod a) cans one by one and it happens that (x \bmod a) >= \frac{a}{2} he decides to buy the whole pack of a cans (instead of buying (x \bmod a) cans). It makes you, as a marketer, happy since the customer bought more than he wanted initially.You know that each of the customers that come to your shop can buy any number of cans from l to r inclusive. Can you choose such size of pack a that each customer buys more cans than they wanted initially? | Input: ['3', '3 4', '1 2', '120 150', ''] Output:['YES', 'NO', 'YES', ''] | [
0,
2,
3
] |
You are given a multiset S. Over all pairs of subsets A and B, such that: B \subset A; |B| = |A| - 1; greatest common divisor of all elements in A is equal to one; find the sum of \sum_{x \in A}{x} \cdot \sum_{x \in B}{x}, modulo 998\,244\,353. | Input: ['2', '1 1', '2 1', ''] Output:['9', ''] | [
3
] |
In this problem MEX of a certain array is the smallest positive integer not contained in this array.Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today.You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers.An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself.Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! | Input: ['3', '1 3 2', ''] Output:['3', ''] | [
4
] |
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of n squares connected by n-1 roads in such a way that it is possible to reach any square from any other square. The square number 1 is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were a_i citizens on the i-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught? | Input: ['3', '1 1', '3 1 2', ''] Output:['3', ''] | [
2,
4
] |
Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down).Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x!Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order.Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. | Input: ['4 1 2', ''] Output:['6', ''] | [
4
] |
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size n * n is called prime if the following three conditions are held simultaneously: all numbers on the square are non-negative integers not exceeding 10^5; there are no prime numbers in the square; sums of integers in each row and each column are prime numbers. Sasha has an integer n. He asks you to find any prime square of size n * n. Sasha is absolutely sure such squares exist, so just help him! | Input: ['2', '4', '2', ''] Output:['4 6 8 1', '4 9 9 9', '4 10 10 65', '1 4 4 4', '1 1', '1 1', ''] | [
3
] |
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that \sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, \frac{5}{2}=2.5. | Input: ['2', '3 8', '2 5 1', '4 4', '0 1 2 3', ''] Output:['YES', 'NO', ''] | [
3
] |
You are a mayor of Berlyatov. There are n districts and m two-way roads between them. The i-th road connects districts x_i and y_i. The cost of travelling along this road is w_i. There is some path between each pair of districts, so the city is connected.There are k delivery routes in Berlyatov. The i-th route is going from the district a_i to the district b_i. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district a_i to the district b_i to deliver products.The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with 0).Let d(x, y) be the cheapest cost of travel between districts x and y.Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with 0. In other words, you have to find the minimum possible value of \sum\limits_{i = 1}^{k} d(a_i, b_i) after applying the operation described above optimally. | Input: ['6 5 2', '1 2 5', '2 3 7', '2 4 4', '4 5 2', '4 6 8', '1 6', '5 3', ''] Output:['22', ''] | [
0
] |
One day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly \frac{n}{2} people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly \frac{n}{2} people. Each person should belong to exactly one of these two round dances.Round dance is a dance circle consisting of 1 or more people. Two round dances are indistinguishable (equal) if one can be transformed to another by choosing the first participant. For example, round dances [1, 3, 4, 2], [4, 2, 1, 3] and [2, 1, 3, 4] are indistinguishable.For example, if n=2 then the number of ways is 1: one round dance consists of the first person and the second one of the second person.For example, if n=4 then the number of ways is 3. Possible options: one round dance — [1,2], another — [3,4]; one round dance — [2,4], another — [3,1]; one round dance — [4,1], another — [3,2]. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly \frac{n}{2} people. | Input: ['2'] Output:['1'] | [
3
] |
There are n piranhas with sizes a_1, a_2, ..., a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the dominant piranha will eat them.Because the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely: The piranha i can eat the piranha i-1 if the piranha i-1 exists and a_{i - 1} < a_i. The piranha i can eat the piranha i+1 if the piranha i+1 exists and a_{i + 1} < a_i. When the piranha i eats some piranha, its size increases by one (a_i becomes a_i + 1).Your task is to find any dominant piranha in the aquarium or determine if there are no such piranhas.Note that you have to find any (exactly one) dominant piranha, you don't have to find all of them.For example, if a = [5, 3, 4, 4, 5], then the third piranha can be dominant. Consider the sequence of its moves: The piranha eats the second piranha and a becomes [5, \underline{5}, 4, 5] (the underlined piranha is our candidate). The piranha eats the third piranha and a becomes [5, \underline{6}, 5]. The piranha eats the first piranha and a becomes [\underline{7}, 5]. The piranha eats the second piranha and a becomes [\underline{8}]. You have to answer t independent test cases. | Input: ['6', '5', '5 3 4 4 5', '3', '1 1 1', '5', '4 4 3 4 4', '5', '5 5 4 3 2', '3', '1 1 2', '5', '5 4 3 5 5', ''] Output:['3', '-1', '4', '3', '3', '1', ''] | [
2
] |
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r the condition a_i = 1 holds) and: Shift it to the right by 1: move the book at index i to i + 1 for all l <= i <= r. This move can be done only if r+1 <= n and there is no book at the position r+1. Shift it to the left by 1: move the book at index i to i-1 for all l <= i <= r. This move can be done only if l-1 >= 1 and there is no book at the position l-1. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for a = [0, 0, 1, 0, 1] there is a gap between books (a_4 = 0 when a_3 = 1 and a_5 = 1), for a = [1, 1, 0] there are no gaps between books and for a = [0, 0,0] there are also no gaps between books.You have to answer t independent test cases. | Input: ['5', '7', '0 0 1 0 1 0 1', '3', '1 0 0', '5', '1 1 0 0 1', '6', '1 0 0 0 0 1', '5', '1 1 0 1 1', ''] Output:['2', '0', '2', '4', '1', ''] | [
2
] |
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone answers the call, in the following order: First he calls all apartments consisting of digit 1, in increasing order (1, 11, 111, 1111). Next he calls all apartments consisting of digit 2, in increasing order (2, 22, 222, 2222) And so on. The resident of the boring apartment x answers the call, and our character stops calling anyone further.Our character wants to know how many digits he pressed in total and your task is to help him to count the total number of keypresses.For example, if the resident of boring apartment 22 answered, then our character called apartments with numbers 1, 11, 111, 1111, 2, 22 and the total number of digits he pressed is 1 + 2 + 3 + 4 + 1 + 2 = 13.You have to answer t independent test cases. | Input: ['4', '22', '9999', '1', '777', ''] Output:['13', '90', '1', '66', ''] | [
3
] |
Marina plays a new rogue-like game. In this game, there are n different character species and m different classes. The game is played in runs; for each run, Marina has to select a species and a class for her character. If she selects the i-th species and the j-th class, she will get c_{i, j} points for this run.Initially, some species and classes are unlocked, all others are locked. To unlock the i-th species, Marina has to get at least a_i points in total for previous runs — that is, as soon as her total score for played runs is at least a_i, this species is unlocked. Similarly, to unlock the j-th class, she has to get at least b_j points in total for previous runs. If a_i = 0 for some i, then this species is unlocked initially (the same applies to classes with b_j = 0).Marina wants to unlock all species and classes in the minimum number of runs. Before playing the game, she can read exactly one guide on some combination of species and class, and reading a guide will increase the score she gets for all runs with that combination by k (formally, before playing the game, she can increase exactly one value of c_{i, j} by k).What is the minimum number of runs she has to play to unlock all species and classes if she chooses the combination to read a guide on optimally? | Input: ['3 4 2', '0 5 7', '0 2 6 10', '2 5 5 2', '5 3 4 4', '3 4 2 4', ''] Output:['3', ''] | [
0,
2
] |
Alice and Bob play a game. They have a set that initially consists of n integers. The game is played in k turns. During each turn, the following events happen: firstly, Alice chooses an integer from the set. She can choose any integer except for the maximum one. Let the integer chosen by Alice be a; secondly, Bob chooses an integer from the set. He can choose any integer that is greater than a. Let the integer chosen by Bob be b; finally, both a and b are erased from the set, and the value of b - a is added to the score of the game. Initially, the score is 0. Alice wants to maximize the resulting score, Bob wants to minimize it. Assuming that both Alice and Bob play optimally, calculate the resulting score of the game. | Input: ['5 2', '3 4 1 5 2', ''] Output:['4', ''] | [
2
] |
You want to train a neural network model for your graduation work. There are n images in the dataset, the i-th image's size is a_i bytes.You don't have any powerful remote servers to train this model so you have to do it on your local machine. But there is a problem: the total size of the dataset is too big for your machine, so you decided to remove some images — though you don't want to make the dataset too weak so you can remove no more than k images from it. Note that you can only remove images, you can't change their order.You want to remove these images optimally so you came up with a metric (you're a data scientist after all) that allows to measure the result of removals. Consider the array b_1, b_2, ..., b_m after removing at most k images (n - k <= m <= n). The data from this array will be uploaded to the machine in blocks of x consecutive elements each. More precisely: elements with indices from 1 to x (b_1, b_2, ..., b_x) belong to the first block; elements with indices from x + 1 to 2x (b_{x + 1}, b_{x + 2}, ..., b_{2x}) belong to the second block; elements with indices from 2x + 1 to 3x (b_{2x + 1}, b_{2x + 2}, ..., b_{3x}) belong to the third block; and so on. There will be cnt = <=ft\lceil\frac{m}{x}\right\rceil blocks in total. Note that if m is not divisible by x then the last block contains less than x elements, and it's okay.Let w(i) be the total size of the i-th block — that is, the sum of sizes of images inside this block. For example, the size of the first block w(1) is b_1 + b_2 + ... + b_x, the size of the second block w(2) is b_{x + 1} + b_{x + 2} + ... + b_{2x}.The value of the metric you came up with is the maximum block size over the blocks of the resulting dataset. In other words, the value of the metric is \max\limits_{i=1}^{cnt} w(i).You don't want to overload your machine too much, so you have to remove at most k images in a way that minimizes the value of the metric described above. | Input: ['5 5 4', '1 1 5 4 5', ''] Output:['0', ''] | [
2,
4
] |
Your University has a large auditorium and today you are on duty there. There will be n lectures today — all from different lecturers, and your current task is to choose in which order ord they will happen.Each lecturer will use one marker to write something on a board during their lecture. Unfortunately, markers become worse the more you use them and lecturers may decline using markers which became too bad in their opinion.Formally, the i-th lecturer has their acceptance value a_i which means they will not use the marker that was used at least in a_i lectures already and will ask for a replacement. More specifically: before the first lecture you place a new marker in the auditorium; before the ord_j-th lecturer (in the order you've chosen) starts, they check the quality of the marker and if it was used in at least a_{ord_j} lectures before, they will ask you for a new marker; if you were asked for a new marker, then you throw away the old one, place a new one in the auditorium, and the lecturer gives a lecture. You know: the better the marker — the easier for an audience to understand what a lecturer has written, so you want to maximize the number of used markers. Unfortunately, the higher-ups watch closely how many markers were spent, so you can't just replace markers before each lecture. So, you have to replace markers only when you are asked by a lecturer. The marker is considered used if at least one lecturer used it for their lecture.You can choose the order ord in which lecturers will give lectures. Find such order that leads to the maximum possible number of the used markers. | Input: ['4', '4', '1 2 1 2', '2', '2 1', '3', '1 1 1', '4', '2 3 1 3', ''] Output:['4 1 3 2', '1 2', '3 1 2', '4 3 2 1', ''] | [
2
] |
You are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i.Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} - a_{y_i}. You must select the numbers so that: all b_i are positive; the value of the expression \sum \limits_{i = 1}^{m} w_i b_i is the lowest possible. It can be shown that for any directed acyclic graph with non-negative w_i, such a way to choose numbers exists. | Input: ['3 2', '2 1 4', '1 3 2', ''] Output:['1 2 0', ''] | [
3
] |
Recently you've discovered a new shooter. They say it has realistic game mechanics.Your character has a gun with magazine size equal to k and should exterminate n waves of monsters. The i-th wave consists of a_i monsters and happens from the l_i-th moment of time up to the r_i-th moments of time. All a_i monsters spawn at moment l_i and you have to exterminate all of them before the moment r_i ends (you can kill monsters right at moment r_i). For every two consecutive waves, the second wave starts not earlier than the first wave ends (though the second wave can start at the same moment when the first wave ends) — formally, the condition r_i <= l_{i + 1} holds. Take a look at the notes for the examples to understand the process better.You are confident in yours and your character's skills so you can assume that aiming and shooting are instant and you need exactly one bullet to kill one monster. But reloading takes exactly 1 unit of time.One of the realistic mechanics is a mechanic of reloading: when you reload you throw away the old magazine with all remaining bullets in it. That's why constant reloads may cost you excessive amounts of spent bullets.You've taken a liking to this mechanic so now you are wondering: what is the minimum possible number of bullets you need to spend (both used and thrown) to exterminate all waves.Note that you don't throw the remaining bullets away after eradicating all monsters, and you start with a full magazine. | Input: ['2 3', '2 3 6', '3 4 3', ''] Output:['9', ''] | [
2
] |
You are given a string s. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the string "aeddba". To accomplish your goal, you can swap the neighboring elements of the string. Your task is to calculate the minimum number of swaps you have to perform to reverse the given string. | Input: ['5', 'aaaza', ''] Output:['2', ''] | [
2
] |
You have a string s consisting of n characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer i from 1 to the length of the string s, then delete the character s_i (the string length gets reduced by 1, the indices of characters to the right of the deleted one also get reduced by 1); if the string s is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string s = 111010, the first operation can be one of the following: select i = 1: we'll get 111010 \rightarrow 11010 \rightarrow 010; select i = 2: we'll get 111010 \rightarrow 11010 \rightarrow 010; select i = 3: we'll get 111010 \rightarrow 11010 \rightarrow 010; select i = 4: we'll get 111010 \rightarrow 11110 \rightarrow 0; select i = 5: we'll get 111010 \rightarrow 11100 \rightarrow 00; select i = 6: we'll get 111010 \rightarrow 11101 \rightarrow 01. You finish performing operations when the string s becomes empty. What is the maximum number of operations you can perform? | Input: ['5', '6', '111010', '1', '0', '1', '1', '2', '11', '6', '101010', ''] Output:['3', '1', '1', '1', '3', ''] | [
2,
4
] |
Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer \frac{a + b}{2} rounded up instead.You should perform the given operation n - 1 times and make the resulting number that will be left on the board as small as possible. For example, if n = 4, the following course of action is optimal: choose a = 4 and b = 2, so the new number is 3, and the whiteboard contains [1, 3, 3]; choose a = 3 and b = 3, so the new number is 3, and the whiteboard contains [1, 3]; choose a = 1 and b = 3, so the new number is 2, and the whiteboard contains [2]. It's easy to see that after n - 1 operations, there will be left only one number. Your goal is to minimize it. | Input: ['1', '4', ''] Output:['2', '2 4', '3 3', '3 1', ''] | [
2,
3
] |
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.Some examples: if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0. | Input: ['2', '4 1', '5 5 5 5', '3 2', '0 0 0', ''] Output:['10', '0', ''] | [
2
] |
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.Monocarp went around the building and counted n windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has n windows. If there are multiple answers, you can print any of them.Here are some examples: if Monocarp has counted 30 windows, there could have been 2 three-room apartments, 2 five-room apartments and 2 seven-room apartments, since 2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30; if Monocarp has counted 67 windows, there could have been 7 three-room apartments, 5 five-room apartments and 3 seven-room apartments, since 7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67; if Monocarp has counted 4 windows, he should have mistaken since no building with the aforementioned layout can have 4 windows. | Input: ['4', '30', '67', '4', '14', ''] Output:['2 2 2', '7 5 3', '-1', '0 0 2', ''] | [
0,
3
] |
This is an interactive problem.To prevent the mischievous rabbits from freely roaming around the zoo, Zookeeper has set up a special lock for the rabbit enclosure. This lock is called the Rotary Laser Lock. The lock consists of n concentric rings numbered from 0 to n-1. The innermost ring is ring 0 and the outermost ring is ring n-1. All rings are split equally into nm sections each. Each of those rings contains a single metal arc that covers exactly m contiguous sections. At the center of the ring is a core and surrounding the entire lock are nm receivers aligned to the nm sections. The core has nm lasers that shine outward from the center, one for each section. The lasers can be blocked by any of the arcs. A display on the outside of the lock shows how many lasers hit the outer receivers. In the example above, there are n=3 rings, each covering m=4 sections. The arcs are colored in green (ring 0), purple (ring 1), and blue (ring 2) while the lasers beams are shown in red. There are nm=12 sections and 3 of the lasers are not blocked by any arc, thus the display will show 3 in this case. Wabbit is trying to open the lock to free the rabbits, but the lock is completely opaque, and he cannot see where any of the arcs are. Given the relative positions of the arcs, Wabbit can open the lock on his own. To be precise, Wabbit needs n-1 integers p_1,p_2,...,p_{n-1} satisfying 0 <=q p_i < nm such that for each i (1 <=q i < n), Wabbit can rotate ring 0 clockwise exactly p_i times such that the sections that ring 0 covers perfectly aligns with the sections that ring i covers. In the example above, the relative positions are p_1 = 1 and p_2 = 7. To operate the lock, he can pick any of the n rings and rotate them by 1 section either clockwise or anti-clockwise. You will see the number on the display after every rotation.Because his paws are small, Wabbit has asked you to help him to find the relative positions of the arcs after all of your rotations are completed. You may perform up to 15000 rotations before Wabbit gets impatient. | Input: ['3 4', '', '4', '', '4', '', '3', ''] Output:['', '? 0 1', '', '? 2 -1', '', '? 1 1', '', '! 1 5'] | [
4
] |
This is the hard version of the problem. The only difference is in the constraint on q. You can make hacks only if all versions of the problem are solved.Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i.Strangely, sheep have superstitions about digits and believe that the digits 3, 6, and 9 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319 has fortune F_{2} + 3F_{0}. Each sheep wants to maximize the sum of fortune among all its k written integers. Can you help them? | Input: ['3', '1 2 3 4 5 6', '2', '57', '63', ''] Output:['11', '8', ''] | [
2
] |
This is the easy version of the problem. The only difference is that in this version q=1. You can make hacks only if all versions of the problem are solved.Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i.Strangely, sheep have superstitions about digits and believe that the digits 3, 6, and 9 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319 has fortune F_{2} + 3F_{0}. Each sheep wants to maximize the sum of fortune among all its k written integers. Can you help them? | Input: ['3', '1 2 3 4 5 6', '1', '57', ''] Output:['11'] | [
2
] |
Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string s_1s_2... s_n of length n. 1 represents an apple and 0 represents an orange.Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguous sequence of apples. Let f(l,r) be the longest contiguous sequence of apples in the substring s_{l}s_{l+1}... s_{r}. Help Zookeeper find \sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r), or the sum of f across all substrings. | Input: ['4', '0110', ''] Output:['12', ''] | [
4
] |
There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, ..., a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers.Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2.Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. | Input: ['3 6', '5 3 1', ''] Output:['15', ''] | [
2,
3,
4
] |
To improve the boomerang throwing skills of the animals, Zookeeper has set up an n * n grid with some targets, where each row and each column has at most 2 targets each. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to n from left to right. For each column, Zookeeper will throw a boomerang from the bottom of the column (below the grid) upwards. When the boomerang hits any target, it will bounce off, make a 90 degree turn to the right and fly off in a straight line in its new direction. The boomerang can hit multiple targets and does not stop until it leaves the grid. In the above example, n=6 and the black crosses are the targets. The boomerang in column 1 (blue arrows) bounces 2 times while the boomerang in column 3 (red arrows) bounces 3 times. The boomerang in column i hits exactly a_i targets before flying out of the grid. It is known that a_i <=q 3.However, Zookeeper has lost the original positions of the targets. Thus, he asks you to construct a valid configuration of targets that matches the number of hits for each column, or tell him that no such configuration exists. If multiple valid configurations exist, you may print any of them. | Input: ['6', '2 0 3 0 1 1', ''] Output:['5', '2 1', '2 5', '3 3', '3 6', '5 6', ''] | [
2
] |
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.For example, Zookeeper can use two such operations: AABABBA \to AABBA \to AAA.Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? | Input: ['3', 'AAA', 'BABA', 'AABBBABBBB', ''] Output:['3', '2', '0', ''] | [
0,
2
] |
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2).He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by 1 unit. For example, if the box is at the point (1,2) and Wabbit is standing at the point (2,2), he can pull the box right by 1 unit, with the box ending up at the point (2,2) and Wabbit ending at the point (3,2).Also, Wabbit can move 1 unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly 1 unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes 1 second to travel 1 unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from (x_1,y_1) to (x_2,y_2). Note that the point where Wabbit ends up at does not matter. | Input: ['2', '1 2 2 2', '1 1 2 2', ''] Output:['1', '4', ''] | [
3
] |
A prisoner wants to escape from a prison. The prison is represented by the interior of the convex polygon with vertices P_1, P_2, P_3, ..., P_{n+1}, P_{n+2}, P_{n+3}. It holds P_1=(0,0), P_{n+1}=(0, h), P_{n+2}=(-10^{18}, h) and P_{n+3}=(-10^{18}, 0). The prison walls P_{n+1}P_{n+2}, P_{n+2}P_{n+3} and P_{n+3}P_1 are very high and the prisoner is not able to climb them. Hence his only chance is to reach a point on one of the walls P_1P_2, P_2P_3,..., P_{n}P_{n+1} and escape from there. On the perimeter of the prison, there are two guards. The prisoner moves at speed 1 while the guards move, remaining always on the perimeter of the prison, with speed v.If the prisoner reaches a point of the perimeter where there is a guard, the guard kills the prisoner. If the prisoner reaches a point of the part of the perimeter he is able to climb and there is no guard there, he escapes immediately. Initially the prisoner is at the point (-10^{17}, h/2) and the guards are at P_1. Find the minimum speed v such that the guards can guarantee that the prisoner will not escape (assuming that both the prisoner and the guards move optimally).Notes: At any moment, the guards and the prisoner can see each other. The "climbing part" of the escape takes no time. You may assume that both the prisoner and the guards can change direction and velocity instantly and that they both have perfect reflexes (so they can react instantly to whatever the other one is doing). The two guards can plan ahead how to react to the prisoner movements. | Input: ['2', '0 0', '223 464', '0 749', ''] Output:['1', ''] | [
4,
4
] |
When they are bored, Federico and Giada often play the following card game with a deck containing 6n cards.Each card contains one number between 1 and 6n and each number appears on exactly one card. Initially the deck is sorted, so the first card contains the number 1, the second card contains the number 2, ..., and the last one contains the number 6n.Federico and Giada take turns, alternating; Federico starts.In his turn, the player takes 3 contiguous cards from the deck and puts them in his pocket. The order of the cards remaining in the deck is not changed. They play until the deck is empty (after exactly 2n turns). At the end of the game both Federico and Giada have 3n cards in their pockets.You are given the cards in Federico's pocket at the end of the game. Describe a sequence of moves that produces that set of cards in Federico's pocket. | Input: ['2', '2 3 4 9 10 11', ''] Output:['9 10 11', '6 7 8', '2 3 4', '1 5 12', ''] | [
2
] |
You have a blackboard and initially only an odd number x is written on it. Your goal is to write the number 1 on the blackboard.You may write new numbers on the blackboard with the following two operations. You may take two numbers (not necessarily distinct) already on the blackboard and write their sum on the blackboard. The two numbers you have chosen remain on the blackboard. You may take two numbers (not necessarily distinct) already on the blackboard and write their bitwise XOR on the blackboard. The two numbers you have chosen remain on the blackboard. Perform a sequence of operations such that at the end the number 1 is on the blackboard. | Input: ['3', ''] Output:['5', '3 + 3', '3 ^ 6', '3 + 5', '3 + 6', '8 ^ 9', ''] | [
3
] |
You like playing chess tournaments online.In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 point. If you win the very first game of the tournament you get 1 point (since there is not a "previous game").The outcomes of the n games are represented by a string s of length n: the i-th character of s is W if you have won the i-th game, while it is L if you have lost the i-th game.After the tournament, you notice a bug on the website that allows you to change the outcome of at most k of your games (meaning that at most k times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.Compute the maximum score you can get by cheating in the optimal way. | Input: ['8', '5 2', 'WLWLL', '6 5', 'LLLWWL', '7 1', 'LWLWLWL', '15 5', 'WWWLLLWWWLLLWWW', '40 7', 'LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL', '1 0', 'L', '1 1', 'L', '6 1', 'WLLWLW', ''] Output:['7', '11', '6', '26', '46', '0', '1', '6', ''] | [
2
] |
You are given an array of n integers a_1,a_2,...,a_n.You have to create an array of n integers b_1,b_2,...,b_n such that: The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \{a_1,a_2,...,a_n\} and \{b_1,b_2,...,b_n\} are equal.For example, if a=[1,-1,0,1], then b=[-1,1,1,0] and b=[0,1,-1,1] are rearrangements of a, but b=[1,-1,-1,0] and b=[1,0,2,-3] are not rearrangements of a. For all k=1,2,...,n the sum of the first k elements of b is nonzero. Formally, for all k=1,2,...,n, it must hold b_1+b_2+\cdots+b_k\not=0\,. If an array b_1,b_2,..., b_n with the required properties does not exist, you have to print NO. | Input: ['4', '4', '1 -2 3 -4', '3', '0 0 0', '5', '1 -1 1 -1 1', '6', '40 -31 -9 0 13 -40', ''] Output:['YES', '1 -2 3 -4', 'NO', 'YES', '1 1 -1 1 -1', 'YES', '-40 13 40 0 -9 -31', ''] | [
3
] |
Alice and Bob have decided to play the game "Rock, Paper, Scissors". The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a draw. Otherwise, the following rules applied: if one player showed rock and the other one showed scissors, then the player who showed rock is considered the winner and the other one is considered the loser; if one player showed scissors and the other one showed paper, then the player who showed scissors is considered the winner and the other one is considered the loser; if one player showed paper and the other one showed rock, then the player who showed paper is considered the winner and the other one is considered the loser. Alice and Bob decided to play exactly n rounds of the game described above. Alice decided to show rock a_1 times, show scissors a_2 times and show paper a_3 times. Bob decided to show rock b_1 times, show scissors b_2 times and show paper b_3 times. Though, both Alice and Bob did not choose the sequence in which they show things. It is guaranteed that a_1 + a_2 + a_3 = n and b_1 + b_2 + b_3 = n.Your task is to find two numbers: the minimum number of round Alice can win; the maximum number of rounds Alice can win. | Input: ['2', '0 1 1', '1 1 0', ''] Output:['0 1', ''] | [
0,
2,
3
] |
Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros.Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages).Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. | Input: ['4', '1 -5 3 2', ''] Output:['1', ''] | [
2
] |
Initially, you have the array a consisting of one element 1 (a = [1]).In one move, you can do one of the following things: Increase some (single) element of a by 1 (choose some i from 1 to the current length of a and increase a_i by one); Append the copy of some (single) element of a to the end of the array (choose some i from 1 to the current length of a and append a_i to the end of the array). For example, consider the sequence of five moves: You take the first element a_1, append its copy to the end of the array and get a = [1, 1]. You take the first element a_1, increase it by 1 and get a = [2, 1]. You take the second element a_2, append its copy to the end of the array and get a = [2, 1, 1]. You take the first element a_1, append its copy to the end of the array and get a = [2, 1, 1, 2]. You take the fourth element a_4, increase it by 1 and get a = [2, 1, 1, 3]. Your task is to find the minimum number of moves required to obtain the array with the sum at least n.You have to answer t independent test cases. | Input: ['5', '1', '5', '42', '1337', '1000000000', ''] Output:['0', '3', '11', '72', '63244', ''] | [
3,
4
] |
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 \cdot x + 2), and so on.Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.You have to answer t independent test cases. | Input: ['4', '7 3', '1 5', '22 5', '987 13', ''] Output:['3', '1', '5', '77', ''] | [
3
] |
Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero).These atoms also form a peculiar one-way bond. For each i, (1 <= i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom.Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 <= i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!note: You must first change exactly K bonds before you can start exciting atoms. | Input: ['6 1', '5 6 7 8 10 2', '3 5 6 7 1 10', ''] Output:['35', ''] | [
2
] |
Mr. Chanek The Ninja is one day tasked with a mission to handle mad snakes that are attacking a site. Now, Mr. Chanek already arrived at the hills where the destination is right below these hills. The mission area can be divided into a grid of size 1000 * 1000 squares. There are N mad snakes on the site, the i'th mad snake is located on square (X_i, Y_i) and has a danger level B_i.Mr. Chanek is going to use the Shadow Clone Jutsu and Rasengan that he learned from Lord Seventh to complete this mission. His attack strategy is as follows: Mr. Chanek is going to make M clones. Each clone will choose a mad snake as the attack target. Each clone must pick a different mad snake to attack. All clones jump off the hills and attack their respective chosen target at once with Rasengan of radius R. If the mad snake at square (X, Y) is attacked with a direct Rasengan, it and all mad snakes at squares (X', Y') where max(|X' - X|, |Y' - Y|) <= R will die. The real Mr. Chanek will calculate the score of this attack. The score is defined as the square of the sum of the danger levels of all the killed snakes. Now Mr. Chanek is curious, what is the sum of scores for every possible attack strategy? Because this number can be huge, Mr. Chanek only needs the output modulo 10^9 + 7. | Input: ['4 2 1', '1 1 10', '2 2 20', '2 3 30', '5 2 40', ''] Output:['33800', ''] | [
3
] |
Mr. Chanek just won the national chess tournament and got a huge chessboard of size N * M. Bored with playing conventional chess, Mr. Chanek now defines a function F(X, Y), which denotes the minimum number of moves to move a knight from square (1, 1) to square (X, Y). It turns out finding F(X, Y) is too simple, so Mr. Chanek defines:G(X, Y) = \sum_{i=X}^{N} \sum_{j=Y}^{M} F(i, j)Given X and Y, you are tasked to find G(X, Y).A knight can move from square (a, b) to square (a', b') if and only if |a - a'| > 0, |b - b'| > 0, and |a - a'| + |b - b'| = 3. Of course, the knight cannot leave the chessboard. | Input: ['2', '3 4 5 6', '5 5 8 8', ''] Output:['27', '70', ''] | [
3
] |
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing N gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves: Take one gold coin from the chest. Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even. Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally. | Input: ['2', '5', '6', ''] Output:['2', '4', ''] | [
2
] |
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.More precisely, two different numbers a and b are friends if gcd(a,b), \frac{a}{gcd(a,b)}, \frac{b}{gcd(a,b)} can form sides of a triangle.Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.In a group of numbers, a number is lonely if it doesn't have any friends in that group.Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely? | Input: ['3', '1 5 10', ''] Output:['1', '3', '3', ''] | [
3,
4
] |
The Bubble Cup hypothesis stood unsolved for 130 years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem:Given a number m, how many polynomials P with coefficients in set {\{0,1,2,3,4,5,6,7\}} have: P(2)=m?Help Jerry Mao solve the long standing problem! | Input: ['2', '2 4', ''] Output:['2', '4', ''] | [
3
] |
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them:All of them take a sit at their round table, some of them with the golden coins they have just stolen. At each iteration of the game if one of them has equal or more than 2 coins, he is eligible to the splitting and he gives one coin to each pirate sitting next to him. If there are more candidates (pirates with equal or more than 2 coins) then You are the one that chooses which one of them will do the splitting in that iteration. The game ends when there are no more candidates eligible to do the splitting. Pirates can call it a day, only when the game ends. Since they are beings with a finite amount of time at their disposal, they would prefer if the game that they are playing can end after finite iterations, and if so, they call it a good game. On the other hand, if no matter how You do the splitting, the game cannot end in finite iterations, they call it a bad game. Can You help them figure out before they start playing if the game will be good or bad? | Input: ['4 2', '1 2', '2 2', ''] Output:['1'] | [
3
] |
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them. | Input: ['3 5', '1 2 1', '2 3 2', '3 3 3', '2 1 4', '2 2 5', ''] Output:['4', ''] | [
4
] |
Yura owns a quite ordinary and boring array a of length n. You think there is nothing more boring than that, but Vladik doesn't agree!In order to make Yura's array even more boring, Vladik makes q boring queries. Each query consists of two integers x and y. Before answering a query, the bounds l and r for this query are calculated: l = (last + x) \bmod n + 1, r = (last + y) \bmod n + 1, where last is the answer on the previous query (zero initially), and \bmod is the remainder operation. Whenever l > r, they are swapped.After Vladik computes l and r for a query, he is to compute the least common multiple (LCM) on the segment [l; r] of the initial array a modulo 10^9 + 7. LCM of a multiset of integers is the smallest positive integer that is divisible by all the elements of the multiset. The obtained LCM is the answer for this query.Help Vladik and compute the answer for each query! | Input: ['3', '2 3 5', '4', '1 3', '3 3', '2 3', '2 3', ''] Output:['6', '2', '15', '30', ''] | [
3
] |
Some time ago Lesha found an entertaining string s consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.Lesha chooses an arbitrary (possibly zero) number of pairs on positions (i, i + 1) in such a way that the following conditions are satisfied: for each pair (i, i + 1) the inequality 0 <= i < |s| - 1 holds; for each pair (i, i + 1) the equality s_i = s_{i + 1} holds; there is no index that is contained in more than one pair. After that Lesha removes all characters on indexes contained in these pairs and the algorithm is over. Lesha is interested in the lexicographically smallest strings he can obtain by applying the algorithm to the suffixes of the given string. | Input: ['abcdd', ''] Output:['3 abc', '2 bc', '1 c', '0 ', '1 d', ''] | [
2
] |
Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price n, Vova removes a non-empty substring of (consecutive) digits from the price, the remaining digits close the gap, and the resulting integer is the price.For example, is Sasha names 1213121, Vova can remove the substring 1312, and the result is 121.It is allowed for result to contain leading zeros. If Vova removes all digits, the price is considered to be 0.Sasha wants to come up with some constraints so that Vova can't just remove all digits, but he needs some arguments supporting the constraints. To start with, he wants to compute the sum of all possible resulting prices after Vova's move.Help Sasha to compute this sum. Since the answer can be very large, print it modulo 10^9 + 7. | Input: ['107', ''] Output:['42', ''] | [
3
] |
A matrix of size n * m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 <= i <= k) the equality a_i = a_{k - i + 1} holds.Sasha owns a matrix a of size n * m. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.Help him! | Input: ['2', '4 2', '4 2', '2 4', '4 2', '2 4', '3 4', '1 2 3 4', '5 6 7 8', '9 10 11 18', ''] Output:['8', '42', ''] | [
2,
3
] |
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to a, b, c, and d. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself. | Input: ['2', '1 2 3', '12 34 56', ''] Output:['4', '42', ''] | [
3
] |
While playing yet another strategy game, Mans has recruited n Swedish heroes, whose powers which can be represented as an array a.Unfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to accomplish his goal, he can pick two consecutive heroes, with powers a_i and a_{i+1}, remove them and insert a hero with power -(a_i+a_{i+1}) back in the same position. For example if the array contains the elements [5, 6, 7, 8], he can pick 6 and 7 and get [5, -(6+7), 8] = [5, -13, 8].After he will perform this operation n-1 times, Mans will end up having only one hero. He wants his power to be as big as possible. What's the largest possible power he can achieve? | Input: ['4', '5 6 7 8', ''] Output:['26', ''] | [
0
] |
Lindsey Buckingham told Stevie Nicks "Go your own way". Nicks is now sad and wants to go away as quickly as possible, but she lives in a 2D hexagonal world.Consider a hexagonal tiling of the plane as on the picture below. Nicks wishes to go from the cell marked (0, 0) to a certain cell given by the coordinates. She may go from a hexagon to any of its six neighbors you want, but there is a cost associated with each of them. The costs depend only on the direction in which you travel. Going from (0, 0) to (1, 1) will take the exact same cost as going from (-2, -1) to (-1, 0). The costs are given in the input in the order c_1, c_2, c_3, c_4, c_5, c_6 as in the picture below. Print the smallest cost of a path from the origin which has coordinates (0, 0) to the given cell. | Input: ['2', '-3 1', '1 3 5 7 9 11', '1000000000 1000000000', '1000000000 1000000000 1000000000 1000000000 1000000000 1000000000', ''] Output:['18', '1000000000000000000', ''] | [
0,
2,
3
] |
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.Tzuyu gave Sana two integers a and b and a really important quest.In order to complete the quest, Sana has to output the smallest possible value of (a \oplus x) + (b \oplus x) for any given x, where \oplus denotes the bitwise XOR operation. | Input: ['6', '6 12', '4 9', '59 832', '28 14', '4925 2912', '1 1', ''] Output:['10', '13', '891', '18', '6237', '0', ''] | [
2,
3
] |
A lighthouse keeper Peter commands an army of n battle lemmings. He ordered his army to stand in a line and numbered the lemmings from 1 to n from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.The more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.Now it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders: give the shield to the left neighbor if it exists and doesn't have a shield; give the shield to the right neighbor if it exists and doesn't have a shield. In one second Peter can give exactly one order.It's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each k from 0 to \frac{n(n-1)}2, if he gives no more that k orders. Help Peter to calculate it! | Input: ['5', '1 0 0 0 1', ''] Output:['0 2 3 3 3 3 3 3 3 3 3 ', ''] | [
2
] |
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 <= b_1 < b_2 < ... < b_k <= n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | Input: ['3', '3 1', '1 3 2', '1 2', '2 2', '1 2', '1 2', '1 2', '7 5', '1 2 5 4 3 6 7', '1 2', '6 7', '3 4', '1 2', '2 3', ''] Output:['3', '4', '2', '2', '2', '9', '10', '10', '10', '9', '11', ''] | [
2
] |
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 <= b_1 < b_2 < ... < b_k <= n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.Note: q=0 in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan! | Input: ['3', '3 0', '1 3 2', '2 0', '1 2', '7 0', '1 2 5 4 3 6 7', ''] Output:['3', '2', '9', ''] | [
2
] |
"You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j >= a_i \oplus a_j, where \& denotes the bitwise AND operation, and \oplus denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | Input: ['5', '5', '1 4 3 7 10', '3', '1 1 1', '4', '6 2 5 3', '2', '2 4', '1', '1', ''] Output:['1', '3', '2', '0', '0', ''] | [
3
] |
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it! Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent — cubes.For completing the chamber Wheatley needs n cubes. i-th cube has a volume a_i.Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each i>1, a_{i-1} <= a_i must hold.To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any i>1 you can exchange cubes on positions i-1 and i.But there is a problem: Wheatley is very impatient. If Wheatley needs more than \frac{n \cdot (n-1)}{2}-1 exchange operations, he won't do this boring work.Wheatly wants to know: can cubes be sorted under this conditions? | Input: ['3', '5', '5 3 2 1 4', '6', '2 2 2 2 2 2', '2', '2 1', ''] Output:['YES', 'YES', 'NO', ''] | [
3
] |
There are n detachments on the surface, numbered from 1 to n, the i-th detachment is placed in a point with coordinates (x_i, y_i). All detachments are placed in different points.Brimstone should visit each detachment at least once. You can choose the detachment where Brimstone starts.To move from one detachment to another he should first choose one of four directions of movement (up, right, left or down) and then start moving with the constant speed of one unit interval in a second until he comes to a detachment. After he reaches an arbitrary detachment, he can repeat the same process.Each t seconds an orbital strike covers the whole surface, so at that moment Brimstone should be in a point where some detachment is located. He can stay with any detachment as long as needed.Brimstone is a good commander, that's why he can create at most one detachment and place it in any empty point with integer coordinates he wants before his trip. Keep in mind that Brimstone will need to visit this detachment, too.Help Brimstone and find such minimal t that it is possible to check each detachment. If there is no such t report about it. | Input: ['4', '100 0', '0 100', '-100 0', '0 -100', ''] Output:['100'] | [
4
] |
An agent called Cypher is decrypting a message, that contains a composite number n. All divisors of n, which are greater than 1, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that. | Input: ['3', '6', '4', '30', ''] Output:['2 3 6 ', '1', '2 4 ', '0', '2 30 6 3 15 5 10 ', '0', ''] | [
3
] |
This is the hard version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row and they are numbered from 1 to n from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | Input: ['7', '1 3 2 2 4 5 4', ''] Output:['3', '3 1 4 2 4 2 5 '] | [
0,
2,
4
] |
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row and they are numbered from 1 to n from left to right. Each ice sphere has a positive integer price. In this version all prices are different.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | Input: ['5', '1 2 3 4 5', ''] Output:['2', '3 1 4 2 5 '] | [
2,
4
] |
A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).Killjoy's account is already infected and has a rating equal to x. Its rating is constant. There are n accounts except hers, numbered from 1 to n. The i-th account's initial rating is a_i. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.Contests are regularly held on Codeforces. In each contest, any of these n accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.It can be proven that all accounts can be infected in some finite number of contests. | Input: ['3', '2 69', '68 70', '6 4', '4 4 4 4 4 4', '9 38', '-21 83 50 -59 -77 15 -71 -78 20', ''] Output:['1', '0', '2', ''] | [
2,
3
] |
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has n stairs, then it is made of n columns, the first column is 1 cell high, the second column is 2 cells high, ..., the n-th column if n cells high. The lowest cells of all stairs must be in the same row.A staircase with n stairs is called nice, if it may be covered by n disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with 7 stairs looks like: Find out the maximal number of different nice staircases, that can be built, using no more than x cells, in total. No cell can be used more than once. | Input: ['4', '1', '8', '6', '1000000000000000000', ''] Output:['1', '2', '1', '30', ''] | [
0,
2,
3
] |
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated from 1 to n from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with n digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of t matches find out, which agent wins, if both of them want to win and play optimally. | Input: ['4', '1', '2', '1', '3', '3', '102', '4', '2069', ''] Output:['2', '1', '1', '2', ''] | [
2
] |
You are given four integers n, m, l and r.Let's name a tuple (x_1, y_1, x_2, y_2) as good if: 1 <= x_1 < x_2 <= n; 1 <= y_2 < y_1 <= m; x_1 \cdot y_1 = x_2 \cdot y_2; l <= x_1 \cdot y_1 <= r. Find any good tuple for each x_1 from 1 to n inclusive. | Input: ['8 20', '91 100', ''] Output:['-1', '-1', '-1', '-1', '-1', '6 16 8 12', '-1', '-1', ''] | [
3
] |
You are playing a computer game. In this game, you have to fight n monsters.To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes: if a = 0, then you receive d damage; if a > 0 and d >= b, you receive no damage, but the current durability of the shield decreases by 1; if a > 0 and d < b, nothing happens. The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order. | Input: ['3 2', '1 3 1', '2 1', '1 2', ''] Output:['665496237', '1', ''] | [
4
] |
You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are n bosses in this tower, numbered from 1 to n. The type of the i-th boss is a_i. If the i-th boss is easy then its type is a_i = 0, otherwise this boss is hard and its type is a_i = 1.During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session.Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss.Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all n bosses in the given order.For example: suppose n = 8, a = [1, 0, 1, 1, 0, 1, 1, 1]. Then the best course of action is the following: your friend kills two first bosses, using one skip point for the first boss; you kill the third and the fourth bosses; your friend kills the fifth boss; you kill the sixth and the seventh bosses; your friend kills the last boss, using one skip point, so the tower is completed using two skip points. You have to answer t independent test cases. | Input: ['6', '8', '1 0 1 1 0 1 1 1', '5', '1 1 1 1 0', '7', '1 1 1 1 0 0 1', '6', '1 1 1 1 1 1', '1', '1', '1', '0', ''] Output:['2', '2', '2', '2', '1', '0', ''] | [
2
] |
You are given an array a, consisting of n integers.Each position i (1 <= i <= n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}], the underlined positions are locked. You can obtain the following arrays: [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]; [-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]; [1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]; [1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]; and some others. Let p be a sequence of prefix sums of the array a after the rearrangement. So p_1 = a_1, p_2 = a_1 + a_2, p_3 = a_1 + a_2 + a_3, ..., p_n = a_1 + a_2 + ... + a_n.Let k be the maximum j (1 <= j <= n) such that p_j < 0. If there are no j such that p_j < 0, then k = 0.Your goal is to rearrange the values in such a way that k is minimum possible.Output the array a after the rearrangement such that the value k for it is minimum possible. If there are multiple answers then print any of them. | Input: ['5', '3', '1 3 2', '0 0 0', '4', '2 -3 4 -1', '1 1 1 1', '7', '-8 4 -2 -6 4 7 1', '1 0 0 0 1 1 0', '5', '0 1 -4 6 3', '0 0 0 1 1', '6', '-1 7 10 4 -8 -1', '1 0 0 0 0 1', ''] Output:['1 2 3', '2 -3 4 -1', '-8 -6 1 4 4 7 -2', '-4 0 1 6 3', '-1 4 7 -8 10 -1'] | [
2
] |
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange 1 stick for x sticks (you lose 1 stick and gain x sticks). exchange y sticks for 1 coal (you lose y sticks and gain 1 coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least k torches. The answer always exists under the given constraints.You have to answer t independent test cases. | Input: ['5', '2 1 5', '42 13 24', '12 11 12', '1000000000 1000000000 1000000000', '2 1000000000 1000000000', ''] Output:['14', '33', '25', '2000000003', '1000000001999999999', ''] | [
3
] |
RedDreamer has an array a consisting of n non-negative integers, and an unlucky integer T.Let's denote the misfortune of array b having length m as f(b) — the number of pairs of integers (i, j) such that 1 <= i < j <= m and b_i + b_j = T. RedDreamer has to paint each element of a into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays c and d so that all white elements belong to c, and all black elements belong to d (it is possible that one of these two arrays becomes empty). RedDreamer wants to paint the elements in such a way that f(c) + f(d) is minimum possible.For example: if n = 6, T = 7 and a = [1, 2, 3, 4, 5, 6], it is possible to paint the 1-st, the 4-th and the 5-th elements white, and all other elements black. So c = [1, 4, 5], d = [2, 3, 6], and f(c) + f(d) = 0 + 0 = 0; if n = 3, T = 6 and a = [3, 3, 3], it is possible to paint the 1-st element white, and all other elements black. So c = [3], d = [3, 3], and f(c) + f(d) = 0 + 1 = 1. Help RedDreamer to paint the array optimally! | Input: ['2', '6 7', '1 2 3 4 5 6', '3 6', '3 3 3', ''] Output:['1 0 0 1 1 0 ', '1 0 0'] | [
2,
3
] |
— Hey folks, how do you like this problem?— That'll do it. BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows: He chooses two piles (i, j) such that 1 <= i, j <= n and i!=j. All candies from pile i are copied into pile j. Formally, the operation a_j := a_j + a_i is performed. BThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than k candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power? | Input: ['3', '2 2', '1 1', '3 5', '1 2 3', '3 7', '3 2 2', ''] Output:['1', '5', '4', ''] | [
2,
3
] |
Another dull quarantine day was going by when BThero decided to start researching matrices of size n * m. The rows are numerated 1 through n from top to bottom, and the columns are numerated 1 through m from left to right. The cell in the i-th row and j-th column is denoted as (i, j).For each cell (i, j) BThero had two values: The cost of the cell, which is a single positive integer. The direction of the cell, which is one of characters L, R, D, U. Those characters correspond to transitions to adjacent cells (i, j - 1), (i, j + 1), (i + 1, j) or (i - 1, j), respectively. No transition pointed outside of the matrix. Let us call a cell (i_2, j_2) reachable from (i_1, j_1), if, starting from (i_1, j_1) and repeatedly moving to the adjacent cell according to our current direction, we will, sooner or later, visit (i_2, j_2). BThero decided to create another matrix from the existing two. For a cell (i, j), let us denote S_{i, j} as a set of all reachable cells from it (including (i, j) itself). Then, the value at the cell (i, j) in the new matrix will be equal to the sum of costs of all cells in S_{i, j}. After quickly computing the new matrix, BThero immediately sent it to his friends. However, he did not save any of the initial matrices! Help him to restore any two valid matrices, which produce the current one. | Input: ['2', '3 4', '7 6 7 8', '5 5 4 4', '5 7 4 4', '1 1', '5', ''] Output:['YES', '1 1 1 1', '2 1 1 1', '3 2 1 1', 'R D L L', 'D R D L', 'U L R U', 'NO', ''] | [
2
] |
One day, BThero decided to play around with arrays and came up with the following problem:You are given an array a, which consists of n positive integers. The array is numerated 1 through n. You execute the following procedure exactly once: You create a new array b which consists of 2n positive integers, where for each 1 <= i <= n the condition b_{2i-1}+b_{2i} = a_i holds. For example, for the array a = [6, 8, 2] you can create b = [2, 4, 4, 4, 1, 1]. You merge consecutive equal numbers in b. For example, b = [2, 4, 4, 4, 1, 1] becomes b = [2, 4, 1]. Find and print the minimum possible value of |b| (size of b) which can be achieved at the end of the procedure. It can be shown that under the given constraints there is at least one way to construct b. | Input: ['3', '3', '6 8 2', '1', '4', '3', '5 6 6', ''] Output:['3', '1', '2', ''] | [
2,
4
] |
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i \oplus x (\oplus denotes the operation bitwise XOR).An inversion in the b array is a pair of integers i and j such that 1 <= i < j <= n and b_i > b_j.You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one. | Input: ['4', '0 1 3 2', ''] Output:['1 0', ''] | [
2,
3
] |
You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: choose three integers i, j and x (1 <= i, j <= n; 0 <= x <= 10^9); assign a_i := a_i - x \cdot i, a_j := a_j + x \cdot i. After each operation, all elements of the array should be non-negative.Can you find a sequence of no more than 3n operations after which all elements of the array are equal? | Input: ['3', '4', '2 16 4 18', '6', '1 2 3 4 5 6', '5', '11 19 1 1 3', ''] Output:['2', '4 1 2', '2 3 3', '-1', '4', '1 2 4', '2 4 5', '2 3 3', '4 5 1', ''] | [
2,
3
] |
You are given an array a consisting of n integers numbered from 1 to n.Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there is no integer occuring in all subsegments of length k for some value of k, then the k-amazing number is -1.For each k from 1 to n calculate the k-amazing number of the array a. | Input: ['3', '5', '1 2 3 4 5', '5', '4 4 4 4 2', '6', '1 3 1 5 3 1', ''] Output:['-1 -1 3 2 1 ', '-1 4 4 4 2 ', '-1 -1 1 1 1 1 ', ''] | [
4
] |
Wabbit is playing a game with n bosses numbered from 1 to n. The bosses can be fought in any order. Each boss needs to be defeated exactly once. There is a parameter called boss bonus which is initially 0.When the i-th boss is defeated, the current boss bonus is added to Wabbit's score, and then the value of the boss bonus increases by the point increment c_i. Note that c_i can be negative, which means that other bosses now give fewer points.However, Wabbit has found a glitch in the game. At any point in time, he can reset the playthrough and start a New Game Plus playthrough. This will set the current boss bonus to 0, while all defeated bosses remain defeated. The current score is also saved and does not reset to zero after this operation. This glitch can be used at most k times. He can reset after defeating any number of bosses (including before or after defeating all of them), and he also can reset the game several times in a row without defeating any boss.Help Wabbit determine the maximum score he can obtain if he has to defeat all n bosses. | Input: ['3 0', '1 1 1', ''] Output:['3', ''] | [
2,
3
] |
Arkady owns a non-decreasing array a_1, a_2, ..., a_n. You are jealous of its beauty and want to destroy this property. You have a so-called XOR-gun that you can use one or more times.In one step you can select two consecutive elements of the array, let's say x and y, remove them from the array and insert the integer x \oplus y on their place, where \oplus denotes the bitwise XOR operation. Note that the length of the array decreases by one after the operation. You can't perform this operation when the length of the array reaches one.For example, if the array is [2, 5, 6, 8], you can select 5 and 6 and replace them with 5 \oplus 6 = 3. The array becomes [2, 3, 8].You want the array no longer be non-decreasing. What is the minimum number of steps needed? If the array stays non-decreasing no matter what you do, print -1. | Input: ['4', '2 5 6 8', ''] Output:['1', ''] | [
0
] |
You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from 1, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell p, then bounces off it, then bounces off a platform in the cell (p + k), then a platform in the cell (p + 2k), and so on every k-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these p and k.You already have some level pattern a_1, a_2, a_3, ..., a_n, where a_i = 0 means there is no platform in the cell i, and a_i = 1 means there is one. You want to modify it so that the level can be passed with given p and k. In x seconds you can add a platform in some empty cell. In y seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than p. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given p and k? | Input: ['3', '10 3 2', '0101010101', '2 2', '5 4 1', '00000', '2 10', '11 2 3', '10110011000', '4 3', ''] Output:['2', '4', '10', ''] | [
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.