question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
There is a rectangular grid of size n * m. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell (i, j) is c_{i, j}. You are also given a map of directions: for each cell, there is a direction s_{i, j} which is one of the four characters 'U', 'R', 'D' and 'L'. If s_{i, j} is 'U' then there is a transition from the cell (i, j) to the cell (i - 1, j); if s_{i, j} is 'R' then there is a transition from the cell (i, j) to the cell (i, j + 1); if s_{i, j} is 'D' then there is a transition from the cell (i, j) to the cell (i + 1, j); if s_{i, j} is 'L' then there is a transition from the cell (i, j) to the cell (i, j - 1). It is guaranteed that the top row doesn't contain characters 'U', the bottom row doesn't contain characters 'D', the leftmost column doesn't contain characters 'L' and the rightmost column doesn't contain characters 'R'.You want to place some robots in this field (at most one robot in a cell). The following conditions should be satisfied. Firstly, each robot should move every time (i.e. it cannot skip the move). During one move each robot goes to the adjacent cell depending on the current direction. Secondly, you have to place robots in such a way that there is no move before which two different robots occupy the same cell (it also means that you cannot place two robots in the same cell). I.e. if the grid is "RL" (one row, two columns, colors does not matter there) then you can place two robots in cells (1, 1) and (1, 2), but if the grid is "RLL" then you cannot place robots in cells (1, 1) and (1, 3) because during the first second both robots will occupy the cell (1, 2). The robots make an infinite number of moves.Your task is to place the maximum number of robots to satisfy all the conditions described above and among all such ways, you have to choose one where the number of black cells occupied by robots before all movements is the maximum possible. Note that you can place robots only before all movements.You have to answer t independent test cases.
Input: ['3', '1 2', '01', 'RL', '3 3', '001', '101', '110', 'RLL', 'DLD', 'ULL', '3 3', '000', '000', '000', 'RRD', 'RLD', 'ULL', ''] Output:['2 1', '4 3', '2 2', '']
[ 2 ]
The only difference between easy and hard versions is constraints.You are given a sequence a consisting of n positive integers.Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, ..., a}_{x}, \underbrace{b, b, ..., b}_{y}, \underbrace{a, a, ..., a}_{x}]. There x, y are integers greater than or equal to 0. For example, sequences [], [2], [1, 1], [1, 2, 1], [1, 2, 2, 1] and [1, 1, 2, 1, 1] are three block palindromes but [1, 2, 3, 2, 1], [1, 2, 1, 2, 1] and [1, 2] are not.Your task is to choose the maximum by length subsequence of a that is a three blocks palindrome.You have to answer t independent test cases.Recall that the sequence t is a a subsequence of the sequence s if t can be derived from s by removing zero or more elements without changing the order of the remaining elements. For example, if s=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
Input: ['6', '8', '1 1 2 2 3 2 1 1', '3', '1 3 3', '4', '1 10 10 1', '1', '26', '2', '2 1', '3', '1 1 1', ''] Output:['7', '2', '4', '1', '1', '3', '']
[ 0 ]
The only difference between easy and hard versions is constraints.You are given a sequence a consisting of n positive integers.Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, ..., a}_{x}, \underbrace{b, b, ..., b}_{y}, \underbrace{a, a, ..., a}_{x}]. There x, y are integers greater than or equal to 0. For example, sequences [], [2], [1, 1], [1, 2, 1], [1, 2, 2, 1] and [1, 1, 2, 1, 1] are three block palindromes but [1, 2, 3, 2, 1], [1, 2, 1, 2, 1] and [1, 2] are not.Your task is to choose the maximum by length subsequence of a that is a three blocks palindrome.You have to answer t independent test cases.Recall that the sequence t is a a subsequence of the sequence s if t can be derived from s by removing zero or more elements without changing the order of the remaining elements. For example, if s=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
Input: ['6', '8', '1 1 2 2 3 2 1 1', '3', '1 3 3', '4', '1 10 10 1', '1', '26', '2', '2 1', '3', '1 1 1', ''] Output:['7', '2', '4', '1', '1', '3', '']
[ 0, 4 ]
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).So, about the teams. Firstly, these two teams should have the same size. Two more constraints: The first team should consist of students with distinct skills (i.e. all skills in the first team are unique). The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team.Consider some examples (skills are given): [1, 2, 3], [4, 4] is not a good pair of teams because sizes should be the same; [1, 1, 2], [3, 3, 3] is not a good pair of teams because the first team should not contain students with the same skills; [1, 2, 3], [3, 4, 4] is not a good pair of teams because the second team should contain students with the same skills; [1, 2, 3], [3, 3, 3] is a good pair of teams; [5], [6] is a good pair of teams. Your task is to find the maximum possible size x for which it is possible to compose a valid pair of teams, where each team size is x (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.You have to answer t independent test cases.
Input: ['4', '7', '4 2 4 1 4 3 4', '5', '2 1 5 4 3', '1', '1', '4', '1 1 1 3', ''] Output:['3', '1', '0', '2', '']
[ 2, 4 ]
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: Alice will get a (a > 0) candies; Betty will get b (b > 0) candies; each sister will get some integer number of candies; Alice will get a greater amount of candies than Betty (i.e. a > b); all the candies will be given to one of two sisters (i.e. a+b=n). Your task is to calculate the number of ways to distribute exactly n candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent n as the sum of n=a+b, where a and b are positive integers and a>b.You have to answer t independent test cases.
Input: ['6', '7', '1', '2', '3', '2000000000', '763243547', ''] Output:['3', '0', '0', '1', '999999999', '381621773', '']
[ 3 ]
You are given a permutation p consisting of exactly 26 integers from 1 to 26 (since it is a permutation, each integer from 1 to 26 occurs in p exactly once) and two strings s and t consisting of lowercase Latin letters.A substring t' of string t is an occurence of string s if the following conditions are met: |t'| = |s|; for each i \in [1, |s|], either s_i = t'_i, or p_{idx(s_i)} = idx(t'_i), where idx(c) is the index of character c in Latin alphabet (idx(\text{a}) = 1, idx(\text{b}) = 2, idx(\text{z}) = 26). For example, if p_1 = 2, p_2 = 3, p_3 = 1, s = \text{abc}, t = \text{abcaaba}, then three substrings of t are occurences of s (they are t' = \text{abc}, t' = \text{bca} and t' = \text{aba}).For each substring of t having length equal to |s|, check if it is an occurence of s.
Input: ['2 3 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26', 'abc', 'abcaaba', ''] Output:['11001']
[ 0 ]
Let's denote the following function f. This function takes an array a of length n and returns an array. Initially the result is an empty array. For each integer i from 1 to n we add element a_i to the end of the resulting array if it is greater than all previous elements (more formally, if a_i > \max\limits_{1 <= j < i}a_j). Some examples of the function f: if a = [3, 1, 2, 7, 7, 3, 6, 7, 8] then f(a) = [3, 7, 8]; if a = [1] then f(a) = [1]; if a = [4, 1, 1, 2, 3] then f(a) = [4]; if a = [1, 3, 1, 2, 6, 8, 7, 7, 4, 11, 10] then f(a) = [1, 3, 6, 8, 11]. You are given two arrays: array a_1, a_2, ... , a_n and array b_1, b_2, ... , b_m. You can delete some elements of array a (possibly zero). To delete the element a_i, you have to pay p_i coins (the value of p_i can be negative, then you get |p_i| coins, if you delete this element). Calculate the minimum number of coins (possibly negative) you have to spend for fulfilling equality f(a) = b.
Input: ['11', '4 1 3 3 7 8 7 9 10 7 11', '3 5 0 -2 5 3 6 7 8 2 4', '3', '3 7 10', ''] Output:['YES', '20', '']
[ 2, 4 ]
You are given a positive integer D. Let's build the following graph from it: each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included); two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime; the weight of an edge is the number of divisors of x that are not divisors of y. For example, here is the graph for D=12: Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 β€” [3,6,12].There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because \frac{12}{3}=4 is not a prime.Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.So the shortest path between two vertices v and u is the path that has the minimal possible length.Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.You are given q queries of the following form: v u β€” calculate the number of the shortest paths between vertices v and u. The answer for each query might be large so print it modulo 998244353.
Input: ['12', '3', '4 4', '12 1', '3 4', ''] Output:['1', '3', '1', '']
[ 2, 3 ]
You are given a complete directed graph K_n with n vertices: each pair of vertices u \neq v in K_n have both directed edges (u, v) and (v, u); there are no self-loops.You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 β€” a visiting order, where each (v_i, v_{i + 1}) occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r.
Input: ['3', '2 1 3', '3 3 6', '99995 9998900031 9998900031', ''] Output:['1 2 1 ', '1 3 2 3 ', '1 ', '']
[ 2 ]
You are playing another computer game, and now you have to slay n monsters. These monsters are standing in a circle, numbered clockwise from 1 to n. Initially, the i-th monster has a_i health.You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by 1 (deals 1 damage to it). Furthermore, when the health of some monster i becomes 0 or less than 0, it dies and explodes, dealing b_i damage to the next monster (monster i + 1, if i < n, or monster 1, if i = n). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.You have to calculate the minimum number of bullets you have to fire to kill all n monsters in the circle.
Input: ['1', '3', '7 15', '2 14', '5 3', ''] Output:['6', '']
[ 0, 2, 3 ]
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles.The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that: the government chooses some subset of people (maybe all of them); the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list [5, 1, 2, 1]: if the government chose the 1-st and the 3-rd persons then it, at first, will take all 5 + 2 = 7 burles and after that will return 3.5 burles to the chosen people. As a result, the savings will become [3.5, 1, 3.5, 1].A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.
Input: ['4', '4 3', '5 1 2 1', '4 10', '11 9 11 9', '2 5', '4 3', '3 7', '9 4 9', ''] Output:['2', '4', '0', '3', '']
[ 2 ]
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by 1. If he manages to finish the level successfully then the number of clears increases by 1 as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.So he peeked at the stats n times and wrote down n pairs of integers β€” (p_1, c_1), (p_2, c_2), ..., (p_n, c_n), where p_i is the number of plays at the i-th moment of time and c_i is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.Help him to check the correctness of his records.For your convenience you have to answer multiple independent test cases.
Input: ['6', '3', '0 0', '1 1', '1 2', '2', '1 0', '1000 3', '4', '10 1', '15 2', '10 2', '15 2', '1', '765 432', '2', '4 4', '4 3', '5', '0 0', '1 0', '1 0', '1 0', '1 0', ''] Output:['NO', 'YES', 'NO', 'YES', 'NO', 'YES', '']
[ 3 ]
Kate has a set S of n integers \{1, ..., n\} . She thinks that imperfection of a subset M \subseteq S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a \neq b. Kate is a very neat girl and for each k \in \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k. Please, help Kate to find I_2, I_3, ..., I_n.
Input: ['2', ''] Output:['1 ']
[ 2, 3 ]
Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The queen walks in all directions vertically and diagonally at any distance. You can see the examples below. To reach the goal, Egor should research the next topic:There is an N * N board. Each cell of the board has a number from 1 to N ^ 2 in it and numbers in all cells are distinct.In the beginning, some chess figure stands in the cell with the number 1. Note that this cell is already considered as visited. After that every move is determined by the following rules: Among all not visited yet cells to which the figure can get in one move, it goes to the cell that has minimal number. If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of 1 vun. If all cells are already visited, the process is stopped. Egor should find an N * N board on which the rook pays strictly less vuns than the queen during the round with this numbering. Help him to find such N * N numbered board, or tell that it doesn't exist.
Input: ['1', ''] Output:['-1']
[ 0 ]
There are n children, who study at the school β„–41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and k = 2 children can do the following steps: At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input: ['2 1', 'RL', ''] Output:['1 1 ', '']
[ 0, 2 ]
Eugene likes working with arrays. And today he needs your help in solving one challenging task.An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input: ['3', '1 2 -3', ''] Output:['5', '']
[ 4 ]
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}.Anton can perform the following sequence of operations any number of times: Choose any pair of indexes (i, j) such that 1 <= i < j <= n. It is possible to choose the same pair (i, j) more than once. Add a_i to a_j. In other words, j-th element of the array becomes equal to a_i + a_j. For example, if you are given array [1, -1, 0], you can transform it only to [1, -1, -1], [1, 0, 0] and [1, -1, 1] by one operation.Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array a so that it becomes equal to array b. Can you help him?
Input: ['5', '3', '1 -1 0', '1 1 -2', '3', '0 1 1', '0 2 2', '2', '1 0', '1 41', '2', '-1 0', '-1 -41', '5', '0 1 -1 1 -1', '1 1 -1 1 -1', ''] Output:['YES', 'NO', 'YES', 'YES', 'NO', '']
[ 2 ]
Alice has got addicted to a game called Sirtet recently.In Sirtet, player is given an n * m grid. Initially a_{i,j} cubes are stacked up in the cell (i,j). Two cells are called adjacent if they share a side. Player can perform the following operations: stack up one cube in two adjacent cells; stack up two cubes in one cell. Cubes mentioned above are identical in height.Here is an illustration of the game. States on the right are obtained by performing one of the above operations on the state on the left, and grey cubes are added due to the operation. Player's goal is to make the height of all cells the same (i.e. so that each cell has the same number of cubes in it) using above operations. Alice, however, has found out that on some starting grids she may never reach the goal no matter what strategy she uses. Thus, she is wondering the number of initial grids such that L <= a_{i,j} <= R for all 1 <= i <= n, 1 <= j <= m; player can reach the goal using above operations. Please help Alice with it. Notice that the answer might be large, please output the desired value modulo 998,244,353.
Input: ['2 2 1 1', ''] Output:['1', '']
[ 3 ]
Bob is playing a game named "Walk on Matrix".In this game, player is given an n * m matrix A=(a_{i,j}), i.e. the element in the i-th row in the j-th column is a_{i,j}. Initially, player is located at position (1,1) with score a_{1,1}. To reach the goal, position (n,m), player can move right or down, i.e. move from (x,y) to (x,y+1) or (x+1,y), as long as player is still on the matrix.However, each move changes player's score to the bitwise AND of the current score and the value at the position he moves to.Bob can't wait to find out the maximum score he can get using the tool he recently learnt β€” dynamic programming. Here is his algorithm for this problem. However, he suddenly realize that the algorithm above fails to output the maximum score for some matrix A. Thus, for any given non-negative integer k, he wants to find out an n * m matrix A=(a_{i,j}) such that 1 <= n,m <= 500 (as Bob hates large matrix); 0 <= a_{i,j} <= 3 \cdot 10^5 for all 1 <= i<= n,1 <= j<= m (as Bob hates large numbers); the difference between the maximum score he can get and the output of his algorithm is exactly k. It can be shown that for any given integer k such that 0 <= k <= 10^5, there exists a matrix satisfying the above constraints.Please help him with it!
Input: ['0', ''] Output:['1 1', '300000']
[ 3 ]
Word s of length n is called k-complete if s is a palindrome, i.e. s_i=s_{n+1-i} for all 1 <= i <= n; s has a period of k, i.e. s_i=s_{k+i} for all 1 <= i <= n-k. For example, "abaaba" is a 3-complete word, while "abccba" is not.Bob is given a word s of length n consisting of only lowercase Latin letters and an integer k, such that n is divisible by k. He wants to convert s to any k-complete word.To do this Bob can choose some i (1 <= i <= n) and replace the letter at position i with some other lowercase Latin letter.So now Bob wants to know the minimum number of letters he has to replace to convert s to any k-complete word.Note that Bob can do zero changes if the word s is already k-complete.You are required to answer t test cases independently.
Input: ['4', '6 2', 'abaaba', '6 3', 'abaaba', '36 9', 'hippopotomonstrosesquippedaliophobia', '21 7', 'wudixiaoxingxingheclp', ''] Output:['2', '0', '23', '16', '']
[ 2 ]
A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97.Alice is given a sequence of n composite numbers a_1,a_2,...,a_n.She wants to choose an integer m <= 11 and color each element one of m colors from 1 to m so that: for each color from 1 to m there is at least one element of this color; each element is colored and colored exactly one color; the greatest common divisor of any two elements that are colored the same color is greater than 1, i.e. \gcd(a_i, a_j)>1 for each pair i, j if these elements are colored the same color. Note that equal elements can be colored different colors β€” you just have to choose one of m colors for each of the indices from 1 to n.Alice showed already that if all a_i <= 1000 then she can always solve the task by choosing some m <= 11.Help Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some m from 1 to 11.
Input: ['3', '3', '6 10 15', '2', '4 9', '23', '437 519 865 808 909 391 194 291 237 395 323 365 511 497 781 737 871 559 731 697 779 841 961', ''] Output:['1', '1 1 1', '2', '2 1', '11', '4 7 8 10 7 3 10 7 7 8 3 1 1 5 5 9 2 2 3 3 4 11 6', '']
[ 0, 2, 3 ]
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move: exactly a steps left: from (u,v) to (u-1,v); exactly b steps right: from (u,v) to (u+1,v); exactly c steps down: from (u,v) to (u,v-1); exactly d steps up: from (u,v) to (u,v+1). Note that the moves can be performed in an arbitrary order. For example, if the cat has to move 1 step left, 3 steps right and 2 steps down, then the walk right, down, left, right, right, down is valid.Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area [x_1,x_2]* [y_1,y_2], i.e. for every cat's position (u,v) of a walk x_1 <= u <= x_2 and y_1 <= v <= y_2 holds.Also, note that the cat can visit the same cell multiple times.Can you help Alice find out if there exists a walk satisfying her wishes?Formally, the walk should contain exactly a+b+c+d unit moves (a to the left, b to the right, c to the down, d to the up). Alice can do the moves in any order. Her current position (u, v) should always satisfy the constraints: x_1 <= u <= x_2, y_1 <= v <= y_2. The staring point is (x, y).You are required to answer t test cases independently.
Input: ['6', '3 2 2 2', '0 0 -2 -2 2 2', '3 1 4 1', '0 0 -1 -1 1 1', '1 1 1 1', '1 1 1 1 1 1', '0 0 0 1', '0 0 0 0 0 1', '5 1 1 1', '0 0 -100 -100 0 100', '1 1 5 1', '0 0 -100 -100 100 0', ''] Output:['Yes', 'No', 'No', 'Yes', 'Yes', 'Yes', '']
[ 2, 3 ]
InputThe input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive.OutputOutput "YES" or "NO".ExamplesInputGENIUS OutputYES InputDOCTOR OutputNO InputIRENE OutputYES InputMARY OutputNO InputSMARTPHONE OutputNO InputREVOLVER OutputYES InputHOLMES OutputNO InputWATSON OutputYES
Input: ['GENIUS', ''] Output:['YES', '']
[ 0 ]
There was once young lass called Mary, Whose jokes were occasionally scary. On this April's Fool Fixed limerick rules Allowed her to trip the unwary.Can she fill all the linesTo work at all times?On juggling the wordsRight around two-thirdsShe nearly ran out of rhymes.
Input: ['35', ''] Output:['57', '']
[ 3 ]
The sequence of m integers is called the permutation if it contains all integers from 1 to m exactly once. The number m is called the length of the permutation.Dreamoon has two permutations p_1 and p_2 of non-zero lengths l_1 and l_2.Now Dreamoon concatenates these two permutations into another sequence a of length l_1 + l_2. First l_1 elements of a is the permutation p_1 and next l_2 elements of a is the permutation p_2. You are given the sequence a, and you need to find two permutations p_1 and p_2. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)
Input: ['6', '5', '1 4 3 2 1', '6', '2 4 1 3 2 1', '4', '2 1 1 3', '4', '1 3 3 1', '12', '2 1 3 4 5 6 7 8 9 1 10 2', '3', '1 1 1', ''] Output:['2', '1 4', '4 1', '1', '4 2', '0', '0', '1', '2 10', '0', '']
[ 3 ]
There is a string of length n+1 of characters 'A' and 'B'. The first character and last character of the string are equal to 'A'.You are given m indices p_1, p_2, ..., p_m (0-indexation) denoting the other indices of characters 'A' in the string. Let's denote the minimum distance between two neighboring 'A' as l, and maximum distance between neighboring 'A' as r.For example, (l,r) of string "ABBAABBBA" is (1,4).And let's denote the balance degree of a string as the value of r-l.Now Dreamoon wants to change exactly k characters from 'B' to 'A', and he wants to make the balance degree of the string as small as possible.Please calculate the required minimum possible value of balance degree.
Input: ['5', '80 3 5', '11 24 50', '81 7 12', '4 10 17 26 37 48 61', '25 10 14', '3 4 7 12 13 15 17 19 21 23', '1 0 0', '', '10 2 0', '2 4', ''] Output:['5', '2', '0', '0', '4', '']
[ 2, 4 ]
Drazil likes heap very much. So he created a problem with heap:There is a max heap with a height h implemented on the array. The details of this heap are the following:This heap contains exactly 2^h - 1 distinct positive non-zero integers. All integers are distinct. These numbers are stored in the array a indexed from 1 to 2^h-1. For any 1 < i < 2^h, a[i] < a[<=ft \lfloor{\frac{i}{2}}\right \rfloor].Now we want to reduce the height of this heap such that the height becomes g with exactly 2^g-1 numbers in heap. To reduce the height, we should perform the following action 2^h-2^g times:Choose an index i, which contains an element and call the following function f in index i:Note that we suppose that if a[i]=0, then index i don't contain an element.After all operations, the remaining 2^g-1 element must be located in indices from 1 to 2^g-1. Now Drazil wonders what's the minimum possible sum of the remaining 2^g-1 elements. Please find this sum and find a sequence of the function calls to achieve this value.
Input: ['2', '3 2', '7 6 3 5 4 2 1', '3 2', '7 6 5 4 3 2 1', ''] Output:['10', '3 2 3 1', '8', '2 1 3 1', '']
[ 2 ]
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: The length of a is n, n >= 1 1 <= a_1 < a_2 < ... < a_n <= d Define an array b of length n as follows: b_1 = a_1, \forall i > 1, b_i = b_{i - 1} \oplus a_i, where \oplus is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m.
Input: ['10', '1 1000000000', '2 999999999', '3 99999998', '4 9999997', '5 999996', '6 99995', '7 9994', '8 993', '9 92', '10 1', ''] Output:['1', '3', '5', '11', '17', '23', '29', '59', '89', '0', '']
[ 3 ]
Dreamoon likes coloring cells very much.There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.You are given an integer m and m integers l_1, l_2, ..., l_m (1 <= l_i <= n)Dreamoon will perform m operations.In i-th operation, Dreamoon will choose a number p_i from range [1, n-l_i+1] (inclusive) and will paint all cells from p_i to p_i+l_i-1 (inclusive) in i-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.Dreamoon hopes that after these m operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose p_i in each operation to satisfy all constraints.
Input: ['5 3', '3 2 2', ''] Output:['2 4 1', '']
[ 2, 3 ]
You are given the array a consisting of n elements and the integer k <= n.You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations: Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1); take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1). Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input: ['6 5', '1 2 2 4 2 3', ''] Output:['3', '']
[ 2 ]
The round carousel consists of n figures of animals. Figures are numbered from 1 to n in order of the carousel moving. Thus, after the n-th figure the figure with the number 1 follows. Each figure has its own type β€” the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the i-th figure equals t_i. The example of the carousel for n=9 and t=[5, 5, 1, 15, 1, 5, 5, 1, 1]. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly k distinct colors, then the colors of figures should be denoted with integers from 1 to k.
Input: ['4', '5', '1 2 1 2 2', '6', '1 2 2 1 2 2', '5', '1 2 1 2 3', '3', '10 10 10', ''] Output:['2', '1 2 1 2 2', '2', '2 1 2 1 2 1', '3', '2 3 2 3 1', '1', '1 1 1 ', '']
[ 2, 3 ]
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.Let's define the ternary XOR operation \odot of two ternary numbers a and b (both of length n) as a number c = a \odot b of length n, where c_i = (a_i + b_i) \% 3 (where \% is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by 3. For example, 10222 \odot 11021 = 21210.Your task is to find such ternary numbers a and b both of length n and both without leading zeros that a \odot b = x and max(a, b) is the minimum possible.You have to answer t independent test cases.
Input: ['4', '5', '22222', '5', '21211', '1', '2', '9', '220222021', ''] Output:['11111', '11111', '11000', '10211', '1', '1', '110111011', '110111010', '']
[ 2 ]
For the given integer n (n > 2) let's write down all the strings of length n which contain n-2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order.Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1 <= i <= n), that s_i < t_i, and for any j (1 <= j < i) s_j = t_j. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.For example, if n=5 the strings are (the order does matter): aaabb aabab aabba abaab ababa abbaa baaab baaba babaa bbaaa It is easy to show that such a list of strings will contain exactly \frac{n \cdot (n-1)}{2} strings.You are given n (n > 2) and k (1 <= k <= \frac{n \cdot (n-1)}{2}). Print the k-th string from the list.
Input: ['7', '5 1', '5 2', '5 8', '5 10', '3 1', '3 2', '20 100', ''] Output:['aaabb', 'aabab', 'baaba', 'bbaaa', 'abb', 'bab', 'aaaaabaaaaabaaaaaaaa', '']
[ 0, 3, 4 ]
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test cases.
Input: ['5', '10 4', '13 9', '100 13', '123 456', '92 46', ''] Output:['2', '5', '4', '333', '0', '']
[ 3 ]
You wrote down all integers from 0 to 10^n - 1, padding them with leading zeroes so their lengths are exactly n. For example, if n = 3 then you wrote out 000, 001, ..., 998, 999.A block in an integer x is a consecutive segment of equal digits that cannot be extended to the left or to the right.For example, in the integer 00027734000 there are three blocks of length 1, one block of length 2 and two blocks of length 3.For all integers i from 1 to n count the number of blocks of length i among the written down integers.Since these integers may be too large, print them modulo 998244353.
Input: ['1', ''] Output:['10', '']
[ 3 ]
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).We can also define a multiplication of permutations a and b as permutation c = a * b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p * p * ... * p}_{k \text{ times}}.Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).It can be proved that the answer always exists.
Input: ['3', '4', '1 3 4 2', '1 2 2 3', '5', '2 3 4 5 1', '1 2 3 4 5', '8', '7 4 5 6 1 8 3 2', '5 3 6 4 7 5 8 4', ''] Output:['1', '5', '2', '']
[ 0, 3 ]
The King of Berland Polycarp LXXXIV has n daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are n other kingdoms as well.So Polycarp LXXXIV has enumerated his daughters from 1 to n and the kingdoms from 1 to n. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.For the first daughter he takes the kingdom with the lowest number from her list and marries the daughter to their prince. For the second daughter he takes the kingdom with the lowest number from her list, prince of which hasn't been taken already. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the n-th daughter.For example, let there be 4 daughters and kingdoms, the lists daughters have are [2, 3], [1, 2], [3, 4], [3], respectively. In that case daughter 1 marries the prince of kingdom 2, daughter 2 marries the prince of kingdom 1, daughter 3 marries the prince of kingdom 3, leaving daughter 4 nobody to marry to.Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. Note that this kingdom should not be present in the daughter's list.Polycarp LXXXIV wants to increase the number of married couples.Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.For your and our convenience you are asked to answer t independent test cases.
Input: ['5', '4', '2 2 3', '2 1 2', '2 3 4', '1 3', '2', '0', '0', '3', '3 1 2 3', '3 1 2 3', '3 1 2 3', '1', '1 1', '4', '1 1', '1 2', '1 3', '1 4', ''] Output:['IMPROVE', '4 4', 'IMPROVE', '1 1', 'OPTIMAL', 'OPTIMAL', 'OPTIMAL', '']
[ 0, 2 ]
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.You have to answer t independent test cases.
Input: ['6', '3 1', '4 2', '10 3', '10 2', '16 4', '16 5', ''] Output:['YES', 'YES', 'NO', 'YES', 'YES', 'NO', '']
[ 3 ]
This is the hard version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved.n wise men live in a beautiful city. Some of them know each other.For each of the n! possible permutations p_1, p_2, ..., p_n of the wise men, let's generate a binary string of length n-1: for each 1 <=q i < n set s_i=1 if p_i and p_{i+1} know each other, and s_i=0 otherwise. For all possible 2^{n-1} binary strings, find the number of permutations that produce this binary string.
Input: ['3', '011', '101', '110', ''] Output:['0 0 0 6 ', '']
[ 3 ]
This is the easy version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved.n wise men live in a beautiful city. Some of them know each other.For each of the n! possible permutations p_1, p_2, ..., p_n of the wise men, let's generate a binary string of length n-1: for each 1 <=q i < n set s_i=1 if p_i and p_{i+1} know each other, and s_i=0 otherwise. For all possible 2^{n-1} binary strings, find the number of permutations that produce this binary string.
Input: ['3', '011', '101', '110', ''] Output:['0 0 0 6 ', '']
[ 0 ]
This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions: The length of t does not exceed the length of s. t is a palindrome. There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input: ['5', 'a', 'abcdfdcecba', 'abbaxyzyx', 'codeforces', 'acbba', ''] Output:['a', 'abcdfdcba', 'xyzyx', 'c', 'abba', '']
[ 2, 4 ]
You are given a permutation p_1, p_2, ..., p_n of integers from 1 to n and an integer k, such that 1 <=q k <=q n. A permutation means that every number from 1 to n is contained in p exactly once.Let's consider all partitions of this permutation into k disjoint segments. Formally, a partition is a set of segments \{[l_1, r_1], [l_2, r_2], ..., [l_k, r_k]\}, such that: 1 <=q l_i <=q r_i <=q n for all 1 <=q i <=q k; For all 1 <=q j <=q n there exists exactly one segment [l_i, r_i], such that l_i <=q j <=q r_i. Two partitions are different if there exists a segment that lies in one partition but not the other.Let's calculate the partition value, defined as \sum\limits_{i=1}^{k} {\max\limits_{l_i <=q j <=q r_i} {p_j}}, for all possible partitions of the permutation into k disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by 998\,244\,353.
Input: ['3 2', '2 1 3', ''] Output:['5 2', '']
[ 2, 3 ]
Alicia has an array, a_1, a_2, ..., a_n, of non-negative integers. For each 1 <=q i <=q n, she has found a non-negative integer x_i = max(0, a_1, ..., a_{i-1}). Note that for i=1, x_i = 0.For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.Then, she calculated an array, b_1, b_2, ..., b_n: b_i = a_i - x_i.For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, b = \{0-0, 1-0, 2-1, 0-2, 3-2\} = \{0, 1, 1, -2, 1\}.Alicia gives you the values b_1, b_2, ..., b_n and asks you to restore the values a_1, a_2, ..., a_n. Can you help her solve the problem?
Input: ['5', '0 1 1 -2 1', ''] Output:['0 1 2 0 3 ']
[ 3 ]
It's the year 5555. You have a graph, and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with n vertices, you can choose to either: find an independent set that has exactly \lceil\sqrt{n}\rceil vertices. find a simple cycle of length at least \lceil\sqrt{n}\rceil. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.
Input: ['6 6', '1 3', '3 4', '4 2', '2 6', '5 6', '5 1', ''] Output:['1', '1 6 4']
[ 2 ]
You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements.
Input: ['3', '1 4 6', ''] Output:['1']
[ 0 ]
Given 2 integers u and v, find the shortest array such that bitwise-xor of its elements is u, and the sum of its elements is v.
Input: ['2 4', ''] Output:['2', '3 1']
[ 2 ]
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 0 and n-2 inclusive. All the written labels are distinct. The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input: ['3', '1 2', '1 3', ''] Output:['0', '1', '']
[ 2 ]
Ehab has an array a of length n. He has just enough free time to make a new array consisting of n copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.
Input: ['2', '3', '3 2 1', '6', '3 1 4 1 5 9', ''] Output:['3', '5', '']
[ 2 ]
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it.It's guaranteed that the solution always exists. If there are several such pairs (a, b), you can output any of them.
Input: ['2', '2', '14', ''] Output:['1 1', '6 4', '']
[ 2 ]
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.
Input: ['5', '4 8 2 6 2', '4 5 4 1 3', ''] Output:['7', '']
[ 4 ]
There is a frog staying to the left of the string s = s_1 s_2 ... s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. If the frog is staying at the i-th cell and the i-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 0.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1-th cell. The frog chooses some positive integer value d before the first jump (and cannot change it later) and jumps by no more than d cells at once. I.e. if the i-th character is 'L' then the frog can jump to any cell in a range [max(0, i - d); i - 1], and if the i-th character is 'R' then the frog can jump to any cell in a range [i + 1; min(n + 1; i + d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of d such that the frog can reach the cell n+1 from the cell 0 if it can jump by no more than d cells at once. It is guaranteed that it is always possible to reach n+1 from 0.You have to answer t independent test cases.
Input: ['6', 'LRLRRLL', 'L', 'LLR', 'RRRR', 'LLLLLL', 'R', ''] Output:['3', '2', '3', '1', '7', '1', '']
[ 2, 4 ]
You are given an array a consisting of n integers.Your task is to determine if a has some subsequence of length at least 3 that is a palindrome.Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without changing the order of remaining elements. For example, [2], [1, 2, 1, 3] and [2, 3] are subsequences of [1, 2, 1, 3], but [1, 1, 2] and [4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array a of length n is the palindrome if a_i = a_{n - i - 1} for all i from 1 to n. For example, arrays [1234], [1, 2, 1], [1, 3, 2, 2, 3, 1] and [10, 100, 10] are palindromes, but arrays [1, 2] and [1, 2, 3, 1] are not.You have to answer t independent test cases.
Input: ['5', '3', '1 2 1', '5', '1 2 2 3 2', '3', '1 1 2', '4', '1 2 2 1', '10', '1 1 2 2 3 3 4 4 5 5', ''] Output:['YES', 'YES', 'NO', 'YES', 'NO', '']
[ 0 ]
You are given an array a of length n and array b of length m both consisting of only integers 0 and 1. Consider a matrix c of size n * m formed by following rule: c_{i, j} = a_i \cdot b_j (i.e. a_i multiplied by b_j). It's easy to see that c consists of only zeroes and ones too.How many subrectangles of size (area) k consisting only of ones are there in c?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x_1, x_2, y_1, y_2 (1 <= x_1 <= x_2 <= n, 1 <= y_1 <= y_2 <= m) a subrectangle c[x_1 ... x_2][y_1 ... y_2] is an intersection of the rows x_1, x_1+1, x_1+2, ..., x_2 and the columns y_1, y_1+1, y_1+2, ..., y_2.The size (area) of a subrectangle is the total number of cells in it.
Input: ['3 3 2', '1 0 1', '1 1 1', ''] Output:['4', '']
[ 2, 4 ]
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset.Both the given array and required subset may contain equal values.
Input: ['3', '3', '1 4 3', '1', '15', '2', '3 5', ''] Output:['1', '2', '-1', '2', '1 2', '']
[ 0, 2 ]
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left half we define N(S) as the set of all vertices of the right half adjacent to at least one vertex in S, and f(S) as the sum of all numbers in vertices of N(S). Find the greatest common divisor of f(S) for all possible non-empty subsets S (assume that GCD of empty set is 0).Wu is too tired after his training to solve this problem. Help him!
Input: ['3', '2 4', '1 1', '1 1', '1 2', '2 1', '2 2', '', '3 4', '1 1 1', '1 1', '1 2', '2 2', '2 3', '', '4 7', '36 31 96 29', '1 2', '1 3', '1 4', '2 2', '2 4', '3 1', '4 3', ''] Output:['2', '1', '12', '']
[ 3 ]
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one β€” xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute (a_1 + a_2) \oplus (a_1 + a_3) \oplus ... \oplus (a_1 + a_n) \\ \oplus (a_2 + a_3) \oplus ... \oplus (a_2 + a_n) \\ ... \\ \oplus (a_{n-1} + a_n) \\ Here x \oplus y is a bitwise XOR operation (i.e. x ^ y in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.
Input: ['2', '1 2', ''] Output:['3']
[ 3, 4 ]
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task β€” she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input: ['8', '))((())(', ''] Output:['6', '']
[ 2 ]
You are given a string s consisting of lowercase Latin letters. Let the length of s be |s|. You may perform several operations on this string.In one operation, you can choose some index i and remove the i-th character of s (s_i) if at least one of its adjacent characters is the previous letter in the Latin alphabet for s_i. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index i should satisfy the condition 1 <= i <= |s| during each operation.For the character s_i adjacent characters are s_{i-1} and s_{i+1}. The first and the last characters of s both have only one adjacent character (unless |s| = 1).Consider the following example. Let s= bacabcab. During the first move, you can remove the first character s_1= b because s_2= a. Then the string becomes s= acabcab. During the second move, you can remove the fifth character s_5= c because s_4= b. Then the string becomes s= acabab. During the third move, you can remove the sixth character s_6='b' because s_5= a. Then the string becomes s= acaba. During the fourth move, the only character you can remove is s_4= b, because s_3= a (or s_5= a). The string becomes s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.
Input: ['8', 'bacabcab', ''] Output:['4', '']
[ 0, 2 ]
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each problem, p_i is an integer not less than 1.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results β€” or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of p_i in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of p_i will be large, it may look very suspicious β€” so Polycarp wants to minimize the maximum value of p_i over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?
Input: ['5', '1 1 1 0 0', '0 1 1 1 1', ''] Output:['3', '']
[ 2 ]
Polycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks β€” axis-aligned cubes of size 1 * 1 * 1. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size 1 * 1 * 1; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates (x, y, z) (the cell with these coordinates is a cube with opposite corners in (x, y, z) and (x + 1, y + 1, z + 1)) and its contents a_{x, y, z}; if the cell is empty, then a_{x, y, z} = 0, otherwise a_{x, y, z} is equal to the type of the block placed in it (the types are integers from 1 to 2 \cdot 10^5).Polycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size n * m * k, containing all cells (x, y, z) such that x \in [1, n], y \in [1, m], and z \in [1, k]. After that, Polycarp has installed 2nm + 2nk + 2mk sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into 6 types: there are mk sensors of the first type; each such sensor is installed in (0, y, z), where y \in [1, m] and z \in [1, k], and it sends a ray that is parallel to the Ox axis and has the same direction; there are mk sensors of the second type; each such sensor is installed in (n + 1, y, z), where y \in [1, m] and z \in [1, k], and it sends a ray that is parallel to the Ox axis and has the opposite direction; there are nk sensors of the third type; each such sensor is installed in (x, 0, z), where x \in [1, n] and z \in [1, k], and it sends a ray that is parallel to the Oy axis and has the same direction; there are nk sensors of the fourth type; each such sensor is installed in (x, m + 1, z), where x \in [1, n] and z \in [1, k], and it sends a ray that is parallel to the Oy axis and has the opposite direction; there are nm sensors of the fifth type; each such sensor is installed in (x, y, 0), where x \in [1, n] and y \in [1, m], and it sends a ray that is parallel to the Oz axis and has the same direction; finally, there are nm sensors of the sixth type; each such sensor is installed in (x, y, k + 1), where x \in [1, n] and y \in [1, m], and it sends a ray that is parallel to the Oz axis and has the opposite direction. Polycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.After some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?
Input: ['4 3 2', '', '1 4', '3 2', '6 5', '', '1 4', '3 2', '6 7', '', '1 4', '1 4', '0 0', '0 7', '', '6 5', '6 5', '0 0', '0 7', '', '1 3 6', '1 3 6', '0 0 0', '0 0 7', '', '4 3 5', '4 2 5', '0 0 0', '0 0 7', ''] Output:['1 4', '3 0', '6 5', '', '1 4', '3 2', '6 5', '', '0 0', '0 0', '0 0', '', '0 0', '0 0', '0 7', '']
[ 0 ]
Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense modifier b_j and is worth cb_j coins.After choosing his equipment Roma can proceed to defeat some monsters. There are p monsters he can try to defeat. Monster k has defense x_k, attack y_k and possesses z_k coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster k can be defeated with a weapon i and an armor set j if a_i > x_k and b_j > y_k. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.
Input: ['2 3 3', '2 3', '4 7', '2 4', '3 2', '5 11', '1 2 4', '2 1 6', '3 4 6', ''] Output:['1', '']
[ 0 ]
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold.For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: c = [1, 2, 4]; c = [3, 5, 6, 8]; c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
Input: ['6', '10 7 1 9 10 15', ''] Output:['26', '']
[ 2, 3 ]
Alice, the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of p players playing in p different positions. She also recognizes the importance of audience support, so she wants to select k people as part of the audience.There are n people in Byteland. Alice needs to select exactly p players, one for each position, and exactly k members of the audience from this pool of n people. Her ultimate goal is to maximize the total strength of the club.The i-th of the n persons has an integer a_{i} associated with him β€” the strength he adds to the club if he is selected as a member of the audience.For each person i and for each position j, Alice knows s_{i, j} β€” the strength added by the i-th person to the club if he is selected to play in the j-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.
Input: ['4 1 2', '1 16 10 3', '18', '19', '13', '15', ''] Output:['44', '']
[ 2 ]
It is Professor R's last class of his teaching career. Every time Professor R taught a class, he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x) = a_0 + a_1x + ... + a_{n-1}x^{n-1} and g(x) = b_0 + b_1x + ... + b_{m-1}x^{m-1}, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 1 for both the given polynomials. In other words, gcd(a_0, a_1, ..., a_{n-1}) = gcd(b_0, b_1, ..., b_{m-1}) = 1. Let h(x) = f(x)\cdot g(x). Suppose that h(x) = c_0 + c_1x + ... + c_{n+m-2}x^{n+m-2}. You are also given a prime number p. Professor R challenges you to find any t such that c_t isn't divisible by p. He guarantees you that under these conditions such t always exists. If there are several such t, output any of them.As the input is quite large, please use fast input reading methods.
Input: ['3 2 2', '1 1 2', '2 1', ''] Output:['1', '']
[ 3, 4 ]
Vasya has a string s of length n. He decides to make the following modification to the string: Pick an integer k, (1 <=q k <=q n). For i from 1 to n-k+1, reverse the substring s[i:i+k-1] of s. For example, if string s is qwer and k = 2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 2) weqr (after reversing the second substring of length 2) werq (after reversing the last substring of length 2) Hence, the resulting string after modifying s with k = 2 is werq. Vasya wants to choose a k such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of k. Among all such k, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a!=b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input: ['6', '4', 'abab', '6', 'qwerty', '5', 'aaaaa', '6', 'alaska', '9', 'lfpbavjsm', '1', 'p', ''] Output:['abab', '1', 'ertyqw', '3', 'aaaaa', '1', 'aksala', '6', 'avjsmbpfl', '5', 'p', '1', '']
[ 0 ]
You are given a sequence b_1, b_2, ..., b_n. Find the lexicographically minimal permutation a_1, a_2, ..., a_{2n} such that b_i = \min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input: ['5', '1', '1', '2', '4 1', '3', '4 1 3', '4', '2 3 4 5', '5', '1 5 7 2 8', ''] Output:['1 2 ', '-1', '4 5 1 2 3 6 ', '-1', '1 3 5 6 7 9 2 4 8 10 ', '']
[ 2 ]
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string s of length n, where s_i = \texttt{A}, if there is a bus station at i-th crossroad, and s_i = \texttt{B}, if there is a tram station at i-th crossroad. Currently Petya is at the first crossroad (which corresponds to s_1) and his goal is to get to the last crossroad (which corresponds to s_n).If for two crossroads i and j for all crossroads i, i+1, ..., j-1 there is a bus station, one can pay a roubles for the bus ticket, and go from i-th crossroad to the j-th crossroad by the bus (it is not necessary to have a bus station at the j-th crossroad). Formally, paying a roubles Petya can go from i to j if s_t = \texttt{A} for all i <= t < j. If for two crossroads i and j for all crossroads i, i+1, ..., j-1 there is a tram station, one can pay b roubles for the tram ticket, and go from i-th crossroad to the j-th crossroad by the tram (it is not necessary to have a tram station at the j-th crossroad). Formally, paying b roubles Petya can go from i to j if s_t = \texttt{B} for all i <= t < j.For example, if s="AABBBAB", a=4 and b=3 then Petya needs: buy one bus ticket to get from 1 to 3, buy one tram ticket to get from 3 to 6, buy one bus ticket to get from 6 to 7. Thus, in total he needs to spend 4+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character s_n) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the n-th crossroad. After the party he has left with p roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad i to go on foot the first, so he has enough money to get from the i-th crossroad to the n-th, using only tram and bus tickets.
Input: ['5', '2 2 1', 'BB', '1 1 1', 'AB', '3 2 8', 'AABBBBAABB', '5 3 4', 'BBBBB', '2 1 1', 'ABABAB', ''] Output:['2', '1', '3', '1', '6', '']
[ 2, 4 ]
This is a harder version of the problem. In this version n <= 500\,000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 <= a_i <= m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input: ['51 2 3 2 1'] Output:['1 2 3 2 1 ']
[ 2 ]
This is an easier version of the problem. In this version n <= 1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 <= a_i <= m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input: ['51 2 3 2 1'] Output:['1 2 3 2 1 ']
[ 0, 2 ]
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be n participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took x-th place and in the second round β€” y-th place. Then the total score of the participant A is sum x + y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every i from 1 to n exactly one participant took i-th place in first round and exactly one participant took i-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got x-th place in first round and y-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
Input: ['15 1 3'] Output:['1 3']
[ 2, 3 ]
Tired of boring office work, Denis decided to open a fast food restaurant.On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?
Input: ['71 2 10 0 09 1 72 2 32 3 23 2 24 4 4'] Output:['3045557']
[ 0, 2 ]
You are given an array a_1, a_2, ..., a_n. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements a_i = a_{i + 1} (if there is at least one such pair). Replace them by one element with value a_i + 1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array a you can get?
Input: ['5', '4 3 2 2 3', ''] Output:['2', '']
[ 2 ]
Your task is to calculate the number of arrays such that: each array contains n elements; each element is an integer from 1 to m; for each array, there is exactly one pair of equal elements; for each array a, there exists an index i such that the array is strictly ascending before the i-th element and strictly descending after it (formally, it means that a_j < a_{j + 1}, if j < i, and a_j > a_{j + 1}, if j >= i).
Input: ['3 4', ''] Output:['6', '']
[ 3 ]
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times β€” at i-th step (0-indexed) you can: either choose position pos (1 <= pos <= n) and increase v_{pos} by k^i; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array v equal to the given array a (v_j = a_j for each j) after some step?
Input: ['5', '4 100', '0 0 0 0', '1 2', '1', '3 4', '1 4 1', '3 2', '0 1 3', '3 9', '0 59049 810', ''] Output:['YES', 'YES', 'NO', 'NO', 'YES', '']
[ 2, 3, 4 ]
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with m vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer t independent test cases.
Input: ['2', '6 3', '7 3', ''] Output:['YES', 'NO', '']
[ 2, 3 ]
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.You have to answer t independent test cases.
Input: ['3', '5 7', '10 19', '10 18', ''] Output:['YES', '1 2 1 3 ', 'YES', '1 2 3 3 9 9 2 1 6 ', 'NO', '']
[ 0 ]
You are given three integers a <= b <= c.In one move, you can add +1 or -1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A <= B <= C such that B is divisible by A and C is divisible by B.You have to answer t independent test cases.
Input: ['8', '1 2 3', '123 321 456', '5 10 15', '15 18 21', '100 100 101', '1 22 29', '3 19 38', '6 30 46', ''] Output:['1', '1 1 3', '102', '114 228 456', '4', '4 8 16', '6', '18 18 18', '1', '100 100 100', '7', '1 22 22', '2', '1 19 38', '8', '6 24 48', '']
[ 0, 3 ]
You want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend m wrong tries to perform the combo and during the i-th try you will make a mistake right after p_i-th button (1 <= p_i < n) (i.e. you will press first p_i buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1-th try you press all buttons right and finally perform the combo.I.e. if s="abca", m=2 and p = [1, 3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer t independent test cases.
Input: ['3', '4 2', 'abca', '1 3', '10 5', 'codeforces', '2 8 3 2 9', '26 10', 'qwertyuioplkjhgfdsazxcvbnm', '20 10 1 2 3 5 10 5 9 4', ''] Output:['4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ', '0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 ', '2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 ', '']
[ 0 ]
You are given two positive integers a and b.In one move, you can change a in the following way: Choose any positive odd integer x (x > 0) and replace a with a+x; choose any positive even integer y (y > 0) and replace a with a-y. You can perform as many such operations as you want. You can choose the same numbers x and y in different moves.Your task is to find the minimum number of moves required to obtain b from a. It is guaranteed that you can always obtain b from a.You have to answer t independent test cases.
Input: ['5', '2 3', '10 10', '2 4', '7 4', '9 3', ''] Output:['1', '0', '2', '2', '1', '']
[ 2, 3 ]
In modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: Let's fix a finite field and two it's elements a and b. One need to fun such x that a^x = b or detect there is no such x. It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field β€” nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to 2^{2^k} - 1 for some positive integer k . Bitwise exclusive or (\oplus) operation is used as addition. One of ways to define multiplication operation (\odot) is following properties: 0 \odot a = a \odot 0 = 0 1 \odot a = a \odot 1 = a a \odot b = b \odot a a \odot (b \odot c)= (a \odot b) \odot c a \odot (b \oplus c) = (a \odot b) \oplus (a \odot c) If a = 2^{2^n} for some integer n > 0, and b < a, then a \odot b = a \cdot b. If a = 2^{2^n} for some integer n > 0, then a \odot a = \frac{3}{2}\cdot a. For example: 4 \odot 4 = 6 8 \odot 8 = 4 \odot 2 \odot 4 \odot 2 = 4 \odot 4 \odot 2 \odot 2 = 6 \odot 3 = (4 \oplus 2) \odot 3 = (4 \odot 3) \oplus (2 \odot (2 \oplus 1)) = (4 \odot 3) \oplus (2 \odot 2) \oplus (2 \odot 1) = 12 \oplus 3 \oplus 2 = 13. 32 \odot 64 = (16 \odot 2) \odot (16 \odot 4) = (16 \odot 16) \odot (2 \odot 4) = 24 \odot 8 = (16 \oplus 8) \odot 8 = (16 \odot 8) \oplus (8 \odot 8) = 128 \oplus 13 = 141 5 \odot 6 = (4 \oplus 1) \odot (4 \oplus 2) = (4\odot 4) \oplus (4 \odot 2) \oplus (4 \odot 1) \oplus (1 \odot 2) = 6 \oplus 8 \oplus 4 \oplus 2 = 8 Formally, this algorithm can be described by following pseudo-code. multiply(a, b) { ans = 0 for p1 in bits(a) // numbers of bits of a equal to one for p2 in bits(b) // numbers of bits of b equal to one ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2) return ans;}multiply_powers_of_2(a, b) { if (a == 1 or b == 1) return a * b n = maximal value, such 2^{2^{n}} <= max(a, b) power = 2^{2^{n}}; if (a >= power and b >= power) { return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power)) } else if (a >= power) { return multiply_powers_of_2(a / power, b) * power } else { return multiply_powers_of_2(a, b / power) * power }}It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally a^{\odot k} = \underbrace{a \odot a \odot \cdots \odot a}_{k~\texttt{times}}.You need to analyze the proposed scheme strength. For pairs of numbers a and b you need to find such x, that a^{\odot x} = b, or determine that it doesn't exist.
Input: ['7', '2 2', '1 1', '2 3', '8 10', '8 2', '321321321321 2', '123214213213 4356903202345442785', ''] Output:['1', '1', '2', '4', '-1', '6148914691236517205', '68943624821423112', '']
[ 3 ]
VK just opened its second HQ in St. Petersburg! Side of its office building has a huge string s written on its side. This part of the office is supposed to be split into m meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of s written on its side.For each possible arrangement of m meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kth label of the delivery?
Input: ['4 2 1', 'abac', ''] Output:['aba', '']
[ 4 ]
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input: ['5', '3 7 9 7 8', '5 2 5 7 5', ''] Output:['6', '']
[ 2 ]
After a successful year of milk production, Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of n units of grass, each with a sweetness s_i. Farmer John has m cows, each with a favorite sweetness f_i and a hunger value h_i. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats h_i units. The moment a cow eats h_i units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 10^9+7)? The order in which FJ sends the cows does not matter as long as no cows get upset.
Input: ['5 2', '1 1 1 1 1', '1 2', '1 3', ''] Output:['2 2', '']
[ 2, 3, 4 ]
Bessie is out grazing on the farm, which consists of n fields connected by m bidirectional roads. She is currently at field 1, and will return to her home at field n at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has k special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 1 to field n. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!
Input: ['5 5 3', '1 3 5', '1 2', '2 3', '3 4', '3 5', '2 4', ''] Output:['3', '']
[ 2, 4 ]
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6.
Input: ['aaabb', ''] Output:['6', '']
[ 0, 3 ]
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its n favorite numbers: a_1, a_2, ..., a_n. What is the minimum number of hops Rabbit needs to get from (0,0) to (x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (x_i, y_i) and (x_j, y_j) is \sqrt{(x_i-x_j)^2+(y_i-y_j)^2}.For example, if Rabbit has favorite numbers 1 and 3 he could hop from (0,0) to (4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0) in 2 hops (e.g. (0,0) \rightarrow (2,-\sqrt{5}) \rightarrow (4,0)). Here is a graphic for the first example. Both hops have distance 3, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number a_i and hops with distance equal to a_i in any direction he wants. The same number can be used multiple times.
Input: ['42 41 33 123 4 51 552 1015 4'] Output:['2', '3', '1', '2', '']
[ 2, 3 ]
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices i and j (1 <= i, j <= n) such that |i-j|=1 and a_i>0 and apply a_i = a_i - 1, a_j = a_j + 1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 1 (i.e. to maximize a_1), and she only has d days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 1 if she acts optimally!
Input: ['3', '4 5', '1 0 3 2', '2 2', '100 1', '1 8', '0', ''] Output:['3', '101', '0', '']
[ 2 ]
As a professional private tutor, Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him.The exam consists of n questions, and m students have taken the exam. Each question was worth 1 point. Question i was solved by at least l_i and at most r_i students. Additionally, you know that the total score of all students is t.Furthermore, you took a glance at the final ranklist of the quiz. The students were ranked from 1 to m, where rank 1 has the highest score and rank m has the lowest score. Ties were broken arbitrarily.You know that the student at rank p_i had a score of s_i for 1 <= i <= q.You wonder if there could have been a huge tie for first place. Help Kuroni determine the maximum number of students who could have gotten as many points as the student with rank 1, and the maximum possible score for rank 1 achieving this maximum number of students.
Input: ['5 4', '2 4', '2 3', '1 1', '0 1', '0 0', '1', '4 1', '7', ''] Output:['3 2', '']
[ 2, 4 ]
Kuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 0 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). n people have heard about Antihype recently, the i-th person's age is a_i. Some of them are friends, but friendship is a weird thing now: the i-th person is a friend of the j-th person if and only if a_i \text{ AND } a_j = 0, where \text{AND} denotes the bitwise AND operation.Nobody among the n people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them?
Input: ['3', '1 2 3', ''] Output:['2']
[ 0 ]
Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array a consisting of n positive integers. An operation consists of choosing an element and either adding 1 to it or subtracting 1 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 1. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!
Input: ['3', '6 2 4', ''] Output:['0', '']
[ 3 ]
Kuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done, and he is discussing with the team about the score distribution for the round.The round consists of n problems, numbered from 1 to n. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a_1, a_2, ..., a_n, where a_i is the score of i-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 10^9. A harder problem should grant a strictly higher score than an easier problem. In other words, 1 <=q a_1 < a_2 < ... < a_n <=q 10^9. The balance of the score distribution, defined as the number of triples (i, j, k) such that 1 <=q i < j < k <=q n and a_i + a_j = a_k, should be exactly m. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output -1.
Input: ['5 3', ''] Output:['4 5 9 13 18']
[ 2, 3 ]
To become the king of Codeforces, Kuroni has to solve the following problem.He is given n numbers a_1, a_2, ..., a_n. Help Kuroni to calculate \prod_{1<= i<j<= n} |a_i - a_j|. As result can be very big, output it modulo m.If you are not familiar with short notation, \prod_{1<= i<j<= n} |a_i - a_j| is equal to |a_1 - a_2|\cdot|a_1 - a_3|\cdot ... \cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot ... \cdot|a_2 - a_n| \cdot ... \cdot |a_{n-1} - a_n|. In other words, this is the product of |a_i - a_j| for all 1<= i < j <= n.
Input: ['2 10', '8 5', ''] Output:['3']
[ 0, 3 ]
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by n characters '(' or ')' is simple if its length n is even and positive, its first \frac{n}{2} characters are '(', and its last \frac{n}{2} characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input: ['(()((', ''] Output:['1', '2', '1 3 ', '']
[ 2 ]
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets: the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different), the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the i-th daughter receives a necklace with brightness x_i and a bracelet with brightness y_i, then the sums x_i + y_i should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a = [1, 7, 5] and b = [6, 1, 2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a_3 + b_1 = 11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a_1 + b_3 = 3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a_2 + b_2 = 8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a_1 + b_1 = 7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a_2 + b_2 = 8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a_3 + b_3 = 7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!
Input: ['2', '3', '1 8 5', '8 4 5', '3', '1 7 5', '6 1 2', ''] Output:['1 8 5', '8 4 5', '5 1 7', '6 2 1', '']
[ 0, 2 ]
The only difference between easy and hard versions is the constraint on k.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for n days, starting from day 1 to day n. The forest can be divided into m areas, numbered from 1 to m. He'll use the cameras in the following way: On every odd day (1-st, 3-rd, 5-th, ...), bring the red camera to the forest and record a video for 2 days. On every even day (2-nd, 4-th, 6-th, ...), bring the blue camera to the forest and record a video for 2 days. If he starts recording on the n-th day with one of the cameras, the camera records for only one day. Each camera can observe k consecutive areas of the forest. For example, if m=5 and k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3], [2,4], and [3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for n days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.
Input: ['4 5 2', '0 2 1 1 0', '0 0 3 1 2', '1 0 4 3 1', '3 3 0 0 4', ''] Output:['25', '']
[ 2 ]
Gildong recently learned how to find the longest increasing subsequence (LIS) in O(n\log{n}) time for a sequence of length n. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of n distinct integers between 1 and n, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n-1, consisting of characters '<' and '>' only. The i-th (1-indexed) character is the comparison result between the i-th element and the i+1-st element of the sequence. If the i-th character of the string is '<', then the i-th element of the sequence is less than the i+1-st element. If the i-th character of the string is '>', then the i-th element of the sequence is greater than the i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of n distinct integers between 1 and n, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.
Input: ['3', '3 <<', '7 >><>><', '5 >>><', ''] Output:['1 2 3', '1 2 3', '5 4 3 7 2 1 6', '4 3 1 7 5 2 6', '4 3 2 1 5', '5 4 2 1 3', '']
[ 2 ]
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: t_i β€” the time (in minutes) when the i-th customer visits the restaurant, l_i β€” the lower bound of their preferred temperature range, and h_i β€” the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the i-th customer is satisfied if and only if the temperature is between l_i and h_i (inclusive) in the t_i-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
Input: ['4', '3 0', '5 1 2', '7 3 5', '10 -1 0', '2 12', '5 7 10', '10 16 20', '3 -100', '100 0 0', '100 -50 50', '200 100 100', '1 100', '99 -100 0', ''] Output:['YES', 'NO', 'YES', 'NO', '']
[ 2 ]
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input: ['3 3', 'tab', 'one', 'bat', ''] Output:['6', 'tabbat', '']
[ 0, 2 ]
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position x, and the shorter rabbit is currently on position y (x \lt y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by a, and the shorter rabbit hops to the negative direction by b. For example, let's say x=0, y=10, a=2, and b=3. At the 1-st second, each rabbit will be at position 2 and 7. At the 2-nd second, both rabbits will be at position 4.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.
Input: ['5', '0 10 2 3', '0 10 3 3', '900000000 1000000000 1 9999999', '1 2 1 1', '1 3 1 1', ''] Output:['2', '-1', '10', '-1', '1', '']
[ 3 ]
You have a bag of size n. Also you have m boxes. The size of i-th box is a_i, where each a_i is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n = 10 and a = [1, 1, 32] then you have to divide the box of size 32 into two parts of size 16, and then divide the box of size 16. So you can fill the bag with boxes of size 1, 1 and 8.Calculate the minimum number of divisions required to fill the bag of size n.
Input: ['3', '10 3', '1 32 1', '23 4', '16 1 4 1', '20 5', '2 1 16 1 8', ''] Output:['2', '-1', '0', '']
[ 2 ]