question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
Let us call two integers x and y adjacent if \frac{lcm(x, y)}{gcd(x, y)} is a perfect square. For example, 3 and 12 are adjacent, but 6 and 9 are not.Here gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y, and lcm(x, y) denotes the least common multiple (LCM) of integers x and y.You are given an array a of length n. Each second the following happens: each element a_i of the array is replaced by the product of all elements of the array (including itself), that are adjacent to the current value. Let d_i be the number of adjacent elements to a_i (including a_i itself). The beauty of the array is defined as \max_{1 <= i <= n} d_i. You are given q queries: each query is described by an integer w, and you have to output the beauty of the array after w seconds. | Input: ['2', '4', '6 8 4 2', '1', '0', '6', '12 3 20 5 80 1', '1', '1', ''] Output:['2', '3', ''] | [
3
] |
Petya organized a strange birthday party. He invited n friends and assigned an integer k_i to the i-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are m unique presents available, the j-th present costs c_j dollars (1 <= c_1 <= c_2 <= ... <= c_m). It's not allowed to buy a single present more than once.For the i-th friend Petya can either buy them a present j <= k_i, which costs c_j dollars, or just give them c_{k_i} dollars directly.Help Petya determine the minimum total cost of hosting his party. | Input: ['2', '5 4', '2 3 4 3 2', '3 5 12 20', '5 5', '5 4 3 2 1', '10 40 90 160 250', ''] Output:['30', '190', ''] | [
2,
4
] |
// We decided to drop the legend about the power sockets but feel free to come up with your own :^)Define a chain: a chain of length 1 is a single vertex; a chain of length x is a chain of length x-1 with a new vertex connected to the end of it with a single edge. You are given n chains of lengths l_1, l_2, ..., l_n. You plan to build a tree using some of them. Each vertex of the tree is either white or black. The tree initially only has a white root vertex. All chains initially consist only of white vertices. You can take one of the chains and connect any of its vertices to any white vertex of the tree with an edge. The chain becomes part of the tree. Both endpoints of this edge become black. Each chain can be used no more than once. Some chains can be left unused. The distance between two vertices of the tree is the number of edges on the shortest path between them.If there is at least k white vertices in the resulting tree, then the value of the tree is the distance between the root and the k-th closest white vertex.What's the minimum value of the tree you can obtain? If there is no way to build a tree with at least k white vertices, then print -1. | Input: ['1 2', '3', ''] Output:['2', ''] | [
2,
4
] |
Let's call two strings a and b (both of length k) a bit similar if they have the same character in some position, i. e. there exists at least one i \in [1, k] such that a_i = b_i.You are given a binary string s of length n (a string of n characters 0 and/or 1) and an integer k. Let's denote the string s[i..j] as the substring of s starting from the i-th character and ending with the j-th character (that is, s[i..j] = s_i s_{i + 1} s_{i + 2} ... s_{j - 1} s_j).Let's call a binary string t of length k beautiful if it is a bit similar to all substrings of s having length exactly k; that is, it is a bit similar to s[1..k], s[2..k+1], ..., s[n-k+1..n].Your goal is to find the lexicographically smallest string t that is beautiful, or report that no such string exists. String x is lexicographically less than string y if either x is a prefix of y (and x!=y), or there exists such i (1 <= i <= \min(|x|, |y|)), that x_i < y_i, and for any j (1 <= j < i) x_j = y_j. | Input: ['7', '4 2', '0110', '4 2', '1001', '9 3', '010001110', '9 3', '101110001', '10 3', '0101110001', '10 10', '1111111111', '11 10', '11111111110', ''] Output:['YES', '11', 'YES', '00', 'YES', '010', 'YES', '101', 'NO', 'YES', '0000000001', 'YES', '0000000010', ''] | [
0
] |
You have an array a_1, a_2, ..., a_n where a_i = i.In one step, you can choose two indices x and y (x \neq y) and set a_x = <=ft\lceil \frac{a_x}{a_y} \right\rceil (ceiling function).Your goal is to make array a consist of n - 1 ones and 1 two in no more than n + 5 steps. Note that you don't have to minimize the number of steps. | Input: ['2', '3', '4', ''] Output:['2', '3 2', '3 2', '3', '3 4', '4 2', '4 2', ''] | [
0,
3
] |
You want to build a fence that will consist of n equal sections. All sections have a width equal to 1 and height equal to k. You will place all sections in one line side by side.Unfortunately, the ground beneath the fence is not flat. For simplicity, you can think that the ground level under the i-th section is equal to h_i. You should follow several rules to build the fence: the consecutive sections should have a common side of length at least 1; the first and the last sections should stand on the corresponding ground levels; the sections between may be either on the ground level or higher, but not higher than k - 1 from the ground level h_i (the height should be an integer); One of possible fences (blue color) for the first test case Is it possible to build a fence that meets all rules? | Input: ['3', '6 3', '0 0 2 5 1 1', '2 3', '0 2', '3 2', '3 0 2', ''] Output:['YES', 'YES', 'NO', ''] | [
2
] |
Monocarp had a sequence a consisting of n + m integers a_1, a_2, ..., a_{n + m}. He painted the elements into two colors, red and blue; n elements were painted red, all other m elements were painted blue.After painting the elements, he has written two sequences r_1, r_2, ..., r_n and b_1, b_2, ..., b_m. The sequence r consisted of all red elements of a in the order they appeared in a; similarly, the sequence b consisted of all blue elements of a in the order they appeared in a as well.Unfortunately, the original sequence was lost, and Monocarp only has the sequences r and b. He wants to restore the original sequence. In case there are multiple ways to restore it, he wants to choose a way to restore that maximizes the value of f(a) = \max(0, a_1, (a_1 + a_2), (a_1 + a_2 + a_3), ..., (a_1 + a_2 + a_3 + ... + a_{n + m}))Help Monocarp to calculate the maximum possible value of f(a). | Input: ['4', '4', '6 -5 7 -3', '3', '2 3 -4', '2', '1 1', '4', '10 -3 2 2', '5', '-1 -2 -3 -4 -5', '5', '-1 -2 -3 -4 -5', '1', '0', '1', '0', ''] Output:['13', '13', '0', '0', ''] | [
2
] |
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS".You are given a sequence s of n characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence.You have to replace every character ? with either ) or ( (different characters ? can be replaced with different brackets). You cannot reorder the characters, remove them, insert other characters, and each ? must be replaced.Determine if it is possible to obtain an RBS after these replacements. | Input: ['5', '()', '(?)', '(??)', '??()', ')?(?', ''] Output:['YES', 'NO', 'YES', 'YES', 'NO', ''] | [
2
] |
The progress is not standing still in Berland. Recently all garbage containers in Bertown, the capital of Berland, were replaced by differentiated recycling bins, each accepting some category of waste. While this will definitely improve the ecological situation, for some citizens it's difficult to get used to the habit of sorting waste.Monocarp is one of those citizens who tries to get used to waste sorting. Today he has to take out the trash from his house. There are three containers near the Monocarp's house, the first one accepts paper waste, the second one accepts plastic waste, and the third one β all other types of waste. It is possible to fit c_1 items into the first container, c_2 items into the second container and c_3 items into the third container.Monocarp has a lot of items to throw into containers. Some are made of paper, so Monocarp has to put them into the first container (he has a_1 such items), some are made of plastic, so he has to put them into the second container (he has a_2 such items), and some are neither paper nor plastic β so Monocarp has to put them into the third container (he has a_3 such items).Unfortunately, there are also two categories of items that Monocarp is unsure of: he has a_4 items which are partially made of paper, so he will put each of these items either into the first container or into the third container. Similarly, he has a_5 items partially made of plastic, so he has to put each of them either into the second container or into the third container. Obviously, this choice is made separately for each item β for example, Monocarp can throw several partially-plastic items into the second container, and all other partially-plastic items β into the third one.Now Monocarp wonders: is it possible to put each item into some container so that the first container will hold no more than c_1 items, the second one β no more than c_2 items, and the third one β no more than c_3 items? | Input: ['7', '1 2 3', '1 2 3 0 0', '2 2 3', '1 2 3 1 0', '2 2 3', '1 2 3 0 1', '1 2 5', '1 2 3 1 1', '0 0 0', '0 0 0 0 0', '0 0 4', '1 0 0 0 0', '13 37 42', '0 0 0 40 47', ''] Output:['YES', 'YES', 'NO', 'YES', 'YES', 'NO', 'YES', ''] | [
2
] |
Suppose you have a sequence of k integers A = [a_1, a_2, ... , a_k] where each a_i >=q 2. A sequence of prime integers P = [p_1, p_2, ..., p_k] is called suitable for the sequence A if a_1 is divisible by p_1, a_2 is divisible by p_2 and so on. A sequence of prime integers P is called friendly if there are no unique integers in this sequence. A sequence A is called ideal, if each sequence P that is suitable for A is friendly as well (i.βe. there is no sequence P that is suitable for A, but not friendly). For example, the sequence [2, 4, 16] is ideal, while the sequence [2, 4, 6] is not ideal (there exists a sequence P = [2, 2, 3] which is suitable for A, but not friendly).You are given n different integers x_1, x_2, ..., x_n. You have to choose exactly k of them in such a way that they form an ideal sequence, or report that it is impossible. Note that no integer can be chosen more than once. | Input: ['3 32 4 6'] Output:['0'] | [
2,
3,
4
] |
There is a robot on a checkered field that is endless in all directions. Initially, the robot is located in the cell with coordinates (0, 0). He will execute commands which are described by a string of capital Latin letters 'L', 'R', 'D', 'U'. When a command is executed, the robot simply moves in the corresponding direction: 'L': one cell to the left (the x-coordinate of the current cell decreases by 1); 'R': one cell to the right (the x-coordinate of the current cell is increased by 1); 'D': one cell down (the y-coordinate of the current cell decreases by 1); 'U': one cell up (the y-coordinate of the current cell is increased by 1). Your task is to put an obstacle in one cell of the field so that after executing the commands, the robot will return to the original cell of its path (0, 0). Of course, an obstacle cannot be placed in the starting cell (0, 0). It is guaranteed that if the obstacle is not placed, then the robot will not return to the starting cell.An obstacle affects the movement of the robot in the following way: if it tries to go in a certain direction, and there is an obstacle, then it simply remains in place (the obstacle also remains, that is, it does not disappear).Find any such cell of the field (other than (0, 0)) that if you put an obstacle there, the robot will return to the cell (0, 0) after the execution of all commands. If there is no solution, then report it. | Input: ['4LRUUDLLLUUDDDUUUUU'] Output:['-1 0', '1 2', '0 0', '0 1', ''] | [
0
] |
There are n cities and m bidirectional roads in Berland. The i-th road connects the cities x_i and y_i, and has the speed limit s_i. The road network allows everyone to get from any city to any other city. The Berland Transport Ministry is planning a road reform.First of all, maintaining all m roads is too costly, so m - (n - 1) roads will be demolished in such a way that the remaining (n - 1) roads still allow to get to any city from any other city. Formally, the remaining roads should represent an undirected tree.Secondly, the speed limits on the remaining roads might be changed. The changes will be done sequentially, each change is either increasing the speed limit on some road by 1, or decreasing it by 1. Since changing the speed limit requires a lot of work, the Ministry wants to minimize the number of changes.The goal of the Ministry is to have a road network of (n - 1) roads with the maximum speed limit over all roads equal to exactly k. They assigned you the task of calculating the minimum number of speed limit changes they have to perform so the road network meets their requirements.For example, suppose the initial map of Berland looks like that, and k = 7: Then one of the optimal courses of action is to demolish the roads 1β4 and 3β4, and then decrease the speed limit on the road 2β3 by 1, so the resulting road network looks like that: | Input: ['44 5 74 1 31 2 52 3 82 4 13 4 44 6 51 2 11 3 11 4 22 4 14 3 13 2 13 2 101 2 81 3 105 5 151 2 173 1 152 3 101 4 142 5 8'] Output:['1', '3', '0', '0', ''] | [
2
] |
You are given five integers n, dx_1, dy_1, dx_2 and dy_2. You have to select n distinct pairs of integers (x_i, y_i) in such a way that, for every possible pair of integers (x, y), there exists exactly one triple of integers (a, b, i) meeting the following constraints: \begin{cases} x \, = \, x_i + a \cdot dx_1 + b \cdot dx_2, \\ y \, = \, y_i + a \cdot dy_1 + b \cdot dy_2. \end{cases} | Input: ['4', '2 0', '0 2', ''] Output:['YES', '0 0', '0 1', '1 0', '1 1', ''] | [
3
] |
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3.You have a sequence of n integers [1, 2, ..., n] and an odd integer k.In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them).For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps?You'll be given t test cases. Solve each test case independently. | Input: ['43 3 117 3 31 5 710 5 34 5 613 7 71 3 5 7 9 11 12'] Output:['NO', 'YES', 'NO', 'YES', ''] | [
2,
3
] |
The hobbits Frodo and Sam are carrying the One Ring to Mordor. In order not to be spotted by orcs, they decided to go through the mountains.The mountain relief can be represented as a polyline with n points (x_i, y_i), numbered from 1 to n (x_i < x_{i + 1} for 1 <= i <= n - 1). Hobbits start their journey at the point (x_1, y_1) and should reach the point (x_n, y_n) to complete their mission.The problem is that there is a tower with the Eye of Sauron, which watches them. The tower is located at the point (x_n, y_n) and has the height H, so the Eye is located at the point (x_n, y_n + H). In order to complete the mission successfully, the hobbits have to wear cloaks all the time when the Sauron Eye can see them, i.βe. when there is a direct line from the Eye to the hobbits which is not intersected by the relief.The hobbits are low, so their height can be considered negligibly small, but still positive, so when a direct line from the Sauron Eye to the hobbits only touches the relief, the Eye can see them. The Sauron Eye can't see hobbits when they are in the left position, but can see them when they are in the right position. The hobbits do not like to wear cloaks, so they wear them only when they can be spotted by the Eye. Your task is to calculate the total distance the hobbits have to walk while wearing cloaks. | Input: ['6 10', '10 40', '20 10', '25 30', '30 15', '50 15', '65 30', ''] Output:['70.4034587602', ''] | [
4
] |
Monocarp wants to draw four line segments on a sheet of paper. He wants the i-th segment to have its length equal to a_i (1 <= i <= 4). These segments can intersect with each other, and each segment should be either horizontal or vertical.Monocarp wants to draw the segments in such a way that they enclose a rectangular space, and the area of that rectangular space should be maximum possible.For example, if Monocarp wants to draw four segments with lengths 1, 2, 3 and 4, he can do it the following way: Here, Monocarp has drawn segments AB (with length 1), CD (with length 2), BC (with length 3) and EF (with length 4). He got a rectangle ABCF with area equal to 3 that is enclosed by the segments. Calculate the maximum area of a rectangle Monocarp can enclose with four segments. | Input: ['4', '1 2 3 4', '5 5 5 5', '3 1 4 1', '100 20 20 100', ''] Output:['3', '25', '3', '2000', ''] | [
2
] |
Consider a long corridor which can be divided into n square cells of size 1 * 1. These cells are numbered from 1 to n from left to right.There are two people in this corridor, a hooligan and a security guard. Initially, the hooligan is in the a-th cell, the guard is in the b-th cell (a!=b). One of the possible situations. The corridor consists of 7 cells, the hooligan is in the 3-rd cell, the guard is in the 6-th (n = 7, a = 3, b = 6). There are m firecrackers in the hooligan's pocket, the i-th firecracker explodes in s_i seconds after being lit.The following events happen each second (sequentially, exactly in the following order): firstly, the hooligan either moves into an adjacent cell (from the cell i, he can move to the cell (i + 1) or to the cell (i - 1), and he cannot leave the corridor) or stays in the cell he is currently. If the hooligan doesn't move, he can light one of his firecrackers and drop it. The hooligan can't move into the cell where the guard is; secondly, some firecrackers that were already dropped may explode. Formally, if the firecracker j is dropped on the T-th second, then it will explode on the (T + s_j)-th second (for example, if a firecracker with s_j = 2 is dropped on the 4-th second, it explodes on the 6-th second); finally, the guard moves one cell closer to the hooligan. If the guard moves to the cell where the hooligan is, the hooligan is caught. Obviously, the hooligan will be caught sooner or later, since the corridor is finite. His goal is to see the maximum number of firecrackers explode before he is caught; that is, he will act in order to maximize the number of firecrackers that explodes before he is caught.Your task is to calculate the number of such firecrackers, if the hooligan acts optimally. | Input: ['37 2 3 61 47 2 3 65 17 2 3 64 4'] Output:['2', '1', '1', ''] | [
4
] |
Let's call a sequence b_1, b_2, b_3 ..., b_{k - 1}, b_k almost increasing if \min(b_1, b_2) <= \min(b_2, b_3) <= ... <= \min(b_{k - 1}, b_k). In particular, any sequence with no more than two elements is almost increasing.You are given a sequence of integers a_1, a_2, ..., a_n. Calculate the length of its longest almost increasing subsequence.You'll be given t test cases. Solve each test case independently.Reminder: a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. | Input: ['381 2 7 3 2 1 2 322 174 1 5 2 6 3 7'] Output:['6', '2', '7', ''] | [
2
] |
There are n cells, numbered 1,2,..., n from left to right. You have to place a robot at any cell initially. The robot must make exactly k moves.In one move, the robot must move one cell to the left or right, provided that it doesn't move out of bounds. In other words, if the robot was in the cell i, it must move to either the cell i-1 or the cell i+1, as long as it lies between 1 and n (endpoints inclusive). The cells, in the order they are visited (including the cell the robot is placed), together make a good path.Each cell i has a value a_i associated with it. Let c_0, c_1, ..., c_k be the sequence of cells in a good path in the order they are visited (c_0 is the cell robot is initially placed, c_1 is the cell where the robot is after its first move, and so on; more formally, c_i is the cell that the robot is at after i moves). Then the value of the path is calculated as a_{c_0} + a_{c_1} + ... + a_{c_k}.Your task is to calculate the sum of values over all possible good paths. Since this number can be very large, output it modulo 10^9 + 7. Two good paths are considered different if the starting cell differs or there exists an integer i \in [1, k] such that the current cell of the robot after exactly i moves is different in those paths.You must process q updates to a and print the updated sum each time. Each update changes the value of exactly one cell. See the input format and the sample input-output for more details. | Input: ['5 1 5', '3 5 1 4 2', '1 9', '2 4', '3 6', '4 6', '5 2', ''] Output:['62', '58', '78', '86', '86', ''] | [
3
] |
You are given three bags. Each bag contains a non-empty multiset of numbers. You can perform a number of operations on these bags. In one operation, you can choose any two non-empty bags, and choose one number from each of the bags. Let's say that you choose number a from the first bag and number b from the second bag. Then, you remove b from the second bag and replace a with a-b in the first bag. Note that if there are multiple occurrences of these numbers, then you shall only remove/replace exactly one occurrence.You have to perform these operations in such a way that you have exactly one number remaining in exactly one of the bags (the other two bags being empty). It can be shown that you can always apply these operations to receive such a configuration in the end. Among all these configurations, find the one which has the maximum number left in the end. | Input: ['2 4 1', '1 2', '6 3 4 5', '5', ''] Output:['20'] | [
2
] |
You are given a sequence of n integers a_1, a_2, ..., a_n. Let us call an index j (2 <= j <= {{n-1}}) a hill if a_j > a_{{j+1}} and a_j > a_{{j-1}}; and let us call it a valley if a_j < a_{{j+1}} and a_j < a_{{j-1}}.Let us define the intimidation value of a sequence as the sum of the number of hills and the number of valleys in the sequence. You can change exactly one integer in the sequence to any number that you want, or let the sequence remain unchanged. What is the minimum intimidation value that you can achieve? | Input: ['4', '3', '1 5 3', '5', '2 2 2 2 2', '6', '1 6 2 5 2 10', '5', '1 6 2 5 1', ''] Output:['0', '0', '1', '0', ''] | [
0
] |
There are n digital panels placed in a straight line. Each panel can show any digit from 0 to 9. Initially, all panels show 0.Every second, the digit shown by each panel increases by 1. In other words, at the end of every second, a panel that showed 9 would now show 0, a panel that showed 0 would now show 1, a panel that showed 1 would now show 2, and so on.When a panel is paused, the digit displayed on the panel does not change in the subsequent seconds.You must pause exactly one of these panels, at any second you wish. Then, the panels adjacent to it get paused one second later, the panels adjacent to those get paused 2 seconds later, and so on. In other words, if you pause panel x, panel y (for all valid y) would be paused exactly |xβy| seconds later.For example, suppose there are 4 panels, and the 3-rd panel is paused when the digit 9 is on it. The panel 1 pauses 2 seconds later, so it has the digit 1; the panel 2 pauses 1 second later, so it has the digit 0; the panel 4 pauses 1 second later, so it has the digit 0. The resulting 4-digit number is 1090. Note that this example is not optimal for n = 4.Once all panels have been paused, you write the digits displayed on them from left to right, to form an n digit number (it can consist of leading zeros). What is the largest possible number you can get? Initially, all panels show 0. | Input: ['2', '1', '2', ''] Output:['9', '98', ''] | [
2,
3
] |
What walks on four feet in the morning, two in the afternoon, and three at night?This is an interactive problem. This problem doesn't support hacks.Sphinx's duty is to guard the city of Thebes by making sure that no unworthy traveler crosses its gates. Only the ones who answer her riddle timely and correctly (or get an acc for short) are allowed to pass. As of those who fail, no one heard of them ever again...So you don't have a choice but to solve the riddle. Sphinx has an array a_1, a_2, ..., a_n of nonnegative integers strictly smaller than 2^b and asked you to find the maximum value among its elements. Of course, she will not show you the array, but she will give you n and b. As it is impossible to answer this riddle blindly, you can ask her some questions. For given i, y, she'll answer you whether a_i is bigger than y. As sphinxes are not very patient, you can ask at most 3 \cdot (n + b) such questions.Although cunning, sphinxes are honest. Even though the array can change between your queries, answers to the previously asked questions will remain valid. | Input: ['5 3', '', 'yes', '', 'no', '', 'no', '', 'no', '', 'no', '', 'yes', ''] Output:['5 101', '', '5 110', '', '4 100', '', '3 101', '', '2 001', '', '1 000', '', '0 110', ''] | [
4
] |
Getting so far in this contest is not an easy feat. By solving all the previous problems, you have impressed the gods greatly. Thus, they decided to spare you the story for this problem and grant a formal statement instead.Consider n agents. Each one of them initially has exactly one item, i-th agent has the item number i. We are interested in reassignments of these items among the agents. An assignment is valid iff each item is assigned to exactly one agent, and each agent is assigned exactly one item.Each agent has a preference over the items, which can be described by a permutation p of items sorted from the most to the least desirable. In other words, the agent prefers item i to item j iff i appears earlier in the permutation p. A preference profile is a list of n permutations of length n each, such that i-th permutation describes preferences of the i-th agent.It is possible that some of the agents are not happy with the assignment of items. A set of dissatisfied agents may choose not to cooperate with other agents. In such a case, they would exchange the items they possess initially (i-th item belongs to i-th agent) only between themselves. Agents from this group don't care about the satisfaction of agents outside of it. However, they need to exchange their items in such a way that will make at least one of them happier, and none of them less happy (in comparison to the given assignment).Formally, consider a valid assignment of items β A. Let A(i) denote the item assigned to i-th agent. Also, consider a subset of agents. Let S be the set of their indices. We will say this subset of agents is dissatisfied iff there exists a valid assignment B(i) such that: For each i \in S, B(i) \in S. No agent i \in S prefers A(i) to B(i) (no agent from the S is less happy). At least one agent i \in S prefers B(i) to A(i) (at least one agent from the S is happier). An assignment is optimal if no subset of the agents is dissatisfied. Note that the empty subset cannot be dissatisfied. It can be proven that for each preference profile, there is precisely one optimal assignment.Example: Consider 3 agents with the following preference profile: [2, 1, 3] [1, 2, 3] [1, 3, 2] And such an assignment: First agent gets item 2 Second agent gets item 3. Third agent gets item 1. See that the set of agents \{1, 2\} is dissatisfied, because they can reassign their (initial) items in the following way: First agent gets item 2. Second agent gets item 1. Third agent gets item 3. This reassignment will make the second agent happier and make no difference to the first agent. As a result, the third agent got an item that is worse for him, but this does not prevent the set \{1,2\} from being dissatisfied (he is not in this set).The following assignment would be optimal: First agent gets item 2. Second agent gets item 1. Third agent gets item 3. Given an assignment A, calculate the number of distinct preference profiles for which assignment A is optimal. As the answer can be huge, output it modulo 10^9+7.Two preference profiles are different iff they assign different preference permutations to any agent. | Input: ['2', '2 1', ''] Output:['1', ''] | [
2,
3
] |
Whoso in ignorance draws near to them and hears the Sirens' voice, he nevermore returns.Homer, OdysseyIn the times of Jason and the Argonauts, it was well known that sirens use the sound of their songs to lure sailors into their demise. Yet only a few knew that every time sirens call a sailor by his name, his will weakens, making him more vulnerable. For the purpose of this problem, both siren songs and names of the sailors will be represented as strings of lowercase English letters. The more times the sailor's name occurs as a contiguous substring of the song, the greater danger he is in.Jason found out that sirens can sing one of the n+1 songs, which have the following structure: let s_i (0 <=q i <=q n) be the i-th song and t be a string of length n, then for every i < n: s_{i+1} = s_i t_i s_i. In other words i+1-st song is the concatenation of i-th song, i-th letter (0-indexed) of t and the i-th song. Fortunately, he also knows s_0 and t. Jason wonders how many times a sailor's name is mentioned in a particular song. Answer q queries: given the sailor's name (w) and the index of a song (i) output the number of occurrences of w in s_i as a substring. As this number can be quite large, output its remainder modulo 10^9+7. | Input: ['3 3', 'aa', 'bcd', '2 aba', '3 ca', '3 aa', ''] Output:['2', '2', '8', ''] | [
3
] |
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare. In his bad dream Euclid has a set S of n m-dimensional vectors over the \mathbb{Z}_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) \bmod 2. Euclid can sum any subset of S and archive another m-dimensional vector over \mathbb{Z}_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1. Help Euclid and calculate |T|, the number of m-dimensional vectors over \mathbb{Z}_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input. Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i. | Input: ['3 2', '1 1', '1 2', '2 2 1', ''] Output:['4 2', '1 2 ', ''] | [
2,
3
] |
Only a few know that Pan and Apollo weren't only battling for the title of the GOAT musician. A few millenniums later, they also challenged each other in math (or rather in fast calculations). The task they got to solve is the following:Let x_1, x_2, ..., x_n be the sequence of n non-negative integers. Find this value: \sum_{i=1}^n \sum_{j=1}^n \sum_{k=1}^n (x_i \, \& \, x_j) \cdot (x_j \, | \, x_k)Here \& denotes the bitwise and, and | denotes the bitwise or.Pan and Apollo could solve this in a few seconds. Can you do it too? For convenience, find the answer modulo 10^9 + 7. | Input: ['8', '2', '1 7', '3', '1 2 4', '4', '5 5 5 5', '5', '6 2 2 1 0', '1', '0', '1', '1', '6', '1 12 123 1234 12345 123456', '5', '536870912 536870911 1152921504606846975 1152921504606846974 1152921504606846973', ''] Output:['128', '91', '1600', '505', '0', '1', '502811676', '264880351', ''] | [
0,
3
] |
You've probably heard about the twelve labors of Heracles, but do you have any idea about the thirteenth? It is commonly assumed it took him a dozen years to complete the twelve feats, so on average, a year to accomplish every one of them. As time flows faster these days, you have minutes rather than months to solve this task. But will you manage?In this problem, you are given a tree with n weighted vertices. A tree is a connected graph with n - 1 edges.Let us define its k-coloring as an assignment of k colors to the edges so that each edge has exactly one color assigned to it. Note that you don't have to use all k colors.A subgraph of color x consists of these edges from the original tree, which are assigned color x, and only those vertices that are adjacent to at least one such edge. So there are no vertices of degree 0 in such a subgraph.The value of a connected component is the sum of weights of its vertices. Let us define the value of a subgraph as a maximum of values of its connected components. We will assume that the value of an empty subgraph equals 0.There is also a value of a k-coloring, which equals the sum of values of subgraphs of all k colors. Given a tree, for each k from 1 to n - 1 calculate the maximal value of a k-coloring. | Input: ['4', '4', '3 5 4 6', '2 1', '3 1', '4 3', '2', '21 32', '2 1', '6', '20 13 17 13 13 11', '2 1', '3 1', '4 1', '5 1', '6 1', '4', '10 6 6 6', '1 2', '2 3', '4 1', ''] Output:['18 22 25', '53', '87 107 127 147 167', '28 38 44', ''] | [
2
] |
After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades. Orpheus, a famous poet, and musician plans to calm Cerberus with his poetry and safely walk past him. He created a very peculiar poem for Cerberus. It consists only of lowercase English letters. We call a poem's substring a palindrome if and only if it reads the same backwards and forwards. A string a is a substring of a string b if a can be obtained from b by deleting several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end.Unfortunately, Cerberus dislikes palindromes of length greater than 1. For example in the poem abaa the hound of Hades wouldn't like substrings aba and aa.Orpheus can only calm Cerberus if the hound likes his poetry. That's why he wants to change his poem so that it does not contain any palindrome substrings of length greater than 1.Orpheus can modify the poem by replacing a letter at any position with any lowercase English letter. He can use this operation arbitrarily many times (possibly zero). Since there can be many palindromes in his poem, he may have to make some corrections. But how many, exactly? Given the poem, determine the minimal number of letters that have to be changed so that the poem does not contain any palindromes of length greater than 1. | Input: ['7', 'babba', 'abaac', 'codeforces', 'zeroorez', 'abcdcba', 'bbbbbbb', 'a', ''] Output:['1', '1', '0', '1', '1', '4', '0', ''] | [
2
] |
Athenaeus has just finished creating his latest musical composition and will present it tomorrow to the people of Athens. Unfortunately, the melody is rather dull and highly likely won't be met with a warm reception. His song consists of n notes, which we will treat as positive integers. The diversity of a song is the number of different notes it contains. As a patron of music, Euterpe watches over composers and guides them throughout the process of creating new melodies. She decided to help Athenaeus by changing his song to make it more diverse.Being a minor goddess, she cannot arbitrarily change the song. Instead, for each of the n notes in the song, she can either leave it as it is or increase it by 1.Given the song as a sequence of integers describing the notes, find out the maximal, achievable diversity. | Input: ['5', '6', '1 2 2 2 5 6', '2', '4 4', '6', '1 1 3 4 4 5', '1', '1', '6', '1 1 1 2 2 2', ''] Output:['5', '2', '6', '1', '3', ''] | [
2
] |
Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io.There are n trees growing along the river, where Argus tends Io. For this problem, the river can be viewed as the OX axis of the Cartesian coordinate system, and the n trees as points with the y-coordinate equal 0. There is also another tree growing in the point (0, 1). Argus will tie a rope around three of the trees, creating a triangular pasture. Its exact shape doesn't matter to Io, but its area is crucial to her. There may be many ways for Argus to arrange the fence, but only the ones which result in different areas of the pasture are interesting for Io. Calculate the number of different areas that her pasture may have. Note that the pasture must have nonzero area. | Input: ['8', '4', '1 2 4 5', '3', '1 3 5', '3', '2 6 8', '2', '1 2', '1', '50', '5', '3 4 5 6 8', '3', '1 25 26', '6', '1 2 4 8 16 32', ''] Output:['4', '2', '3', '1', '0', '5', '3', '15', ''] | [
0,
3
] |
Let's call the set of positive integers S correct if the following two conditions are met: S \subseteq \{1, 2, ..., n\}; if a \in S and b \in S, then |a-b| \neq x and |a-b| \neq y. For the given values n, x, and y, you have to find the maximum size of the correct set. | Input: ['10 2 5', ''] Output:['5', ''] | [
3
] |
You have 2n integers 1, 2, ..., 2n. You have to redistribute these 2n elements into n pairs. After that, you choose x pairs and take minimum elements from them, and from the other n - x pairs, you take maximum elements.Your goal is to obtain the set of numbers \{b_1, b_2, ..., b_n\} as the result of taking elements from the pairs.What is the number of different x-s (0 <= x <= n) such that it's possible to obtain the set b if for each x you can choose how to distribute numbers into pairs and from which x pairs choose minimum elements? | Input: ['3', '1', '1', '5', '1 4 5 9 10', '2', '3 4', ''] Output:['1', '3', '1', ''] | [
2,
4
] |
You are given an array [a_1, a_2, ..., a_n] such that 1 <= a_i <= 10^9. Let S be the sum of all elements of the array a.Let's call an array b of n integers beautiful if: 1 <= b_i <= 10^9 for each i from 1 to n; for every pair of adjacent integers from the array (b_i, b_{i + 1}), either b_i divides b_{i + 1}, or b_{i + 1} divides b_i (or both); 2 \sum \limits_{i = 1}^{n} |a_i - b_i| <= S. Your task is to find any beautiful array. It can be shown that at least one beautiful array always exists. | Input: ['4', '5', '1 2 3 4 5', '2', '4 6', '2', '1 1000000000', '6', '3 4 8 1 2 3', ''] Output:['3 3 3 3 3', '3 6', '1 1000000000', '4 4 8 1 3 3', ''] | [
2
] |
You are playing a new computer game in which you have to fight monsters. In a dungeon you are trying to clear, you met three monsters; the first of them has a health points, the second has b health points, and the third has c.To kill the monsters, you can use a cannon that, when fired, deals 1 damage to the selected monster. Every 7-th (i. e. shots with numbers 7, 14, 21 etc.) cannon shot is enhanced and deals 1 damage to all monsters, not just one of them. If some monster's current amount of health points is 0, it can't be targeted by a regular shot and does not receive damage from an enhanced shot.You want to pass the dungeon beautifully, i. e., kill all the monsters with the same enhanced shot (i. e. after some enhanced shot, the health points of each of the monsters should become equal to 0 for the first time). Each shot must hit a monster, i. e. each shot deals damage to at least one monster. | Input: ['3', '3 2 4', '1 1 1', '10 1 7', ''] Output:['YES', 'NO', 'NO', ''] | [
3,
4
] |
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 <=q i <=q k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? | Input: ['4', '3', '1 4', '2 3', '3 6', '4', '1 2', '2 3', '3 5', '4 5', '5', '1 2', '3 8', '4 5', '6 7', '9 10', '5', '1 5', '2 4', '3 5', '3 8', '4 8', ''] Output:['0', '1', '2', '0', ''] | [
2,
4
] |
This is the hard version of this problem. The only difference between the easy and hard versions is the constraints on k and m. In this version of the problem, you need to output the answer by modulo 10^9+7.You are given a sequence a of length n consisting of integers from 1 to n. The sequence may contain duplicates (i.e. some elements can be equal).Find the number of tuples of m elements such that the maximum number in the tuple differs from the minimum by no more than k. Formally, you need to find the number of tuples of m indices i_1 < i_2 < ... < i_m, such that\max(a_{i_1}, a_{i_2}, ..., a_{i_m}) - \min(a_{i_1}, a_{i_2}, ..., a_{i_m}) <= k.For example, if n=4, m=3, k=2, a=[1,2,4,3], then there are two such triples (i=1, j=2, z=4 and i=2, j=3, z=4). If n=4, m=2, k=1, a=[1,1,1,1], then all six possible pairs are suitable.As the result can be very large, you should print the value modulo 10^9 + 7 (the remainder when divided by 10^9 + 7). | Input: ['4', '4 3 2', '1 2 4 3', '4 2 1', '1 1 1 1', '1 1 1', '1', '10 4 3', '5 6 1 3 2 9 8 1 2 4', ''] Output:['2', '6', '1', '20', ''] | [
3,
4
] |
This is the easy version of this problem. The only difference between easy and hard versions is the constraints on k and m (in this version k=2 and m=3). Also, in this version of the problem, you DON'T NEED to output the answer by modulo.You are given a sequence a of length n consisting of integers from 1 to n. The sequence may contain duplicates (i.e. some elements can be equal).Find the number of tuples of m = 3 elements such that the maximum number in the tuple differs from the minimum by no more than k = 2. Formally, you need to find the number of triples of indices i < j < z such that\max(a_i, a_j, a_z) - \min(a_i, a_j, a_z) <= 2.For example, if n=4 and a=[1,2,4,3], then there are two such triples (i=1, j=2, z=4 and i=2, j=3, z=4). If n=4 and a=[1,1,1,1], then all four possible triples are suitable. | Input: ['4', '4', '1 2 4 3', '4', '1 1 1 1', '1', '1', '10', '5 6 1 3 2 9 8 1 2 4', ''] Output:['2', '4', '0', '15', ''] | [
3,
4
] |
Polycarp was given an array of a[1 ... n] of n integers. He can perform the following operation with the array a no more than n times: Polycarp selects the index i and adds the value a_i to one of his choice of its neighbors. More formally, Polycarp adds the value of a_i to a_{i-1} or to a_{i+1} (if such a neighbor does not exist, then it is impossible to add to it). After adding it, Polycarp removes the i-th element from the a array. During this step the length of a is decreased by 1. The two items above together denote one single operation.For example, if Polycarp has an array a = [3, 1, 6, 6, 2], then it can perform the following sequence of operations with it: Polycarp selects i = 2 and adds the value a_i to (i-1)-th element: a = [4, 6, 6, 2]. Polycarp selects i = 1 and adds the value a_i to (i+1)-th element: a = [10, 6, 2]. Polycarp selects i = 3 and adds the value a_i to (i-1)-th element: a = [10, 8]. Polycarp selects i = 2 and adds the value a_i to (i-1)-th element: a = [18]. Note that Polycarp could stop performing operations at any time.Polycarp wondered how many minimum operations he would need to perform to make all the elements of a equal (i.e., he wants all a_i are equal to each other). | Input: ['4', '5', '3 1 6 6 2', '4', '1 2 2 1', '3', '2 2 2', '4', '6 3 2 1', ''] Output:['4', '2', '0', '2', ''] | [
2,
3
] |
You are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique). | Input: ['4', '1', '5', '15', '50', ''] Output:['1', '5', '69', '-1', ''] | [
0,
2,
3
] |
Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, ..., a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers in a way that would make the resulting expression's value as large as possible. To find out which symbols were available the teacher has given Barbara a string s which contained that information. It's easy to notice that Barbara has to place n - 1 symbols between numbers in total. The expression must start with a number and all symbols must be allowed (i.e. included in s). Note that multiplication takes precedence over addition or subtraction, addition and subtraction have the same priority and performed from left to right. Help Barbara and create the required expression! | Input: ['3', '2 2 0', '+-*', ''] Output:['2*2-0', ''] | [
2
] |
In recent years John has very successfully settled at his new job at the office. But John doesn't like to idly sit around while his code is compiling, so he immediately found himself an interesting distraction. The point of his distraction was to maintain a water level in the water cooler used by other zebras. Originally the cooler contained exactly k liters of water. John decided that the amount of water must always be at least l liters of water but no more than r liters. John will stay at the office for exactly t days. He knows that each day exactly x liters of water will be used by his colleagues. At the beginning of each day he can add exactly y liters of water to the cooler, but at any point in time the amount of water in the cooler must be in the range [l, r].Now John wants to find out whether he will be able to maintain the water level at the necessary level for t days. Help him answer this question! | Input: ['8 1 10 2 6 4', ''] Output:['No', ''] | [
0,
2,
3
] |
Mike received an array a of length n as a birthday present and decided to test how pretty it is.An array would pass the i-th prettiness test if there is a way to get an array with a sum of elements totaling s_i, using some number (possibly zero) of slicing operations. An array slicing operation is conducted in the following way: assume mid = \lfloor\frac{max(array) + min(array)}{2}\rfloor, where max and min β are functions that find the maximum and the minimum array elements. In other words, mid is the sum of the maximum and the minimum element of array divided by 2 rounded down. Then the array is split into two parts \mathit{left} and right. The \mathit{left} array contains all elements which are less than or equal mid, and the right array contains all elements which are greater than mid. Elements in \mathit{left} and right keep their relative order from array. During the third step we choose which of the \mathit{left} and right arrays we want to keep. The chosen array replaces the current one and the other is permanently discarded. You need to help Mike find out the results of q prettiness tests.Note that you test the prettiness of the array a, so you start each prettiness test with the primordial (initial) array a. Thus, the first slice (if required) is always performed on the array a. | Input: ['2', '5 5', '1 2 3 4 5', '1', '8', '9', '12', '6', '5 5', '3 1 3 1 3', '1', '2', '3', '9', '11', ''] Output:['Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', ''] | [
0,
4
] |
Ron is a happy owner of a permutation a of length n.A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data.As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged.You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. | Input: ['4', '4 3', '4 3 2 1', '1 0.3', '3 1', '4 0.6', '5 3', '4 2 1 3 5', '3 0.8', '4 0.6', '5 0.3', '6 5', '1 3 2 4 5 6', '4 0.9', '5 0.3', '2 0.4', '6 0.7', '3 0.5', '4 2', '1 2 3 4', '2 0.5', '4 0.1', ''] Output:['0.600000', '0.720000', '0.989500', '1.000000', ''] | [
3
] |
Holidays are coming up really soon. Rick realized that it's time to think about buying a traditional spruce tree. But Rick doesn't want real trees to get hurt so he decided to find some in an n * m matrix consisting of "*" and ".". To find every spruce first let's define what a spruce in the matrix is. A set of matrix cells is called a spruce of height k with origin at point (x, y) if: All cells in the set contain an "*". For each 1 <= i <= k all cells with the row number x+i-1 and columns in range [y - i + 1, y + i - 1] must be a part of the set. All other cells cannot belong to the set. Examples of correct and incorrect spruce trees: Now Rick wants to know how many spruces his n * m matrix contains. Help Rick solve this problem. | Input: ['4', '2 3', '.*.', '***', '2 3', '.*.', '**.', '4 5', '.***.', '*****', '*****', '*.*.*', '5 7', '..*.*..', '.*****.', '*******', '.*****.', '..*.*..', ''] Output:['5', '3', '23', '34', ''] | [
0
] |
One fall day Joe got bored because he couldn't find himself something interesting to do. Marty suggested Joe to generate a string of length n to entertain him somehow. It didn't seem particularly difficult, but Joe's generated string had to follow these rules: the string may only contain characters 'a', 'b', or 'c'; the maximum length of a substring of this string that is a palindrome does not exceed k. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. For example, strings "a", "bc", "abc" are substrings of a string "abc", while strings "ac", "ba", "cba" are not.A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, strings "abccba", "abbba", "aba", "abacaba", "a", and "bacab" are palindromes, while strings "abcbba", "abb", and "ab" are not.Now Joe wants to find any correct string. Help him! It can be proven that the answer always exists under the given constraints. | Input: ['2', '3 2', '4 1', ''] Output:['aab', 'acba', ''] | [
2
] |
A robot is standing at the origin of the infinite two-dimensional plane. Each second the robot moves exactly 1 meter in one of the four cardinal directions: north, south, west, and east. For the first step the robot can choose any of the four directions, but then at the end of every second it has to turn 90 degrees left or right with respect to the direction it just moved in. For example, if the robot has just moved north or south, the next step it takes has to be either west or east, and vice versa.The robot makes exactly n steps from its starting position according to the rules above. How many different points can the robot arrive to at the end? The final orientation of the robot can be ignored. | Input: ['1', ''] Output:['4', ''] | [
3
] |
There are n cards numbered 1, ..., n. The card i has a red digit r_i and a blue digit b_i written on it.We arrange all n cards in random order from left to right, with all permutations of 1, ..., n having the same probability. We then read all red digits on the cards from left to right, and obtain an integer R. In the same way, we read all blue digits and obtain an integer B. When reading a number, leading zeros can be ignored. If all digits in a number are zeros, then the number is equal to 0. Below is an illustration of a possible rearrangement of three cards, and how R and B can be found. Two players, Red and Blue, are involved in a bet. Red bets that after the shuffle R > B, and Blue bets that R < B. If in the end R = B, the bet results in a draw, and neither player wins.Determine, which of the two players is more likely (has higher probability) to win the bet, or that their chances are equal. Refer to the Note section for a formal discussion of comparing probabilities. | Input: ['3', '3', '777', '111', '3', '314', '159', '5', '09281', '09281', ''] Output:['RED', 'BLUE', 'EQUAL', ''] | [
3
] |
You are given a string s of 0's and 1's. You are allowed to perform the following operation: choose a non-empty contiguous substring of s that contains an equal number of 0's and 1's; flip all characters in the substring, that is, replace all 0's with 1's, and vice versa; reverse the substring. For example, consider s = 00111011, and the following operation: Choose the first six characters as the substring to act upon: 00111011. Note that the number of 0's and 1's are equal, so this is a legal choice. Choosing substrings 0, 110, or the entire string would not be possible. Flip all characters in the substring: 11000111. Reverse the substring: 10001111. Find the lexicographically smallest string that can be obtained from s after zero or more operations. | Input: ['3', '100101', '1100011', '10101010', ''] Output:['010110', '0110110', '10101010', ''] | [
2
] |
You are given a square matrix of size n. Every row and every column of this matrix is a permutation of 1, 2, ..., n. Let a_{i, j} be the element at the intersection of i-th row and j-th column for every 1 <=q i, j <=q n. Rows are numbered 1, ..., n top to bottom, and columns are numbered 1, ..., n left to right.There are six types of operations: R: cyclically shift all columns to the right, formally, set the value of each a_{i, j} to a_{i, ((j - 2)\bmod n) + 1}; L: cyclically shift all columns to the left, formally, set the value of each a_{i, j} to a_{i, (j\bmod n) + 1}; D: cyclically shift all rows down, formally, set the value of each a_{i, j} to a_{((i - 2)\bmod n) + 1, j}; U: cyclically shift all rows up, formally, set the value of each a_{i, j} to a_{(i\bmod n) + 1, j}; I: replace the permutation read left to right in each row with its inverse. C: replace the permutation read top to bottom in each column with its inverse. Inverse of a permutation p_1, p_2, ..., p_n is a permutation q_1, q_2, ..., q_n, such that p_{q_i} = i for every 1 <=q i <=q n.One can see that after any sequence of operations every row and every column of the matrix will still be a permutation of 1, 2, ..., n.Given the initial matrix description, you should process m operations and output the final matrix. | Input: ['5', '3 2', '1 2 3', '2 3 1', '3 1 2', 'DR', '3 2', '1 2 3', '2 3 1', '3 1 2', 'LU', '3 1', '1 2 3', '2 3 1', '3 1 2', 'I', '3 1', '1 2 3', '2 3 1', '3 1 2', 'C', '3 16', '1 2 3', '2 3 1', '3 1 2', 'LDICRUCILDICRUCI', ''] Output:['2 3 1 ', '3 1 2 ', '1 2 3 ', '', '3 1 2 ', '1 2 3 ', '2 3 1 ', '', '1 2 3 ', '3 1 2 ', '2 3 1 ', '', '1 3 2 ', '2 1 3 ', '3 2 1 ', '', '2 3 1 ', '3 1 2 ', '1 2 3', ''] | [
3
] |
You are given two positive integer sequences a_1, ..., a_n and b_1, ..., b_m. For each j = 1, ..., m find the greatest common divisor of a_1 + b_j, ..., a_n + b_j. | Input: ['4 4', '1 25 121 169', '1 2 7 23', ''] Output:['2 3 8 24', ''] | [
3
] |
Given integers c_{0}, c_{1}, ..., c_{k-1} we can define the cost of a number 0 <= x < 2^{k} as p(x) = \sum_{i=0}^{k-1} <=ft( <=ft\lfloor \frac{x}{2^{i}} \right\rfloor \bmod 2 \right) \cdot c_{i}. In other words, the cost of number x is the sum of c_{i} over the bits of x which are equal to one.Let's define the cost of array a of length n >= 2 with elements from [0, 2^{k}) as follows: cost(a) = \sum_{i=1}^{n - 1} p(a_{i} \oplus a_{i+1}), where \oplus denotes bitwise exclusive OR operation.You have to construct an array of length n with minimal cost, given that each element should belong to the given segment: l_{i} <= a_{i} <= r_{i}. | Input: ['4 3', '3 3', '5 5', '6 6', '1 1', '5 2 7', ''] Output:['30', ''] | [
2
] |
You are given a string s consisting of n characters. These characters are among the first k lowercase letters of the Latin alphabet. You have to perform n operations with the string.During the i-th operation, you take the character that initially occupied the i-th position, and perform one of the following actions with it: swap it with the previous character in the string (if it exists). This operation is represented as L; swap it with the next character in the string (if it exists). This operation is represented as R; cyclically change it to the previous character in the alphabet (b becomes a, c becomes b, and so on; a becomes the k-th letter of the Latin alphabet). This operation is represented as D; cyclically change it to the next character in the alphabet (a becomes b, b becomes c, and so on; the k-th letter of the Latin alphabet becomes a). This operation is represented as U; do nothing. This operation is represented as 0. For example, suppose the initial string is test, k = 20, and the sequence of operations is URLD. Then the string is transformed as follows: the first operation is U, so we change the underlined letter in test to the next one in the first 20 Latin letters, which is a. The string is now aest; the second operation is R, so we swap the underlined letter with the next one in the string aest. The string is now aset; the third operation is L, so we swap the underlined letter with the previous one in the string aset (note that this is now the 2-nd character of the string, but it was initially the 3-rd one, so the 3-rd operation is performed to it). The resulting string is saet; the fourth operation is D, so we change the underlined letter in saet to the previous one in the first 20 Latin letters, which is s. The string is now saes. The result of performing the sequence of operations is saes.Given the string s and the value of k, find the lexicographically smallest string that can be obtained after applying a sequence of operations to s. | Input: ['6', '4 2', 'bbab', '7 5', 'cceddda', '6 5', 'ecdaed', '7 4', 'dcdbdaa', '8 3', 'ccabbaca', '5 7', 'eabba', ''] Output:['aaaa', 'baccacd', 'aabdac', 'aabacad', 'aaaaaaaa', 'abadb', ''] | [
2
] |
You are given four different integer points p_1, p_2, p_3 and p_4 on \mathit{XY} grid.In one step you can choose one of the points p_i and move it in one of four directions by one. In other words, if you have chosen point p_i = (x, y) you can move it to (x, y + 1), (x, y - 1), (x + 1, y) or (x - 1, y).Your goal to move points in such a way that they will form a square with sides parallel to \mathit{OX} and \mathit{OY} axes (a square with side 0 is allowed).What is the minimum number of steps you need to make such a square? | Input: ['3', '0 2', '4 2', '2 0', '2 4', '1 0', '2 0', '4 0', '6 0', '1 6', '2 2', '2 5', '4 1', ''] Output:['8', '7', '5', ''] | [
0,
2,
3
] |
You are given a sequence a consisting of n integers a_1, a_2, ..., a_n, and an integer x. Your task is to make the sequence a sorted (it is considered sorted if the condition a_1 <= a_2 <= a_3 <= ... <= a_n holds).To make the sequence sorted, you may perform the following operation any number of times you want (possibly zero): choose an integer i such that 1 <= i <= n and a_i > x, and swap the values of a_i and x.For example, if a = [0, 2, 3, 5, 4], x = 1, the following sequence of operations is possible: choose i = 2 (it is possible since a_2 > x), then a = [0, 1, 3, 5, 4], x = 2; choose i = 3 (it is possible since a_3 > x), then a = [0, 1, 2, 5, 4], x = 3; choose i = 4 (it is possible since a_4 > x), then a = [0, 1, 2, 3, 4], x = 5. Calculate the minimum number of operations you have to perform so that a becomes sorted, or report that it is impossible. | Input: ['6', '4 1', '2 3 5 4', '5 6', '1 1 3 4 4', '1 10', '2', '2 10', '11 9', '2 10', '12 11', '5 18', '81 324 218 413 324', ''] Output:['3', '0', '0', '-1', '1', '3', ''] | [
2
] |
Alice and Bob play ping-pong with simplified rules.During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.The one who doesn't make a return loses this play. The winner of the play commences the next play. Alice starts the first play.Alice has x stamina and Bob has y. To hit the ball (while serving or returning) each player spends 1 stamina, so if they don't have any stamina, they can't return the ball (and lose the play) or can't serve the ball (in this case, the other player serves the ball instead). If both players run out of stamina, the game is over.Sometimes, it's strategically optimal not to return the ball, lose the current play, but save the stamina. On the contrary, when the server commences a play, they have to hit the ball, if they have some stamina left.Both Alice and Bob play optimally and want to, firstly, maximize their number of wins and, secondly, minimize the number of wins of their opponent.Calculate the resulting number of Alice's and Bob's wins. | Input: ['3', '1 1', '2 1', '1 7', ''] Output:['0 1', '1 1', '0 7', ''] | [
3
] |
You are standing on the \mathit{OX}-axis at point 0 and you want to move to an integer point x > 0.You can make several jumps. Suppose you're currently at point y (y may be negative) and jump for the k-th time. You can: either jump to the point y + k or jump to the point y - 1. What is the minimum number of jumps you need to reach the point x? | Input: ['5', '1', '2', '3', '4', '5', ''] Output:['1', '3', '2', '3', '4', ''] | [
3
] |
Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111.Let's define another function g(x) = \dfrac{x}{f(f(x))} (x is a positive integer as well).Your task is the following: for the given positive integer n, calculate the number of different values of g(x) among all numbers x such that 1 <= x <= n. | Input: ['5', '4', '37', '998244353', '1000000007', '12345678901337426966631415', ''] Output:['1', '2', '9', '10', '26', ''] | [
3
] |
You are given an array a consisting of n integers.Let min(l, r) be the minimum value among a_l, a_{l + 1}, ..., a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, ..., a_r.Your task is to choose three positive (greater than 0) integers x, y and z such that: x + y + z = n; max(1, x) = min(x + 1, x + y) = max(x + y + 1, n). In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).Among all such triples (partitions), you can choose any.You have to answer t independent test cases. | Input: ['6', '11', '1 2 3 3 3 4 4 3 4 2 1', '8', '2 9 1 7 3 9 4 1', '9', '2 1 4 2 4 3 3 1 2', '7', '4 2 1 1 4 1 4', '5', '1 1 1 1 1', '7', '4 3 4 3 3 3 4', ''] Output:['YES', '6 1 4', 'NO', 'YES', '2 5 2', 'YES', '4 1 2', 'YES', '1 1 3', 'YES', '2 1 4', ''] | [
2,
4
] |
You are given an integer n (n > 1).Your task is to find a sequence of integers a_1, a_2, ..., a_k such that: each a_i is strictly greater than 1; a_1 \cdot a_2 \cdot ... \cdot a_k = n (i. e. the product of this sequence is n); a_{i + 1} is divisible by a_i for each i from 1 to k-1; k is the maximum possible (i. e. the length of this sequence is the maximum possible). If there are several such sequences, any of them is acceptable. It can be proven that at least one valid sequence always exists for any integer n > 1.You have to answer t independent test cases. | Input: ['4', '2', '360', '4999999937', '4998207083', ''] Output:['1', '2 ', '3', '2 2 90 ', '1', '4999999937 ', '1', '4998207083 ', ''] | [
3
] |
You are given a sequence a, initially consisting of n integers.You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i!=x if l <= i <= r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).Note that you can not change x after you chose it.For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then: choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2]; choose l = 3, r = 3, so the resulting sequence is a = [1, 1]. Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.Your task is to find the minimum number of operations required to transform the sequence in a way described above.You have to answer t independent test cases. | Input: ['5', '3', '1 1 1', '5', '1 2 3 4 5', '5', '1 2 3 2 1', '7', '1 2 3 1 2 3 1', '11', '2 2 1 2 3 2 1 2 3 1 2', ''] Output:['0', '1', '1', '2', '3', ''] | [
2
] |
Gildong is playing with his dog, Badugi. They're at a park that has n intersections and n-1 bidirectional roads, each 1 meter in length and connecting two intersections with each other. The intersections are numbered from 1 to n, and for every a and b (1 <= a, b <= n), it is possible to get to the b-th intersection from the a-th intersection using some set of roads.Gildong has put one snack at every intersection of the park. Now Gildong will give Badugi a mission to eat all of the snacks. Badugi starts at the 1-st intersection, and he will move by the following rules: Badugi looks for snacks that are as close to him as possible. Here, the distance is the length of the shortest path from Badugi's current location to the intersection with the snack. However, Badugi's sense of smell is limited to k meters, so he can only find snacks that are less than or equal to k meters away from himself. If he cannot find any such snack, he fails the mission. Among all the snacks that Badugi can smell from his current location, he chooses a snack that minimizes the distance he needs to travel from his current intersection. If there are multiple such snacks, Badugi will choose one arbitrarily. He repeats this process until he eats all n snacks. After that, he has to find the 1-st intersection again which also must be less than or equal to k meters away from the last snack he just ate. If he manages to find it, he completes the mission. Otherwise, he fails the mission. Unfortunately, Gildong doesn't know the value of k. So, he wants you to find the minimum value of k that makes it possible for Badugi to complete his mission, if Badugi moves optimally. | Input: ['3', '3', '1 2', '1 3', '4', '1 2', '2 3', '3 4', '8', '1 2', '2 3', '3 4', '1 5', '5 6', '6 7', '5 8', ''] Output:['2', '3', '3', ''] | [
2,
4
] |
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the expected number of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}. | Input: ['4', '1', '2', '8', '12', ''] Output:['-1', '1', '1', '4', '1 1 1 1', '5', '1 1 0 1 1', ''] | [
0,
2,
3
] |
Gildong has a square board consisting of n rows and n columns of square cells, each consisting of a single digit (from 0 to 9). The cell at the j-th column of the i-th row can be represented as (i, j), and the length of the side of each cell is 1. Gildong likes big things, so for each digit d, he wants to find a triangle such that: Each vertex of the triangle is in the center of a cell. The digit of every vertex of the triangle is d. At least one side of the triangle is parallel to one of the sides of the board. You may assume that a side of length 0 is parallel to both sides of the board. The area of the triangle is maximized. Of course, he can't just be happy with finding these triangles as is. Therefore, for each digit d, he's going to change the digit of exactly one cell of the board to d, then find such a triangle. He changes it back to its original digit after he is done with each digit. Find the maximum area of the triangle he can make for each digit.Note that he can put multiple vertices of the triangle on the same cell, and the triangle can be a degenerate triangle; i.e. the area of the triangle can be 0. Also, note that he is allowed to change the digit of a cell from d to d. | Input: ['5', '3', '000', '122', '001', '2', '57', '75', '4', '0123', '4012', '3401', '2340', '1', '9', '8', '42987101', '98289412', '38949562', '87599023', '92834718', '83917348', '19823743', '38947912', ''] Output:['4 4 1 0 0 0 0 0 0 0', '0 0 0 0 0 1 0 1 0 0', '9 6 9 9 6 0 0 0 0 0', '0 0 0 0 0 0 0 0 0 0', '18 49 49 49 49 15 0 30 42 42', ''] | [
2
] |
Alice and Bob are playing a game. They have a tree consisting of n vertices. Initially, Bob has k chips, the i-th chip is located in the vertex a_i (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree.The game consists of turns. Each turn, the following events happen (sequentially, exactly in the following order): Alice either moves her chip to an adjacent vertex or doesn't move it; for each Bob's chip, he either moves it to an adjacent vertex or doesn't move it. Note that this choice is done independently for each chip. The game ends when Alice's chip shares the same vertex with one (or multiple) of Bob's chips. Note that Bob's chips may share the same vertex, even though they are in different vertices at the beginning of the game.Alice wants to maximize the number of turns, Bob wants to minimize it. If the game ends in the middle of some turn (Alice moves her chip to a vertex that contains one or multiple Bob's chips), this turn is counted.For each vertex, calculate the number of turns the game will last if Alice places her chip in that vertex. | Input: ['5', '2 4', '3 1', '3 4', '3 5', '2', '4 5', ''] Output:['2 1 2 0 0', ''] | [
2
] |
You are given a multiset of powers of two. More precisely, for each i from 0 to n exclusive you have cnt_i elements equal to 2^i.In one operation, you can choose any one element 2^l > 1 and divide it into two elements 2^{l - 1}.You should perform q queries. Each query has one of two types: "1 pos val" β assign cnt_{pos} := val; "2 x k" β calculate the minimum number of operations you need to make at least k elements with value lower or equal to 2^x. Note that all queries of the second type don't change the multiset; that is, you just calculate the minimum number of operations, you don't perform them. | Input: ['6 11', '0 1 0 0 1 0', '2 1 5', '2 4 18', '1 1 0', '2 2 5', '2 0 17', '1 0 3', '2 1 2', '1 1 4', '1 4 0', '1 5 1', '2 2 8', ''] Output:['4', '16', '4', '-1', '0', '1', ''] | [
2
] |
Berland regional ICPC contest has just ended. There were m participants numbered from 1 to m, who competed on a problemset of n problems numbered from 1 to n.Now the editorial is about to take place. There are two problem authors, each of them is going to tell the tutorial to exactly k consecutive tasks of the problemset. The authors choose the segment of k consecutive tasks for themselves independently of each other. The segments can coincide, intersect or not intersect at all.The i-th participant is interested in listening to the tutorial of all consecutive tasks from l_i to r_i. Each participant always chooses to listen to only the problem author that tells the tutorials to the maximum number of tasks he is interested in. Let this maximum number be a_i. No participant can listen to both of the authors, even if their segments don't intersect.The authors want to choose the segments of k consecutive tasks for themselves in such a way that the sum of a_i over all participants is maximized. | Input: ['10 5 3', '1 3', '2 4', '6 9', '6 9', '1 8', ''] Output:['14', ''] | [
0,
2
] |
There are n + 2 towns located on a coordinate line, numbered from 0 to n + 1. The i-th town is located at the point i.You build a radio tower in each of the towns 1, 2, ..., n with probability \frac{1}{2} (these events are independent). After that, you want to set the signal power on each tower to some integer from 1 to n (signal powers are not necessarily the same, but also not necessarily different). The signal from a tower located in a town i with signal power p reaches every city c such that |c - i| < p.After building the towers, you want to choose signal powers in such a way that: towns 0 and n + 1 don't get any signal from the radio towers; towns 1, 2, ..., n get signal from exactly one radio tower each. For example, if n = 5, and you have built the towers in towns 2, 4 and 5, you may set the signal power of the tower in town 2 to 2, and the signal power of the towers in towns 4 and 5 to 1. That way, towns 0 and n + 1 don't get the signal from any tower, towns 1, 2 and 3 get the signal from the tower in town 2, town 4 gets the signal from the tower in town 4, and town 5 gets the signal from the tower in town 5.Calculate the probability that, after building the towers, you will have a way to set signal powers to meet all constraints. | Input: ['2', ''] Output:['748683265', ''] | [
3
] |
You are given a string s, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string s (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform? | Input: ['5', '()', '[]()', '([)]', ')]([', ')[(]', ''] Output:['1', '2', '2', '0', '1', ''] | [
2
] |
You are asked to watch your nephew who likes to play with toy blocks in a strange way.He has n boxes and the i-th box has a_i blocks. His game consists of two steps: he chooses an arbitrary box i; he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes.You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? | Input: ['3', '3', '3 2 2', '4', '2 2 3 2', '3', '0 3 0', ''] Output:['1', '0', '3', ''] | [
2,
3,
4
] |
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute: move north from cell (i, j) to (i, j + 1); move east from cell (i, j) to (i + 1, j); move south from cell (i, j) to (i, j - 1); move west from cell (i, j) to (i - 1, j); stay in cell (i, j). The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.What is the minimum number of commands required to reach (x, y) from (0, 0)? | Input: ['5', '5 5', '3 4', '7 1', '0 0', '2 0', ''] Output:['10', '7', '13', '0', '3', ''] | [
3
] |
The only difference between the easy and hard versions is the constraints on the number of queries.This is an interactive problem.Ridbit has a hidden array a of n integers which he wants Ashish to guess. Note that n is a power of two. Ashish is allowed to ask three different types of queries. They are of the form AND i j: ask for the bitwise AND of elements a_i and a_j (1 <=q i, j <= n, i \neq j) OR i j: ask for the bitwise OR of elements a_i and a_j (1 <=q i, j <= n, i \neq j) XOR i j: ask for the bitwise XOR of elements a_i and a_j (1 <=q i, j <= n, i \neq j) Can you help Ashish guess the elements of the array?In this version, each element takes a value in the range [0, n-1] (inclusive) and Ashish can ask no more than n+1 queries. | Input: ['4', '', '0', '', '2', '', '3', '', ''] Output:['OR 1 2', '', 'OR 2 3', '', 'XOR 2 4', '', '! 0 0 2 3', ''] | [
3
] |
The only difference between the easy and hard versions is the constraints on the number of queries.This is an interactive problem.Ridbit has a hidden array a of n integers which he wants Ashish to guess. Note that n is a power of two. Ashish is allowed to ask three different types of queries. They are of the form AND i j: ask for the bitwise AND of elements a_i and a_j (1 <=q i, j <= n, i \neq j) OR i j: ask for the bitwise OR of elements a_i and a_j (1 <=q i, j <= n, i \neq j) XOR i j: ask for the bitwise XOR of elements a_i and a_j (1 <=q i, j <= n, i \neq j) Can you help Ashish guess the elements of the array?In this version, each element takes a value in the range [0, n-1] (inclusive) and Ashish can ask no more than n+2 queries. | Input: ['4', '', '0', '', '2', '', '3', '', ''] Output:['OR 1 2', '', 'OR 2 3', '', 'XOR 2 4', '', '! 0 0 2 3', ''] | [
3
] |
Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first.Consider the 2D plane. There is a token which is initially at (0,0). In one move a player must increase either the x coordinate or the y coordinate of the token by exactly k. In doing so, the player must ensure that the token stays within a (Euclidean) distance d from (0,0).In other words, if after a move the coordinates of the token are (p,q), then p^2 + q^2 <=q d^2 must hold.The game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win. | Input: ['5', '2 1', '5 2', '10 3', '25 4', '15441 33', ''] Output:['Utkarsh', 'Ashish', 'Utkarsh', 'Utkarsh', 'Ashish', ''] | [
3
] |
Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters.He wants to convert string a into string b by performing some (possibly zero) operations on a.In one move, he can either choose an index i (1 <=q i<=q n-1) and swap a_i and a_{i+1}, or choose an index i (1 <=q i <=q n-k+1) and if a_i, a_{i+1}, ..., a_{i+k-1} are all equal to some character c (c \neq 'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. | Input: ['4', '3 3', 'abc', 'bcd', '4 2', 'abba', 'azza', '2 1', 'zz', 'aa', '6 2', 'aaabba', 'ddddcc', ''] Output:['No', 'Yes', 'No', 'Yes', ''] | [
2
] |
Hr0d1y has q queries on a binary string s of length n. A binary string is a string containing only characters '0' and '1'.A query is described by a pair of integers l_i, r_i (1 <=q l_i \lt r_i <=q n). For each query, he has to determine whether there exists a good subsequence in s that is equal to the substring s[l_i... r_i]. A substring s[i... j] of a string s is the string formed by characters s_i s_{i+1} ... s_j. String a is said to be a subsequence of string b if a can be obtained from b by deleting some characters without changing the order of the remaining characters. A subsequence is said to be good if it is not contiguous and has length >= 2. For example, if s is "1100110", then the subsequences s_1s_2s_4 ("1100110") and s_1s_5s_7 ("1100110") are good, while s_1s_2s_3 ("1100110") is not good. Can you help Hr0d1y answer each query? | Input: ['2', '6 3', '001000', '2 4', '1 3', '3 5', '4 2', '1111', '1 4', '2 3', ''] Output:['YES', 'NO', 'YES', 'NO', 'YES', ''] | [
2
] |
Ridbit starts with an integer n.In one move, he can perform one of the following operations: divide n by one of its proper divisors, or subtract 1 from n if n is greater than 1. A proper divisor is a divisor of a number, excluding itself. For example, 1, 2, 4, 5, and 10 are proper divisors of 20, but 20 itself is not.What is the minimum number of moves Ridbit is required to make to reduce n to 1? | Input: ['6', '1', '2', '3', '4', '6', '9', ''] Output:['0', '1', '2', '2', '2', '3', ''] | [
2,
3
] |
The only difference between the two versions of the problem is that there are no updates in the easy version.There are n spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white.For any two spools of the same color, you can attach them with a thread of that color in a straight line segment. Define a matching as a way to attach spools together so that each spool is attached to exactly one other spool.Coloring is an assignment of colors (white and black) to the spools. A coloring is called valid if it has at least one matching. That is if the number of black spools and the number of white spools are both even.Given a matching, we can find the number of times some white thread intersects some black thread. We compute the number of pairs of differently colored threads that intersect instead of the number of intersection points, so one intersection point may be counted multiple times if different pairs of threads intersect at the same point. If c is a valid coloring, let f(c) denote the minimum number of such intersections out of all possible matchings. The circle above is described by the coloring bwbbbwww. After matching the spools as shown, there is one intersection between differently colored threads. It can be proven that it is the minimum possible, so f(\text{bwbbbwww}) = 1. You are given a string s representing an unfinished coloring, with black, white, and uncolored spools. A coloring c is called s-reachable if you can achieve it by assigning colors to the uncolored spools of s without changing the others.A coloring c is chosen uniformly at random among all valid, s-reachable colorings. Compute the expected value of f(c). You should find it by modulo 998244353.There will be m updates to change one character of s. After each update, you should again compute the expected value of f(c).We can show that each answer can be written in the form \frac{p}{q} where p and q are relatively prime integers and q\not\equiv 0\pmod{998244353}. The answer by modulo 998244353 is equal to (p\cdot q^{-1}) modulo 998244353. | Input: ['8 0', 'bwbb?www', ''] Output:['1', ''] | [
3
] |
The only difference between the two versions of the problem is that there are no updates in the easy version.There are n spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white.For any two spools of the same color, you can attach them with a thread of that color in a straight line segment. Define a matching as a way to attach spools together so that each spool is attached to exactly one other spool.Coloring is an assignment of colors (white and black) to the spools. A coloring is called valid if it has at least one matching. That is if the number of black spools and the number of white spools are both even.Given a matching, we can find the number of times some white thread intersects some black thread. We compute the number of pairs of differently colored threads that intersect instead of the number of intersection points, so one intersection point may be counted multiple times if different pairs of threads intersect at the same point. If c is a valid coloring, let f(c) denote the minimum number of such intersections out of all possible matchings. The circle above is described by the coloring bwbbbwww. After matching the spools as shown, there is one intersection between differently colored threads. It can be proven that it is the minimum possible, so f(\text{bwbbbwww}) = 1. You are given a string s representing an unfinished coloring, with black, white, and uncolored spools. A coloring c is called s-reachable if you can achieve it by assigning colors to the uncolored spools of s without changing the others.A coloring c is chosen uniformly at random among all valid, s-reachable colorings. Compute the expected value of f(c). You should find it by modulo 998244353.We can show that the answer can be written in the form \frac{p}{q} where p and q are relatively prime integers and q\not\equiv 0\pmod{998244353}. The answer by modulo 998244353 is equal to (p\cdot q^{-1}) modulo 998244353. | Input: ['8 0', 'bwbb?www', ''] Output:['1', ''] | [
3
] |
To help those contestants who struggle a lot in contests, the headquarters of Codeforces are planning to introduce Division 5. In this new division, the tags of all problems will be announced prior to the round to help the contestants.The contest consists of n problems, where the tag of the i-th problem is denoted by an integer a_i.You want to AK (solve all problems). To do that, you must solve the problems in some order. To make the contest funnier, you created extra limitations on yourself. You do not want to solve two problems consecutively with the same tag since it is boring. Also, you are afraid of big jumps in difficulties while solving them, so you want to minimize the number of times that you solve two problems consecutively that are not adjacent in the contest order.Formally, your solve order can be described by a permutation p of length n. The cost of a permutation is defined as the number of indices i (1<= i<n) where |p_{i+1}-p_i|>1. You have the requirement that a_{p_i}\ne a_{p_{i+1}} for all 1<= i< n.You want to know the minimum possible cost of permutation that satisfies the requirement. If no permutations meet this requirement, you should report about it. | Input: ['4', '6', '2 1 2 3 1 1', '5', '1 1 1 2 2', '8', '7 7 2 7 7 1 8 7', '10', '1 2 3 4 1 1 2 3 4 1', ''] Output:['1', '3', '-1', '2', ''] | [
2
] |
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that b_j =\min_{j<= i<= j+k-1}a_iFor example, the 3-compression array of [1, 3, 4, 5, 2] is [\min\{1, 3, 4\}, \min\{3, 4, 5\}, \min\{4, 5, 2\}]=[1, 3, 2].A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1<=q k<=q n if CodeCook users will be happy after a k-compression of this array or not. | Input: ['5', '5', '1 5 3 4 2', '4', '1 3 2 1', '5', '1 3 3 3 2', '10', '1 2 3 4 5 6 7 8 9 10', '3', '3 3 2', ''] Output:['10111', '0001', '00111', '1111111111', '000', ''] | [
2,
4
] |
The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces.In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell of the grid is either empty or contains a token. There are two types of tokens: X and O. If there exist three tokens of the same type consecutive in a row or column, it is a winning configuration. Otherwise, it is a draw configuration. The patterns in the first row are winning configurations. The patterns in the second row are draw configurations. In an operation, you can change an X to an O, or an O to an X. Let k denote the total number of tokens in the grid. Your task is to make the grid a draw in at most \lfloor \frac{k}{3}\rfloor (rounding down) operations.You are not required to minimize the number of operations. | Input: ['3', '3', '.O.', 'OOO', '.O.', '6', 'XXXOOO', 'XXXOOO', 'XX..OO', 'OO..XX', 'OOOXXX', 'OOOXXX', '5', '.OOO.', 'OXXXO', 'OXXXO', 'OXXXO', '.OOO.', ''] Output:['.O.', 'OXO', '.O.', 'OXXOOX', 'XOXOXO', 'XX..OO', 'OO..XX', 'OXOXOX', 'XOOXXO', '.OXO.', 'OOXXO', 'XXOXX', 'OXXOO', '.OXO.'] | [
3
] |
The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces.In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell of the grid is either empty or contains a token. There are two types of tokens: X and O. If there exist three tokens of the same type consecutive in a row or column, it is a winning configuration. Otherwise, it is a draw configuration. The patterns in the first row are winning configurations. The patterns in the second row are draw configurations. In an operation, you can change an X to an O, or an O to an X. Let k denote the total number of tokens in the grid. Your task is to make the grid a draw in at most \lfloor \frac{k}{3}\rfloor (rounding down) operations.You are not required to minimize the number of operations. | Input: ['3', '3', '.X.', 'XXX', '.X.', '6', 'XX.XXX', 'XXXXXX', 'XXX.XX', 'XXXXXX', 'XX.X.X', 'XXXXXX', '5', 'XXX.X', '.X..X', 'XXX.X', '..X..', '..X..', ''] Output:['.X.', 'XOX', '.X.', 'XX.XXO', 'XOXXOX', 'OXX.XX', 'XOOXXO', 'XX.X.X', 'OXXOXX', 'XOX.X', '.X..X', 'XXO.O', '..X..', '..X..', ''] | [
3
] |
You have n distinct points (x_1, y_1),...,(x_n,y_n) on the plane and a non-negative integer parameter k. Each point is a microscopic steel ball and k is the attract power of a ball when it's charged. The attract power is the same for all balls.In one operation, you can select a ball i to charge it. Once charged, all balls with Manhattan distance at most k from ball i move to the position of ball i. Many balls may have the same coordinate after an operation.More formally, for all balls j such that |x_i - x_j| + |y_i - y_j| <= k, we assign x_j:=x_i and y_j:=y_i. An example of an operation. After charging the ball in the center, two other balls move to its position. On the right side, the red dot in the center is the common position of those balls. Your task is to find the minimum number of operations to move all balls to the same position, or report that this is impossible. | Input: ['3', '3 2', '0 0', '3 3', '1 1', '3 3', '6 7', '8 8', '6 9', '4 1', '0 0', '0 1', '0 2', '0 3', ''] Output:['-1', '1', '-1', ''] | [
0,
2
] |
You are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it.You can perform the following operation any number of times (possibly zero): Choose any two adjacent cells and multiply the values in them by -1. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations.You are interested in X, the sum of all the numbers in the grid. What is the maximum X you can achieve with these operations? | Input: ['2', '2 2', '-1 1', '1 1', '3 4', '0 -1 -2 -3', '-1 -2 -3 -4', '-2 -3 -4 -5', ''] Output:['2', '30', ''] | [
2,
3
] |
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: Choose m such that 1 <= m <= 1000Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart from the chosen one.Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies. It can be proved that for the given constraints such a sequence always exists.You don't have to minimize m.If there are several valid sequences, you can output any. | Input: ['2', '2', '3', ''] Output:['1', '2', '5', '3 3 3 1 2'] | [
3
] |
You are given an integer k and n distinct points with integer coordinates on the Euclidean plane, the i-th point has coordinates (x_i, y_i).Consider a list of all the \frac{n(n - 1)}{2} pairs of points ((x_i, y_i), (x_j, y_j)) (1 <= i < j <= n). For every such pair, write out the distance from the line through these two points to the origin (0, 0).Your goal is to calculate the k-th smallest number among these distances. | Input: ['4 3', '2 1', '-2 -1', '0 -1', '-2 4', ''] Output:['0.707106780737', ''] | [
4
] |
This is the hard version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.You are given an array [a_1, a_2, ..., a_n]. Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.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: ['7', '1 1 2 2 3 3 3', ''] Output:['6', ''] | [
2
] |
This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.You are given an array [a_1, a_2, ..., a_n]. Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.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: ['7', '1 1 2 2 3 3 3', ''] Output:['6'] | [
2
] |
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way: Consider a graph on k nodes, with numbers from b_1 to b_k written on them. For every i from 1 to k: find such j (1 <= j <= k, j\neq i), for which (b_i \oplus b_j) is the smallest among all such j, where \oplus denotes the operation of bitwise XOR (https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph. We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles). It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.You can find an example below (the picture corresponding to the first test case). Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.However, sequence (0, 1, 5, 2) is good. You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good. | Input: ['5', '0 1 5 2 6', ''] Output:['1', ''] | [
4
] |
You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i. You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: \lceil \frac{W}{2}\rceil <= C <= W. Output the list of items you will put into the knapsack or determine that fulfilling the conditions is impossible. If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights of items in the knapsack. | Input: ['3', '1 3', '3', '6 2', '19 8 19 69 9 4', '7 12', '1 1 1 17 1 1 1', ''] Output:['1', '1', '-1', '6', '1 2 3 5 6 7'] | [
2
] |
There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately. In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct). In the first contest, the participant on the 100-th place scored a points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least b points in the second contest.Similarly, for the second contest, the participant on the 100-th place has c points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least d points in the first contest.After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place.Given integers a, b, c, d, please help the jury determine the smallest possible value of the cutoff score. | Input: ['2', '1 2 2 1', '4 8 9 2', ''] Output:['3', '12', ''] | [
2,
3
] |
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i <=q x holds for each i (1 <= i <= n). | Input: ['4', '3 4', '1 2 3', '1 1 2', '', '2 6', '1 4', '2 5', '', '4 4', '1 2 3 4', '1 2 3 4', '', '1 5', '5', '5', ''] Output:['Yes', 'Yes', 'No', 'No', ''] | [
2
] |
This is an interactive problem.You are given a tree β connected undirected graph without cycles. One vertex of the tree is special, and you have to find which one. You can ask questions in the following form: given an edge of the tree, which endpoint is closer to the special vertex, meaning which endpoint's shortest path to the special vertex contains fewer edges. You have to find the special vertex by asking the minimum number of questions in the worst case for a given tree.Please note that the special vertex might not be fixed by the interactor in advance: it might change the vertex to any other one, with the requirement of being consistent with the previously given answers. | Input: ['5', '1 2', '2 3', '3 4', '4 5', '3', '2', '1', ''] Output:['? 3 4', '? 2 3', '? 1 2', '! 1', ''] | [
0
] |
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = \sum_{i = 1}^n |x_i - y_i|.Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353. | Input: ['1', '1 4', ''] Output:['6'] | [
3
] |
Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.To improve his division skills, Oleg came up with t pairs of integers p_i and q_i and for each pair decided to find the greatest integer x_i, such that: p_i is divisible by x_i; x_i is not divisible by q_i. Oleg is really good at division and managed to find all the answers quickly, how about you? | Input: ['3', '10 4', '12 6', '179 822', ''] Output:['10', '4', '179', ''] | [
0,
3
] |
A permutation is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] β are permutations, and [1, 1], [4, 3, 1], [2, 3, 4] β no.Permutation a is lexicographically smaller than permutation b (they have the same length n), if in the first index i in which they differ, a[i] < b[i]. For example, the permutation [1, 3, 2, 4] is lexicographically smaller than the permutation [1, 3, 4, 2], because the first two elements are equal, and the third element in the first permutation is smaller than in the second.The next permutation for a permutation a of length n β is the lexicographically smallest permutation b of length n that lexicographically larger than a. For example: for permutation [2, 1, 4, 3] the next permutation is [2, 3, 1, 4]; for permutation [1, 2, 3] the next permutation is [1, 3, 2]; for permutation [2, 1] next permutation does not exist. You are given the number n β the length of the initial permutation. The initial permutation has the form a = [1, 2, ..., n]. In other words, a[i] = i (1 <= i <= n).You need to process q queries of two types: 1 l r: query for the sum of all elements on the segment [l, r]. More formally, you need to find a[l] + a[l + 1] + ... + a[r]. 2 x: x times replace the current permutation with the next permutation. For example, if x=2 and the current permutation has the form [1, 3, 4, 2], then we should perform such a chain of replacements [1, 3, 4, 2] \rightarrow [1, 4, 2, 3] \rightarrow [1, 4, 3, 2]. For each query of the 1-st type output the required sum. | Input: ['4 4', '1 2 4', '2 3', '1 1 2', '1 3 4', ''] Output:['9', '4', '6', ''] | [
0,
3
] |
Petya is preparing for his birthday. He decided that there would be n different dishes on the dinner table, numbered from 1 to n. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from n different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it: the dish will be delivered by a courier from the restaurant i, in this case the courier will arrive in a_i minutes, Petya goes to the restaurant i on his own and picks up the dish, he will spend b_i minutes on this. Each restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.For example, if Petya wants to order n = 4 dishes and a = [3, 7, 4, 5], and b = [2, 1, 2, 4], then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in 3 minutes, the courier of the fourth restaurant will bring the order in 5 minutes, and Petya will pick up the remaining dishes in 1 + 2 = 3 minutes. Thus, in 5 minutes all the dishes will be at Petya's house.Find the minimum time after which all the dishes can be at Petya's home. | Input: ['4', '4', '3 7 4 5', '2 1 2 4', '4', '1 2 3 4', '3 3 3 3', '2', '1 2', '10 10', '2', '10 10', '1 2', ''] Output:['5', '3', '2', '3', ''] | [
2,
4
] |
Bertown is a city with n buildings in a straight line.The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length n, where the i-th character is "1" if there is a mine under the building number i and "0" otherwise.Bertown's best sapper knows how to activate mines so that the buildings above them are not damaged. When a mine under the building numbered x is activated, it explodes and activates two adjacent mines under the buildings numbered x-1 and x+1 (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment. For manual activation of one mine, the sapper takes a coins. He can repeat this operation as many times as you want.Also, a sapper can place a mine under a building if it wasn't there. For such an operation, he takes b coins. He can also repeat this operation as many times as you want.The sapper can carry out operations in any order.You want to blow up all the mines in the city to make it safe. Find the minimum number of coins that the sapper will have to pay so that after his actions there are no mines left in the city. | Input: ['2', '1 1', '01000010', '5 1', '01101110', ''] Output:['2', '6', ''] | [
2,
3
] |
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a \neq b) will indulge if: gcd(a, b) = 1 or, a divides b or b divides a. gcd(a, b) β the maximum number x such that a is divisible by x and b is divisible by x.For example, if n=3 and the kids sit on chairs with numbers 2, 3, 4, then they will indulge since 4 is divided by 2 and gcd(2, 3) = 1. If kids sit on chairs with numbers 4, 6, 10, then they will not indulge.The teacher really doesn't want the mess at the table, so she wants to seat the kids so there are no 2 of the kid that can indulge. More formally, she wants no pair of chairs a and b that the kids occupy to fulfill the condition above.Since the teacher is very busy with the entertainment of the kids, she asked you to solve this problem. | Input: ['3', '2', '3', '4', ''] Output:['6 4', '4 6 10', '14 10 12 8', ''] | [
3
] |