question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
Monocarp has got an array a consisting of n integers. Let's denote k as the mathematic mean of these elements (note that it's possible that k is not an integer). The mathematic mean of an array of n elements is the sum of elements divided by the number of these elements (i. e. sum divided by n).Monocarp wants to delete exactly two elements from a so that the mathematic mean of the remaining (n - 2) elements is still equal to k.Your task is to calculate the number of pairs of positions [i, j] (i < j) such that if the elements on these positions are deleted, the mathematic mean of (n - 2) remaining elements is equal to k (that is, it is equal to the mathematic mean of n elements of the original array a).
Input: ['4', '4', '8 8 8 8', '3', '50 20 10', '5', '1 4 7 3 5', '7', '1 2 3 4 5 6 7', ''] Output:['6', '0', '2', '3', '']
[ 3 ]
n students attended the first meeting of the Berland SU programming course (n is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups must be different. Furthermore, both groups should contain the same number of students.Each student has filled a survey in which they told which days of the week are convenient for them to attend a lesson, and which are not. Your task is to determine if it is possible to choose two different week days to schedule the lessons for the group (the first group will attend the lesson on the first chosen day, the second group will attend the lesson on the second chosen day), and divide the students into two groups, so the groups have equal sizes, and for each student, the chosen lesson day for their group is convenient.
Input: ['2', '4', '1 0 0 1 0', '0 1 0 0 1', '0 0 0 1 0', '0 1 0 1 0', '2', '0 0 0 1 0', '0 0 0 1 0', ''] Output:['YES', 'NO', '']
[ 0 ]
Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of 2 rows and n columns. Monocarp controls a character, which starts in cell (1, 1) β€” at the intersection of the 1-st row and the 1-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell (x_1, y_1) to cell (x_2, y_2) in one step if |x_1 - x_2| <= 1 and |y_1 - y_2| <= 1. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell (2, n) β€” at the intersection of row 2 and column n.Help Monocarp determine if it is possible to complete the level.
Input: ['4', '3', '000', '000', '4', '0011', '1100', '4', '0111', '1110', '6', '010101', '101010', ''] Output:['YES', 'YES', 'NO', 'YES', '']
[ 0 ]
Theofanis decided to visit his uncle's farm. There are s animals and n animal pens on the farm. For utility purpose, animal pens are constructed in one row.Uncle told Theofanis that a farm is lucky if you can distribute all animals in all pens in such a way that there are no empty pens and there is at least one continuous segment of pens that has exactly k animals in total.Moreover, a farm is ideal if it's lucky for any distribution without empty pens.Neither Theofanis nor his uncle knows if their farm is ideal or not. Can you help them to figure it out?
Input: ['4', '1 1 1', '1 1 2', '100 50 200', '56220 47258 14497', ''] Output:['YES', 'NO', 'NO', 'YES', '']
[ 3 ]
It is the hard version of the problem. The difference is that in this version, there are nodes with already chosen colors.Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?You have a perfect binary tree of 2^k - 1 nodes β€” a binary tree where all vertices i from 1 to 2^{k - 1} - 1 have exactly two children: vertices 2i and 2i + 1. Vertices from 2^{k - 1} to 2^k - 1 don't have any children. You want to color its vertices with the 6 Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).Let's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube. A picture of Rubik's cube and its 2D map. More formally: a white node can not be neighboring with white and yellow nodes; a yellow node can not be neighboring with white and yellow nodes; a green node can not be neighboring with green and blue nodes; a blue node can not be neighboring with green and blue nodes; a red node can not be neighboring with red and orange nodes; an orange node can not be neighboring with red and orange nodes; However, there are n special nodes in the tree, colors of which are already chosen.You want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.The answer may be too large, so output the answer modulo 10^9+7.
Input: ['3', '2', '5 orange', '2 white', ''] Output:['1024', '']
[ 0, 3 ]
It is the easy version of the problem. The difference is that in this version, there are no nodes with already chosen colors.Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?You have a perfect binary tree of 2^k - 1 nodes β€” a binary tree where all vertices i from 1 to 2^{k - 1} - 1 have exactly two children: vertices 2i and 2i + 1. Vertices from 2^{k - 1} to 2^k - 1 don't have any children. You want to color its vertices with the 6 Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).Let's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube. A picture of Rubik's cube and its 2D map. More formally: a white node can not be neighboring with white and yellow nodes; a yellow node can not be neighboring with white and yellow nodes; a green node can not be neighboring with green and blue nodes; a blue node can not be neighboring with green and blue nodes; a red node can not be neighboring with red and orange nodes; an orange node can not be neighboring with red and orange nodes; You want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.The answer may be too large, so output the answer modulo 10^9+7.
Input: ['3', ''] Output:['24576', '']
[ 3 ]
Theofanis has a string s_1 s_2 ... s_n and a character c. He wants to make all characters of the string equal to c using the minimum number of operations.In one operation he can choose a number x (1 <= x <= n) and for every position i, where i is not divisible by x, replace s_i with c. Find the minimum number of operations required to make all the characters equal to c and the x-s that he should use in his operations.
Input: ['3', '4 a', 'aaaa', '4 a', 'baaa', '4 b', 'bzyx', ''] Output:['0', '1', '2', '2 ', '2 3', '']
[ 0, 2, 3 ]
Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.Let's call a positive number special if it can be written as a sum of different non-negative powers of n. For example, for n = 4 number 17 is special, because it can be written as 4^0 + 4^2 = 1 + 16 = 17, but 9 is not.Theofanis asks you to help him find the k-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo 10^9+7.
Input: ['3', '3 4', '2 12', '105 564', ''] Output:['9', '12', '3595374', '']
[ 3 ]
Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).You are given an integer n. You need to find two integers l and r such that -10^{18} <= l < r <= 10^{18} and l + (l + 1) + ... + (r - 1) + r = n.
Input: ['7', '1', '2', '3', '6', '100', '25', '3000000000000', ''] Output:['0 1', '-1 2 ', '1 2 ', '1 3 ', '18 22', '-2 7', '999999999999 1000000000001']
[ 3 ]
A sequence of round and square brackets is given. You can change the sequence by performing the following operations: change the direction of a bracket from opening to closing and vice versa without changing the form of the bracket: i.e. you can change '(' to ')' and ')' to '('; you can change '[' to ']' and ']' to '['. The operation costs 0 burles. change any square bracket to round bracket having the same direction: i.e. you can change '[' to '(' but not from '(' to '['; similarly, you can change ']' to ')' but not from ')' to ']'. The operation costs 1 burle. The operations can be performed in any order any number of times.You are given a string s of the length n and q queries of the type "l r" where 1 <= l < r <= n. For every substring s[l ... r], find the minimum cost to pay to make it a correct bracket sequence. It is guaranteed that the substring s[l ... r] has an even length.The queries must be processed independently, i.e. the changes made in the string for the answer to a question i don't affect the queries j (j > i). In other words, for every query, the substring s[l ... r] is given from the initially given string s.A correct bracket sequence is a sequence that can be built according the following rules: an empty sequence is a correct bracket sequence; if "s" is a correct bracket sequence, the sequences "(s)" and "[s]" are correct bracket sequences. if "s" and "t" are correct bracket sequences, the sequence "st" (the concatenation of the sequences) is a correct bracket sequence. E.g. the sequences "", "(()[])", "[()()]()" and "(())()" are correct bracket sequences whereas "(", "[(])" and ")))" are not.
Input: ['3', '([))[)()][]]', '3', '1 12', '4 9', '3 6', '))))))', '2', '2 3', '1 4', '[]', '1', '1 2', ''] Output:['0', '2', '1', '0', '0', '0', '']
[ 2 ]
It is given a non-negative integer x, the decimal representation of which contains n digits. You need to color each its digit in red or black, so that the number formed by the red digits is divisible by A, and the number formed by the black digits is divisible by B.At least one digit must be colored in each of two colors. Consider, the count of digits colored in red is r and the count of digits colored in black is b. Among all possible colorings of the given number x, you need to output any such that the value of |r - b| is the minimum possible.Note that the number x and the numbers formed by digits of each color, may contain leading zeros. Example of painting a number for A = 3 and B = 13 The figure above shows an example of painting the number x = 02165 of n = 5 digits for A = 3 and B = 13. The red digits form the number 015, which is divisible by 3, and the black ones β€” 26, which is divisible by 13. Note that the absolute value of the difference between the counts of red and black digits is 1, it is impossible to achieve a smaller value.
Input: ['4', '5 3 13', '02165', '4 2 1', '1357', '8 1 1', '12345678', '2 7 9', '90', ''] Output:['RBRBR', '-1', 'BBRRRRBB', 'BR', '']
[ 3 ]
A tree is an undirected connected graph in which there are no cycles. This problem is about non-rooted trees. A leaf of a tree is a vertex that is connected to at most one vertex.The gardener Vitaly grew a tree from n vertices. He decided to trim the tree. To do this, he performs a number of operations. In one operation, he removes all leaves of the tree. Example of a tree. For example, consider the tree shown in the figure above. The figure below shows the result of applying exactly one operation to the tree. The result of applying the operation "remove all leaves" to the tree. Note the special cases of the operation: applying an operation to an empty tree (of 0 vertices) does not change it; applying an operation to a tree of one vertex removes this vertex (this vertex is treated as a leaf); applying an operation to a tree of two vertices removes both vertices (both vertices are treated as leaves). Vitaly applied k operations sequentially to the tree. How many vertices remain?
Input: ['6', '', '14 1', '1 2', '2 3', '2 4', '4 5', '4 6', '2 7', '7 8', '8 9', '8 10', '3 11', '3 12', '1 13', '13 14', '', '2 200000', '1 2', '', '3 2', '1 2', '2 3', '', '5 1', '5 1', '3 2', '2 1', '5 4', '', '6 2', '5 1', '2 5', '5 6', '4 2', '3 4', '', '7 1', '4 3', '5 1', '1 3', '6 1', '1 7', '2 1', ''] Output:['7', '0', '0', '3', '1', '2', '']
[ 0, 2 ]
This problem is a complicated version of D1, but it has significant differences, so read the whole statement.Polycarp has an array of n (n is even) integers a_1, a_2, ..., a_n. Polycarp conceived of a positive integer k. After that, Polycarp began performing the following operations on the array: take an index i (1 <= i <= n) and reduce the number a_i by k.After Polycarp performed some (possibly zero) number of such operations, it turned out that at least half of the numbers in the array became the same. Find the maximum k at which such a situation is possible, or print -1 if such a number can be arbitrarily large.
Input: ['4', '6', '48 13 22 -15 16 35', '8', '-1 0 1 -1 0 1 -1 0', '4', '100 -1000 -1000 -1000', '4', '1 1 1 1', ''] Output:['13', '2', '-1', '-1', '']
[ 0, 3 ]
This problem is a simplified version of D2, but it has significant differences, so read the whole statement.Polycarp has an array of n (n is even) integers a_1, a_2, ..., a_n. Polycarp conceived of a positive integer k. After that, Polycarp began performing the following operations on the array: take an index i (1 <= i <= n) and reduce the number a_i by k.After Polycarp performed some (possibly zero) number of such operations, it turned out that all numbers in the array became the same. Find the maximum k at which such a situation is possible, or print -1 if such a number can be arbitrarily large.
Input: ['3', '6', '1 5 3 1 1 5', '8', '-1 0 1 -1 0 1 -1 0', '4', '100 -1000 -1000 -1000', ''] Output:['2', '1', '1100', '']
[ 3 ]
There are one cat, k mice, and one hole on a coordinate line. The cat is located at the point 0, the hole is located at the point n. All mice are located between the cat and the hole: the i-th mouse is located at the point x_i (0 < x_i < n). At each point, many mice can be located.In one second, the following happens. First, exactly one mouse moves to the right by 1. If the mouse reaches the hole, it hides (i.e. the mouse will not any more move to any point and will not be eaten by the cat). Then (after that the mouse has finished its move) the cat moves to the right by 1. If at the new cat's position, some mice are located, the cat eats them (they will not be able to move after that). The actions are performed until any mouse hasn't been hidden or isn't eaten.In other words, the first move is made by a mouse. If the mouse has reached the hole, it's saved. Then the cat makes a move. The cat eats the mice located at the pointed the cat has reached (if the cat has reached the hole, it eats nobody).Each second, you can select a mouse that will make a move. What is the maximum number of mice that can reach the hole without being eaten?
Input: ['3', '10 6', '8 7 5 4 9 4', '2 8', '1 1 1 1 1 1 1 1', '12 11', '1 2 3 4 5 6 7 8 9 10 11', ''] Output:['3', '1', '4', '']
[ 2, 2, 4 ]
It is given a positive integer n. In 1 move, one can select any single digit and remove it (i.e. one selects some position in the number and removes the digit located at this position). The operation cannot be performed if only one digit remains. If the resulting number contains leading zeroes, they are automatically removed.E.g. if one removes from the number 32925 the 3-rd digit, the resulting number will be 3225. If one removes from the number 20099050 the first digit, the resulting number will be 99050 (the 2 zeroes going next to the first digit are automatically removed).What is the minimum number of steps to get a number such that it is divisible by 25 and positive? It is guaranteed that, for each n occurring in the input, the answer exists. It is guaranteed that the number n has no leading zeros.
Input: ['5', '100', '71345', '3259', '50555', '2050047', ''] Output:['0', '3', '1', '3', '2', '']
[ 2, 3, 3 ]
The elections in which three candidates participated have recently ended. The first candidate received a votes, the second one received b votes, the third one received c votes. For each candidate, solve the following problem: how many votes should be added to this candidate so that he wins the election (i.e. the number of votes for this candidate was strictly greater than the number of votes for any other candidate)?Please note that for each candidate it is necessary to solve this problem independently, i.e. the added votes for any candidate do not affect the calculations when getting the answer for the other two candidates.
Input: ['5', '0 0 0', '10 75 15', '13 13 17', '1000 0 0', '0 1000000000 0', ''] Output:['1 1 1', '66 0 61', '5 5 0', '0 1001 1001', '1000000001 0 1000000001', '']
[ 3 ]
The difference between the versions is in the costs of operations. Solution for one version won't work for another!Alice has a grid of size n * m, initially all its cells are colored white. The cell on the intersection of i-th row and j-th column is denoted as (i, j). Alice can do the following operations with this grid:Choose any subrectangle containing cell (1, 1), and flip the colors of all its cells. (Flipping means changing its color from white to black or from black to white). This operation costs 1 coin.Choose any subrectangle containing cell (n, 1), and flip the colors of all its cells. This operation costs 3 coins.Choose any subrectangle containing cell (1, m), and flip the colors of all its cells. This operation costs 4 coins.Choose any subrectangle containing cell (n, m), and flip the colors of all its cells. This operation costs 2 coins. As a reminder, subrectangle is a set of all cells (x, y) with x_1 <= x <= x_2, y_1 <= y <= y_2 for some 1 <= x_1 <= x_2 <= n, 1 <= y_1 <= y_2 <= m.Alice wants to obtain her favorite coloring with these operations. What's the smallest number of coins that she would have to spend? It can be shown that it's always possible to transform the initial grid into any other.
Input: ['3 3', 'WWW', 'WBB', 'WBB', ''] Output:['2', '']
[ 2 ]
The difference between the versions is in the costs of operations. Solution for one version won't work for another!Alice has a grid of size n * m, initially all its cells are colored white. The cell on the intersection of i-th row and j-th column is denoted as (i, j). Alice can do the following operations with this grid:Choose any subrectangle containing cell (1, 1), and flip the colors of all its cells. (Flipping means changing its color from white to black or from black to white). This operation costs 1 coin.Choose any subrectangle containing cell (n, 1), and flip the colors of all its cells. This operation costs 2 coins.Choose any subrectangle containing cell (1, m), and flip the colors of all its cells. This operation costs 4 coins.Choose any subrectangle containing cell (n, m), and flip the colors of all its cells. This operation costs 3 coins. As a reminder, subrectangle is a set of all cells (x, y) with x_1 <= x <= x_2, y_1 <= y <= y_2 for some 1 <= x_1 <= x_2 <= n, 1 <= y_1 <= y_2 <= m.Alice wants to obtain her favorite coloring with these operations. What's the smallest number of coins that she would have to spend? It can be shown that it's always possible to transform the initial grid into any other.
Input: ['3 3', 'WWW', 'WBB', 'WBB', ''] Output:['3', '']
[ 2 ]
Bakry got bored of solving problems related to xor, so he asked you to solve this problem for him.You are given an array a of n integers [a_1, a_2, ..., a_n].Let's call a subarray a_{l}, a_{l+1}, a_{l+2}, ..., a_r good if a_l \, \& \, a_{l+1} \, \& \, a_{l+2} \, ... \, \& \, a_r > a_l \oplus a_{l+1} \oplus a_{l+2} ... \oplus a_r, where \oplus denotes the bitwise XOR operation and \& denotes the bitwise AND operation.Find the length of the longest good subarray of a, or determine that no such subarray exists.
Input: ['2', '5 6', ''] Output:['2', '']
[ 2, 3 ]
This is an interactive problem!In the last regional contest Hemose, ZeyadKhattab and YahiaSherif β€” members of the team Carpe Diem β€” did not qualify to ICPC because of some unknown reasons. Hemose was very sad and had a bad day after the contest, but ZeyadKhattab is very wise and knows Hemose very well, and does not want to see him sad.Zeyad knows that Hemose loves tree problems, so he gave him a tree problem with a very special device.Hemose has a weighted tree with n nodes and n-1 edges. Unfortunately, Hemose doesn't remember the weights of edges.Let's define Dist(u, v) for u\neq v as the greatest common divisor of the weights of all edges on the path from node u to node v.Hemose has a special device. Hemose can give the device a set of nodes, and the device will return the largest Dist between any two nodes from the set. More formally, if Hemose gives the device a set S of nodes, the device will return the largest value of Dist(u, v) over all pairs (u, v) with u, v \in S and u \neq v.Hemose can use this Device at most 12 times, and wants to find any two distinct nodes a, b, such that Dist(a, b) is maximum possible. Can you help him?
Input: ['6', '1 2', '2 3', '2 4', '1 5', '5 6', '', '10', '', '2', '', '10'] Output:['? 6 1 2 3 4 5 6', '', '? 3 3 1 5', '', '? 2 1 2', '', '! 1 2']
[ 3, 4 ]
Hemose was shopping with his friends Samez, AhmedZ, AshrafEzz, TheSawan and O_E in Germany. As you know, Hemose and his friends are problem solvers, so they are very clever. Therefore, they will go to all discount markets in Germany.Hemose has an array of n integers. He wants Samez to sort the array in the non-decreasing order. Since it would be a too easy problem for Samez, Hemose allows Samez to use only the following operation:Choose indices i and j such that 1 <= i, j <= n, and \lvert i - j \rvert >=q x. Then, swap elements a_i and a_j.Can you tell Samez if there's a way to sort the array in the non-decreasing order by using the operation written above some finite number of times (possibly 0)?
Input: ['4', '3 3', '3 2 1', '4 3', '1 2 3 4', '5 2', '5 1 2 3 4', '5 4', '1 2 3 4 4', ''] Output:['NO', 'YES', 'YES', 'YES', '']
[ 3 ]
One day, Ahmed_Hossam went to Hemose and said "Let's solve a gym contest!". Hemose didn't want to do that, as he was playing Valorant, so he came up with a problem and told it to Ahmed to distract him. Sadly, Ahmed can't solve it... Could you help him?There is an Agent in Valorant, and he has n weapons. The i-th weapon has a damage value a_i, and the Agent will face an enemy whose health value is H.The Agent will perform one or more moves until the enemy dies.In one move, he will choose a weapon and decrease the enemy's health by its damage value. The enemy will die when his health will become less than or equal to 0. However, not everything is so easy: the Agent can't choose the same weapon for 2 times in a row.What is the minimum number of times that the Agent will need to use the weapons to kill the enemy?
Input: ['3', '2 4', '3 7', '2 6', '4 2', '3 11', '2 1 7', ''] Output:['1', '2', '3', '']
[ 2, 3, 4 ]
You are given an array of integers a of size n and a permutation p of size n. There are q queries of three types coming to you: For given numbers l and r, calculate the sum in array a on the segment from l to r: \sum\limits_{i=l}^{r} a_i. You are given two numbers v and x. Let's build a directed graph from the permutation p: it has n vertices and n edges i \to p_i. Let C be the set of vertices that are reachable from v in this graph. You should add x to all a_u such that u is in C. You are given indices i and j. You should swap p_i and p_j. The graph corresponding to the permutation [2, 3, 1, 5, 4]. Please, process all queries and print answers to queries of type 1.
Input: ['5', '6 9 -5 3 0', '2 3 1 5 4', '6', '1 1 5', '2 1 1', '1 1 5', '3 1 5', '2 1 -1', '1 1 5', ''] Output:['13', '16', '11', '']
[ 4 ]
Omkar is creating a mosaic using colored square tiles, which he places in an n * n grid. When the mosaic is complete, each cell in the grid will have either a glaucous or sinoper tile. However, currently he has only placed tiles in some cells. A completed mosaic will be a mastapeece if and only if each tile is adjacent to exactly 2 tiles of the same color (2 tiles are adjacent if they share a side.) Omkar wants to fill the rest of the tiles so that the mosaic becomes a mastapeece. Now he is wondering, is the way to do this unique, and if it is, what is it?
Input: ['4', 'S...', '..G.', '....', '...S', ''] Output:['MULTIPLE', '']
[ 3 ]
You are given an array of n positive integers a_1, a_2, ..., a_n. Your task is to calculate the number of arrays of n positive integers b_1, b_2, ..., b_n such that: 1 <= b_i <= a_i for every i (1 <= i <= n), and b_i \neq b_{i+1} for every i (1 <= i <= n - 1). The number of such arrays can be very large, so print it modulo 998\,244\,353.
Input: ['3', '2 2 2', ''] Output:['2']
[ 3 ]
Petya has an array of integers a_1, a_2, ..., a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 <=q i, j, k <=q n) and apply i \to j \to k \to i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input: ['7', '1', '1', '2', '2 2', '2', '2 1', '3', '1 2 3', '3', '2 1 3', '3', '3 1 2', '4', '2 1 4 3', ''] Output:['YES', 'YES', 'NO', 'YES', 'NO', 'YES', 'YES', '']
[ 3 ]
A total of n depots are located on a number line. Depot i lies at the point x_i for 1 <= i <= n.You are a salesman with n bags of goods, attempting to deliver one bag to each of the n depots. You and the n bags are initially at the origin 0. You can carry up to k bags at a time. You must collect the required number of goods from the origin, deliver them to the respective depots, and then return to the origin to collect your next batch of goods.Calculate the minimum distance you need to cover to deliver all the bags of goods to the depots. You do not have to return to the origin after you have delivered all the bags.
Input: ['4', '5 1', '1 2 3 4 5', '9 3', '-5 -10 -15 6 5 8 3 7 4', '5 3', '2 2 3 3 3', '4 2', '1000000000 1000000000 1000000000 1000000000', ''] Output:['25', '41', '7', '3000000000', '']
[ 2 ]
You are given an array a of length n.Let's define the eversion operation. Let x = a_n. Then array a is partitioned into two parts: left and right. The left part contains the elements of a that are not greater than x (<= x). The right part contains the elements of a that are strictly greater than x (> x). The order of elements in each part is kept the same as before the operation, i. e. the partition is stable. Then the array is replaced with the concatenation of the left and the right parts.For example, if the array a is [2, 4, 1, 5, 3], the eversion goes like this: [2, 4, 1, 5, 3] \to [2, 1, 3], [4, 5] \to [2, 1, 3, 4, 5].We start with the array a and perform eversions on this array. We can prove that after several eversions the array a stops changing. Output the minimum number k such that the array stops changing after k eversions.
Input: ['3', '5', '2 4 1 5 3', '5', '5 3 2 4 1', '4', '1 1 1 1', ''] Output:['1', '2', '0', '']
[ 2 ]
You are given n strings s_1, s_2, ..., s_n, each consisting of lowercase and uppercase English letters. In addition, it's guaranteed that each character occurs in each string at most twice. Find the longest common subsequence of these strings.A string t is a subsequence of a string s if t can be obtained from s by deletion of several (possibly, zero or all) symbols.
Input: ['4', '2', 'ABC', 'CBA', '2', 'bacab', 'defed', '3', 'abcde', 'aBcDe', 'ace', '2', 'codeforces', 'technocup', ''] Output:['1', 'A', '0', '', '3', 'ace', '3', 'coc', '']
[ 2 ]
Bob decided to take a break from calculus homework and designed a game for himself. The game is played on a sequence of piles of stones, which can be described with a sequence of integers s_1, ..., s_k, where s_i is the number of stones in the i-th pile. On each turn, Bob picks a pair of non-empty adjacent piles i and i+1 and takes one stone from each. If a pile becomes empty, its adjacent piles do not become adjacent. The game ends when Bob can't make turns anymore. Bob considers himself a winner if at the end all piles are empty.We consider a sequence of piles winning if Bob can start with it and win with some sequence of moves.You are given a sequence a_1, ..., a_n, count the number of subsegments of a that describe a winning sequence of piles. In other words find the number of segments [l, r] (1 <=q l <=q r <=q n), such that the sequence a_l, a_{l+1}, ..., a_r is winning.
Input: ['6', '2', '2 2', '3', '1 2 3', '4', '1 1 1 1', '4', '1 2 2 1', '4', '1 2 1 2', '8', '1 2 1 2 1 2 1 2', ''] Output:['1', '0', '4', '2', '1', '3', '']
[ 2, 4 ]
This is an interactive problem.Jury initially had a sequence a of length n, such that a_i = i.The jury chose three integers i, j, k, such that 1 <=q i < j < k <=q n, j - i > 1. After that, Jury reversed subsegments [i, j - 1] and [j, k] of the sequence a.Reversing a subsegment [l, r] of the sequence a means reversing the order of elements a_l, a_{l+1}, ..., a_r in the sequence, i. e. a_l is swapped with a_r, a_{l+1} is swapped with a_{r-1}, etc.You are given the number n and you should find i, j, k after asking some questions.In one question you can choose two integers l and r (1 <=q l <=q r <=q n) and ask the number of inversions on the subsegment [l, r] of the sequence a. You will be given the number of pairs (i, j) such that l <=q i < j <=q r, and a_i > a_j.Find the chosen numbers i, j, k after at most 40 questions.The numbers i, j, and k are fixed before the start of your program and do not depend on your queries.
Input: ['2 ', '5 ', '', '4 ', '', '3 ', '', '3 ', '', '5 ', '', '2 ', '', '2 ', '', '1 '] Output:['', '', '? 1 5', '', '? 2 5', '', '? 3 5', '', '! 1 3 5', '', '? 1 5', '', '? 2 5', '', '? 3 5', '', '! 2 4 5']
[ 3, 4 ]
You are given two arrays of integers a_1, a_2, ..., a_n and b_1, b_2, ..., b_n.Let's define a transformation of the array a: Choose any non-negative integer k such that 0 <= k <= n. Choose k distinct array indices 1 <= i_1 < i_2 < ... < i_k <= n. Add 1 to each of a_{i_1}, a_{i_2}, ..., a_{i_k}, all other elements of array a remain unchanged. Permute the elements of array a in any order. Is it possible to perform some transformation of the array a exactly once, so that the resulting array is equal to b?
Input: ['3', '3', '-1 1 0', '0 0 2', '1', '0', '2', '5', '1 2 3 4 5', '1 2 3 4 5', ''] Output:['YES', 'NO', 'YES', '']
[ 2, 3 ]
David was given a red checkered rectangle of size n * m. But he doesn't like it. So David cuts the original or any other rectangle piece obtained during the cutting into two new pieces along the grid lines. He can do this operation as many times as he wants.As a result, he will get a set of rectangles. Rectangles 1 * 1 are forbidden.David also knows how to paint the cells blue. He wants each rectangle from the resulting set of pieces to be colored such that any pair of adjacent cells by side (from the same piece) have different colors.What is the minimum number of cells David will have to paint?
Input: ['4', '1 3', '2 2', '2 5', '3 5', ''] Output:['1', '2', '4', '5', '']
[ 2, 3 ]
Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form: You are given two positive integers u and v, find any pair of integers (not necessarily positive) x, y, such that: \frac{x}{u} + \frac{y}{v} = \frac{x + y}{u + v}. The solution x = 0, y = 0 is forbidden, so you should find any solution with (x, y) \neq (0, 0). Please help Ivan to solve some equations of this form.
Input: ['4', '1 1', '2 3', '3 5', '6 9', ''] Output:['-1 1', '-4 9', '-18 50', '-4 9', '']
[ 3 ]
El Psy Kongroo.Omkar is watching Steins;Gate.In Steins;Gate, Okabe Rintarou needs to complete n tasks (1 <=q n <=q 2 \cdot 10^5). Unfortunately, he doesn't know when he needs to complete the tasks.Initially, the time is 0. Time travel will now happen according to the following rules:For each k = 1, 2, ..., n, Okabe will realize at time b_k that he was supposed to complete the k-th task at time a_k (a_k < b_k). When he realizes this, if k-th task was already completed at time a_k, Okabe keeps the usual flow of time. Otherwise, he time travels to time a_k then immediately completes the task.If Okabe time travels to time a_k, all tasks completed after this time will become incomplete again. That is, for every j, if a_j>a_k, the j-th task will become incomplete, if it was complete (if it was incomplete, nothing will change).Okabe has bad memory, so he can time travel to time a_k only immediately after getting to time b_k and learning that he was supposed to complete the k-th task at time a_k. That is, even if Okabe already had to perform k-th task before, he wouldn't remember it before stumbling on the info about this task at time b_k again.Please refer to the notes for an example of time travelling.There is a certain set s of tasks such that the first moment that all of the tasks in s are simultaneously completed (regardless of whether any other tasks are currently completed), a funny scene will take place. Omkar loves this scene and wants to know how many times Okabe will time travel before this scene takes place. Find this number modulo 10^9 + 7. It can be proven that eventually all n tasks will be completed and so the answer always exists.
Input: ['2', '1 4', '2 3', '2', '1 2', ''] Output:['3', '']
[ 3 ]
She does her utmost to flawlessly carry out a person's last rites and preserve the world's balance of yin and yang.Hu Tao, being the little prankster she is, has tried to scare you with this graph problem! You are given a connected undirected graph of n nodes with m edges. You also have q queries. Each query consists of two nodes a and b.Initially, all edges in the graph have a weight of 0. For each query, you must choose a simple path starting from a and ending at b. Then you add 1 to every edge along this path. Determine if it's possible, after processing all q queries, for all edges in this graph to have an even weight. If so, output the choice of paths for each query. If it is not possible, determine the smallest number of extra queries you could add to make it possible. It can be shown that this number will not exceed 10^{18} under the given constraints.A simple path is defined as any path that does not visit a node more than once.An edge is said to have an even weight if its value is divisible by 2.
Input: ['6 7', '2 1', '2 3', '3 5', '1 4', '6 1', '5 6', '4 5', '3', '1 4', '5 1', '4 5', ''] Output:['YES', '2', '1 4', '4', '5 3 2 1', '5', '4 1 2 3 5', '']
[ 2 ]
It turns out that the meaning of life is a permutation p_1, p_2, ..., p_n of the integers 1, 2, ..., n (2 <=q n <=q 100). Omkar, having created all life, knows this permutation, and will allow you to figure it out using some queries.A query consists of an array a_1, a_2, ..., a_n of integers between 1 and n. a is not required to be a permutation. Omkar will first compute the pairwise sum of a and p, meaning that he will compute an array s where s_j = p_j + a_j for all j = 1, 2, ..., n. Then, he will find the smallest index k such that s_k occurs more than once in s, and answer with k. If there is no such index k, then he will answer with 0.You can perform at most 2n queries. Figure out the meaning of life p.
Input: ['5', '', '2', '', '0', '', '1', ''] Output:['', '? 4 4 2 3 2', '', '? 3 5 1 5 5', '', '? 5 2 4 3 1', '', '! 3 2 1 5 4', '']
[ 2 ]
A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of n (n >= 3) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer x is called composite if there exists a positive integer y such that 1 < y < x and x is divisible by y.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.
Input: ['4', '3', '8 1 2', '4', '6 9 4 2', '9', '1 2 3 4 5 6 7 8 9', '3', '200 199 198', ''] Output:['2', '2 1', '4', '2 1 4 3', '9', '6 9 1 2 3 4 5 7 8', '3', '1 2 3 ', '']
[ 3 ]
This is a harder version of the problem with bigger constraints.Korney Korneevich dag up an array a of length n. Korney Korneevich has recently read about the operation bitwise XOR, so he wished to experiment with it. For this purpose, he decided to find all integers x >= 0 such that there exists an increasing subsequence of the array a, in which the bitwise XOR of numbers is equal to x.It didn't take a long time for Korney Korneevich to find all such x, and he wants to check his result. That's why he asked you to solve this problem!A sequence s is a subsequence of a sequence b if s can be obtained from b by deletion of several (possibly, zero or all) elements.A sequence s_1, s_2, ... , s_m is called increasing if s_1 < s_2 < ... < s_m.
Input: ['4', '4 2 2 4', ''] Output:['4', '0 2 4 6 ', '']
[ 0, 2, 4 ]
This is an easier version of the problem with smaller constraints.Korney Korneevich dag up an array a of length n. Korney Korneevich has recently read about the operation bitwise XOR, so he wished to experiment with it. For this purpose, he decided to find all integers x >= 0 such that there exists an increasing subsequence of the array a, in which the bitwise XOR of numbers is equal to x.It didn't take a long time for Korney Korneevich to find all such x, and he wants to check his result. That's why he asked you to solve this problem!A sequence s is a subsequence of a sequence b if s can be obtained from b by deletion of several (possibly, zero or all) elements.A sequence s_1, s_2, ... , s_m is called increasing if s_1 < s_2 < ... < s_m.
Input: ['4', '4 2 2 4', ''] Output:['4', '0 2 4 6 ', '']
[ 2 ]
Pchelyonok decided to give Mila a gift. Pchelenok has already bought an array a of length n, but gifting an array is too common. Instead of that, he decided to gift Mila the segments of that array!Pchelyonok wants his gift to be beautiful, so he decided to choose k non-overlapping segments of the array [l_1,r_1], [l_2,r_2], ... [l_k,r_k] such that: the length of the first segment [l_1,r_1] is k, the length of the second segment [l_2,r_2] is k-1, ..., the length of the k-th segment [l_k,r_k] is 1 for each i<j, the i-th segment occurs in the array earlier than the j-th (i.e. r_i<l_j) the sums in these segments are strictly increasing (i.e. let sum(l ... r) = \sum\limits_{i=l}^{r} a_i β€” the sum of numbers in the segment [l,r] of the array, then sum(l_1 ... r_1) < sum(l_2 ... r_2) < ... < sum(l_k ... r_k)). Pchelenok also wants his gift to be as beautiful as possible, so he asks you to find the maximal value of k such that he can give Mila a gift!
Input: ['5', '1', '1', '3', '1 2 3', '5', '1 1 2 2 3', '7', '1 2 1 1 3 2 6', '5', '9 6 7 9 7', ''] Output:['1', '1', '2', '3', '1', '']
[ 2, 3, 4 ]
Vupsen and Pupsen were gifted an integer array. Since Vupsen doesn't like the number 0, he threw away all numbers equal to 0 from the array. As a result, he got an array a of length n.Pupsen, on the contrary, likes the number 0 and he got upset when he saw the array without zeroes. To cheer Pupsen up, Vupsen decided to come up with another array b of length n such that \sum_{i=1}^{n}a_i \cdot b_i=0. Since Vupsen doesn't like number 0, the array b must not contain numbers equal to 0. Also, the numbers in that array must not be huge, so the sum of their absolute values cannot exceed 10^9. Please help Vupsen to find any such array b!
Input: ['3', '2', '5 5', '5', '5 -2 10 -9 4', '7', '1 2 3 4 5 6 7', ''] Output:['1 -1', '-1 5 1 -1 -1', '-10 2 2 -3 5 -1 -1', '']
[ 3 ]
Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string s of length n.Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string s.She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string s a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.
Input: ['5', '8', 'abcaacab', '6', 'xyzxyz', '4', 'abba', '8', 'rprarlap', '10', 'khyyhhyhky', ''] Output:['2', '-1', '0', '3', '2', '']
[ 0, 2 ]
Luntik came out for a morning stroll and found an array a of length n. He calculated the sum s of the elements of the array (s= \sum_{i=1}^{n} a_i). Luntik calls a subsequence of the array a nearly full if the sum of the numbers in that subsequence is equal to s-1.Luntik really wants to know the number of nearly full subsequences of the array a. But he needs to come home so he asks you to solve that problem!A sequence x is a subsequence of a sequence y if x can be obtained from y by deletion of several (possibly, zero or all) elements.
Input: ['5', '5', '1 2 3 4 5', '2', '1000 1000', '2', '1 0', '5', '3 0 2 1 1', '5', '2 1 0 3 0', ''] Output:['1', '0', '2', '4', '4', '']
[ 3 ]
Luntik has decided to try singing. He has a one-minute songs, b two-minute songs and c three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.He wants to make the absolute difference of durations of the concerts as small as possible. The duration of the concert is the sum of durations of all songs in that concert.Please help Luntik and find the minimal possible difference in minutes between the concerts durations.
Input: ['4', '1 1 1', '2 1 3', '5 5 5', '1 1 2', ''] Output:['0', '1', '0', '1', '']
[ 3 ]
CQXYM wants to create a connected undirected graph with n nodes and m edges, and the diameter of the graph must be strictly less than k-1. Also, CQXYM doesn't want a graph that contains self-loops or multiple edges (i.e. each edge connects two different vertices and between each pair of vertices there is at most one edge).The diameter of a graph is the maximum distance between any two nodes.The distance between two nodes is the minimum number of the edges on the path which endpoints are the two nodes.CQXYM wonders whether it is possible to create such a graph.
Input: ['5', '1 0 3', '4 5 3', '4 6 3', '5 4 1', '2 1 1', ''] Output:['YES', 'NO', 'YES', 'NO', 'NO', '']
[ 2, 3 ]
CQXYM is counting permutations length of 2n.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).A permutation p(length of 2n) will be counted only if the number of i satisfying p_i<p_{i+1} is no less than n. For example: Permutation [1, 2, 3, 4] will count, because the number of such i that p_i<p_{i+1} equals 3 (i = 1, i = 2, i = 3). Permutation [3, 2, 1, 4] won't count, because the number of such i that p_i<p_{i+1} equals 1 (i = 3). CQXYM wants you to help him to count the number of such permutations modulo 1000000007 (10^9+7).In addition, modulo operation is to get the remainder. For example: 7 \mod 3=1, because 7 = 3 \cdot 2 + 1, 15 \mod 4=3, because 15 = 4 \cdot 3 + 3.
Input: ['4', '1', '2', '9', '91234', ''] Output:['1', '12', '830455698', '890287984', '']
[ 3 ]
XYMXYM and CQXYM will prepare n problems for Codeforces. The difficulty of the problem i will be an integer a_i, where a_i >=q 0. The difficulty of the problems must satisfy a_i+a_{i+1}<m (1 <=q i < n), and a_1+a_n<m, where m is a fixed integer. XYMXYM wants to know how many plans of the difficulty of the problems there are modulo 998\,244\,353.Two plans of difficulty a and b are different only if there is an integer i (1 <=q i <=q n) satisfying a_i \neq b_i.
Input: ['3 2', ''] Output:['4', '']
[ 3 ]
Because the railway system in Gensokyo is often congested, as an enthusiastic engineer, Kawasiro Nitori plans to construct more railway to ease the congestion.There are n stations numbered from 1 to n and m two-way railways in Gensokyo. Every two-way railway connects two different stations and has a positive integer length d. No two two-way railways connect the same two stations. Besides, it is possible to travel from any station to any other using those railways. Among these n stations, station 1 is the main station. You can get to any station from any other station using only two-way railways.Because of the technological limitation, Nitori can only construct one-way railways, whose length can be arbitrary positive integer. Constructing a one-way railway from station u will costs w_u units of resources, no matter where the railway ends. To ease the congestion, Nitori plans that after construction there are at least two shortest paths from station 1 to any other station, and these two shortest paths do not pass the same station except station 1 and the terminal. Besides, Nitori also does not want to change the distance of the shortest path from station 1 to any other station.Due to various reasons, sometimes the cost of building a new railway will increase uncontrollably. There will be a total of q occurrences of this kind of incident, and the i-th event will add additional amount of x_i to the cost of building a new railway from the station k_i.To save resources, before all incidents and after each incident, Nitori wants you to help her calculate the minimal cost of railway construction.
Input: ['5 5 1', '1 1 1 1 1', '1 2 1', '2 3 1', '2 4 1', '3 5 1', '4 5 1', '1 2', ''] Output:['3', '9', '']
[ 0 ]
Alice has an integer sequence a of length n and all elements are different. She will choose a subsequence of a of length m, and defines the value of a subsequence a_{b_1},a_{b_2},...,a_{b_m} as \sum_{i = 1}^m (m \cdot a_{b_i}) - \sum_{i = 1}^m \sum_{j = 1}^m f(\min(b_i, b_j), \max(b_i, b_j)), where f(i, j) denotes \min(a_i, a_{i + 1}, ..., a_j).Alice wants you to help her to maximize the value of the subsequence she choose.A sequence s is a subsequence of a sequence t if s can be obtained from t by deletion of several (possibly, zero or all) elements.
Input: ['6 4', '15 2 18 12 13 4', ''] Output:['100', '']
[ 0, 2 ]
Kawasiro Nitori is excellent in engineering. Thus she has been appointed to help maintain trains.There are n models of trains, and Nitori's department will only have at most one train of each model at any moment. In the beginning, there are no trains, at each of the following m days, one train will be added, or one train will be removed. When a train of model i is added at day t, it works for x_i days (day t inclusive), then it is in maintenance for y_i days, then in work for x_i days again, and so on until it is removed.In order to make management easier, Nitori wants you to help her calculate how many trains are in maintenance in each day.On a day a train is removed, it is not counted as in maintenance.
Input: ['3 4', '10 15', '12 10', '1 1', '1 3', '1 1', '2 1', '2 3', ''] Output:['0', '1', '0', '0', '']
[ 0 ]
Let c_1, c_2, ..., c_n be a permutation of integers 1, 2, ..., n. Consider all subsegments of this permutation containing an integer x. Given an integer m, we call the integer x good if there are exactly m different values of maximum on these subsegments.Cirno is studying mathematics, and the teacher asks her to count the number of permutations of length n with exactly k good numbers.Unfortunately, Cirno isn't good at mathematics, and she can't answer this question. Therefore, she asks you for help.Since the answer may be very big, you only need to tell her the number of permutations modulo p.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).A sequence a is a subsegment of a sequence b if a 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.
Input: ['4 3 2 10007', ''] Output:['4', '']
[ 0 ]
CQXYM found a rectangle A of size n * m. There are n rows and m columns of blocks. Each block of the rectangle is an obsidian block or empty. CQXYM can change an obsidian block to an empty block or an empty block to an obsidian block in one operation.A rectangle M size of a * b is called a portal if and only if it satisfies the following conditions: a >=q 5,b >=q 4. For all 1 < x < a, blocks M_{x,1} and M_{x,b} are obsidian blocks. For all 1 < x < b, blocks M_{1,x} and M_{a,x} are obsidian blocks. For all 1<x<a,1<y<b, block M_{x,y} is an empty block. M_{1, 1}, M_{1, b}, M_{a, 1}, M_{a, b} can be any type. Note that the there must be a rows and b columns, not b rows and a columns.Note that corners can be any typeCQXYM wants to know the minimum number of operations he needs to make at least one sub-rectangle a portal.
Input: ['1', '5 4', '1000', '0000', '0110', '0000', '0001', ''] Output:['12', '']
[ 0, 2 ]
You are given an array a[0 ... n - 1] = [a_0, a_1, ..., a_{n - 1}] of zeroes and ones only. Note that in this problem, unlike the others, the array indexes are numbered from zero, not from one.In one step, the array a is replaced by another array of length n according to the following rules: First, a new array a^{\rightarrow d} is defined as a cyclic shift of the array a to the right by d cells. The elements of this array can be defined as a^{\rightarrow d}_i = a_{(i + n - d) \bmod n}, where (i + n - d) \bmod n is the remainder of integer division of i + n - d by n. It means that the whole array a^{\rightarrow d} can be represented as a sequence a^{\rightarrow d} = [a_{n - d}, a_{n - d + 1}, ..., a_{n - 1}, a_0, a_1, ..., a_{n - d - 1}] Then each element of the array a_i is replaced by a_i \,\&\, a^{\rightarrow d}_i, where \& is a logical "AND" operator. For example, if a = [0, 0, 1, 1] and d = 1, then a^{\rightarrow d} = [1, 0, 0, 1] and the value of a after the first step will be [0 \,\&\, 1, 0 \,\&\, 0, 1 \,\&\, 0, 1 \,\&\, 1], that is [0, 0, 0, 1].The process ends when the array stops changing. For a given array a, determine whether it will consist of only zeros at the end of the process. If yes, also find the number of steps the process will take before it finishes.
Input: ['5', '2 1', '0 1', '3 2', '0 1 0', '5 2', '1 1 0 1 0', '4 2', '0 1 0 1', '1 1', '0', ''] Output:['1', '1', '3', '-1', '0', '']
[ 0, 3 ]
In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.You are given an integer array a[1 ... n] = [a_1, a_2, ..., a_n].Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements [3, 4, 4] currently in the deque, adding an element 1 to the beginning will produce the sequence [\color{red}{1}, 3, 4, 4], and adding the same element to the end will produce [3, 4, 4, \color{red}{1}].The elements of the array are sequentially added to the initially empty deque, starting with a_1 and finishing with a_n. Before adding each element to the deque, you may choose whether to add it to the beginning or to the end.For example, if we consider an array a = [3, 7, 5, 5], one of the possible sequences of actions looks like this: \quad 1.add 3 to the beginning of the deque:deque has a sequence [\color{red}{3}] in it;\quad 2.add 7 to the end of the deque:deque has a sequence [3, \color{red}{7}] in it;\quad 3.add 5 to the end of the deque:deque has a sequence [3, 7, \color{red}{5}] in it;\quad 4.add 5 to the beginning of the deque:deque has a sequence [\color{red}{5}, 3, 7, 5] in it;Find the minimal possible number of inversions in the deque after the whole array is processed. An inversion in sequence d is a pair of indices (i, j) such that i < j and d_i > d_j. For example, the array d = [5, 3, 7, 5] has exactly two inversions β€” (1, 2) and (3, 4), since d_1 = 5 > 3 = d_2 and d_3 = 7 > 5 = d_4.
Input: ['6', '4', '3 7 5 5', '3', '3 2 1', '3', '3 1 2', '4', '-1 2 2 -1', '4', '4 5 1 3', '5', '1 3 1 3 2', ''] Output:['2', '0', '1', '0', '1', '2', '']
[ 2 ]
In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.A permutation p of size n is given. A permutation of size n is an array of size n in which each integer from 1 to n occurs exactly once. For example, [1, 4, 3, 2] and [4, 2, 1, 3] are correct permutations while [1, 2, 4] and [1, 2, 2] are not.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements [1, 5, 2] currently in the deque, adding an element 4 to the beginning will produce the sequence [\color{red}{4}, 1, 5, 2], and adding same element to the end will produce [1, 5, 2, \color{red}{4}].The elements of the permutation are sequentially added to the initially empty deque, starting with p_1 and finishing with p_n. Before adding each element to the deque, you may choose whether to add it to the beginning or the end.For example, if we consider a permutation p = [3, 1, 2, 4], one of the possible sequences of actions looks like this: \quad 1.add 3 to the end of the deque:deque has a sequence [\color{red}{3}] in it;\quad 2.add 1 to the beginning of the deque:deque has a sequence [\color{red}{1}, 3] in it;\quad 3.add 2 to the end of the deque:deque has a sequence [1, 3, \color{red}{2}] in it;\quad 4.add 4 to the end of the deque:deque has a sequence [1, 3, 2, \color{red}{4}] in it;Find the lexicographically smallest possible sequence of elements in the deque after the entire permutation has been processed. A sequence [x_1, x_2, ..., x_n] is lexicographically smaller than the sequence [y_1, y_2, ..., y_n] if there exists such i <=q n that x_1 = y_1, x_2 = y_2, ..., x_{i - 1} = y_{i - 1} and x_i < y_i. In other words, if the sequences x and y have some (possibly empty) matching prefix, and the next element of the sequence x is strictly smaller than the corresponding element of the sequence y. For example, the sequence [1, 3, 2, 4] is smaller than the sequence [1, 3, 4, 2] because after the two matching elements [1, 3] in the start the first sequence has an element 2 which is smaller than the corresponding element 4 in the second sequence.
Input: ['5', '4', '3 1 2 4', '3', '3 2 1', '3', '3 1 2', '2', '1 2', '2', '2 1', ''] Output:['1 3 2 4 ', '1 2 3 ', '1 3 2 ', '1 2 ', '1 2 ', '']
[ 2, 3 ]
An important meeting is to be held and there are exactly n people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting.Each person has limited sociability. The sociability of the i-th person is a non-negative integer a_i. This means that after exactly a_i talks this person leaves the meeting (and does not talk to anyone else anymore). If a_i = 0, the i-th person leaves the meeting immediately after it starts.A meeting is considered most productive if the maximum possible number of talks took place during it.You are given an array of sociability a, determine which people should talk to each other so that the total number of talks is as large as possible.
Input: ['8', '2', '2 3', '3', '1 2 3', '4', '1 2 3 4', '3', '0 0 2', '2', '6 2', '3', '0 0 2', '5', '8 2 0 1 1', '5', '0 1 0 0 6', ''] Output:['2', '1 2', '1 2', '3', '1 3', '2 3', '2 3', '5', '1 3', '2 4', '2 4', '3 4', '3 4', '0', '2', '1 2', '1 2', '0', '4', '1 2', '1 5', '1 4', '1 2', '1', '5 2', '']
[ 2 ]
Casimir has a rectangular piece of paper with a checkered field of size n * m. Initially, all cells of the field are white.Let us denote the cell with coordinates i vertically and j horizontally by (i, j). The upper left cell will be referred to as (1, 1) and the lower right cell as (n, m).Casimir draws ticks of different sizes on the field. A tick of size d (d > 0) with its center in cell (i, j) is drawn as follows: First, the center cell (i, j) is painted black. Then exactly d cells on the top-left diagonally to the center and exactly d cells on the top-right diagonally to the center are also painted black. That is all the cells with coordinates (i - h, j \pm h) for all h between 0 and d are painted. In particular, a tick consists of 2d + 1 black cells. An already painted cell will remain black if painted again. Below you can find an example of the 4 * 9 box, with two ticks of sizes 2 and 3. You are given a description of a checkered field of size n * m. Casimir claims that this field came about after he drew some (possibly 0) ticks on it. The ticks could be of different sizes, but the size of each tick is at least k (that is, d >= k for all the ticks).Determine whether this field can indeed be obtained by drawing some (possibly none) ticks of sizes d >= k or not.
Input: ['8', '2 3 1', '*.*', '...', '4 9 2', '*.*.*...*', '.*.*...*.', '..*.*.*..', '.....*...', '4 4 1', '*.*.', '****', '.**.', '....', '5 5 1', '.....', '*...*', '.*.*.', '..*.*', '...*.', '5 5 2', '.....', '*...*', '.*.*.', '..*.*', '...*.', '4 7 1', '*.....*', '.....*.', '..*.*..', '...*...', '3 3 1', '***', '***', '***', '3 5 1', '*...*', '.***.', '.**..', ''] Output:['NO', 'YES', 'YES', 'YES', 'NO', 'NO', 'NO', 'NO', '']
[ 2 ]
Casimir has a string s which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions: he can either erase exactly one letter 'A' and exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent); or he can erase exactly one letter 'B' and exactly one letter 'C' from arbitrary places in the string (these letters don't have to be adjacent). Therefore, each turn the length of the string is decreased exactly by 2. All turns are independent so for each turn, Casimir can choose any of two possible actions.For example, with s = "ABCABC" he can obtain a string s = "ACBC" in one turn (by erasing the first occurrence of 'B' and the second occurrence of 'A'). There are also many other options for a turn aside from this particular example.For a given string s determine whether there is a sequence of actions leading to an empty string. In other words, Casimir's goal is to erase all letters from the string. Is there a way to do this?
Input: ['6', 'ABACAB', 'ABBA', 'AC', 'ABC', 'CABCBB', 'BCBCBCBCBCBCBCBC', ''] Output:['NO', 'YES', 'NO', 'NO', 'YES', 'YES', '']
[ 3 ]
In a dream, Lucy found herself in a labyrinth. This labyrinth consists of n rooms, connected by m passages (i-th passage is w_i cm wide). Each passage can be traversed in both directions. It is guaranteed that it is possible to get from any room to any other room. But this is not an ordinary labyrinth β€” each room in this labyrinth contains a magic candy. When Lucy eats this magic candy, she is getting wider. Specifically, if she eats candy from room i she becomes wider by c_i cm. Note that she is not obliged to eat candy the first time she visits a particular room, but she can eat each candy only once. Unfortunately, passages in this labyrinth are pretty narrow, so after eating some candy, Lucy can get too wide and will not be able to traverse them β€” her width should not be greater than the width of the corresponding passage.Lucy starts her journey in a room number 1. She wants to eat all the candies. After that, she will just wake up, so she does not have to be able to return to the room 1. She realizes that with her current width, she may not be able to do so, so she plans a workout before embarking on her journey. Lucy wants to know if it is possible to start with some positive width and still eat all the candies. If yes, then what is the maximal starting width with which it is possible.
Input: ['3 3', '1 2 3', '1 2 4', '1 3 4', '2 3 6', ''] Output:['3', '']
[ 2, 4 ]
The Kingdom of Islands consists of p islands. As the king, you rule over the whole kingdom, while each island is ruled over by one or several jarls under your rule. In total, there are n jarls under your jurisdiction.Each island of the kingdom has its own strong traditions, so jarls that rule over the same island support each other and never have conflicts. The downsides of such strength are cultural conflicts between people inhabiting different islands. Thus, two jarls that rule over different islands are in conflict.However, recent years brought a few changes to traditional relations between the jarls. To your knowledge, there are exactly k pairs of jarls such that relationships between two jarls in the pair are different from the traditional. That is, if two jarls of the pair you know rule over the same island, these jarls are in conflict. If they rule over different islands, then they overcome cultural disagreement and there is no conflict between them anymore.As a true responsible king, you are worried about whether the kingdom is close to a major conflict. In order to estimate the current situation, you would like to find the largest possible group of jarls such that every two jarls in the group are in conflict.
Input: ['4 4', '1 2 3 4', '1', '2 3', ''] Output:['3', '1 4 2 ']
[ 0 ]
The Just Kingdom is ruled by a king and his n lords, numbered 1 to n. Each of the lords is a vassal of some overlord, who might be the king himself, or a different lord closer to the king. The king, and all his lords, are just and kind.Each lord has certain needs, which can be expressed as a certain amount of money they need. However, if a lord, or the king, receives any money, they will first split it equally between all their vassals who still have unmet needs. Only if all the needs of all their vassals are met, they will take the money to fulfill their own needs. If there is any money left over, they will return the excess to their overlord (who follows the standard procedure for distributing money).At the beginning of the year, the king receives a certain sum of tax money and proceeds to split it according to the rules above. If the amount of tax money is greater than the total needs of all the lords, the procedure guarantees everybody's needs will be fulfilled, and the excess money will be left with the king. However, if there is not enough money, some lords will not have their needs met.For each lord, determine the minimum amount of tax money the king has to receive so that this lord's needs are met.
Input: ['5', '0 2', '1 2', '0 1', '1 1', '0 5', ''] Output:['11', '7', '3', '5', '11', '']
[ 0 ]
The King wants to marry off his daughter, and he wants her husband to have the greatest innate luckiness possible. To find such a person he decided to hold a heads-or-tails tournament. If person A with luckiness x and person B with luckiness y play heads-or-tails against each other, person A wins with probability x/(x+y). The tournament has several rounds. Each round some participants are split into pairs. Each pair plays against each other, and the loser leaves the tournament. The participants are numbered from 1 to n. During the first round, a number k (1 <= k <= n) is selected such that n-k/2 is a power of 2 (such k always exists and is unique). Only participants numbered from 1 to k take part in the first round. It ensures that in all other rounds the number of participants is the power of 2. During other rounds, all the participants who still have not left the tournament take part. If during some round, participants numbered p_1 < ... < p_{2m} take part, then they are split into pairs in the following manner: participant p_{2i-1} plays against participant p_{2i} for each i from 1 to m. The rounds are held until only one participant is left. He is declared the winner of the tournament and he will marry the King's daughter. The princess can't wait to find out who is her future husband. She asked every participant to tell her his luckiness. Assuming they did not lie, she wants to know the probability of each participant winning the tournament. As you are the best friend of the princess, she asks you to help her.
Input: ['5', '1 4 1 1 4', ''] Output:['0.026 0.3584 0.0676 0.0616 0.4864', '']
[ 3 ]
Eonathan Eostar decided to learn the magic of multiprocessor systems. He has a full binary tree of tasks with height h. In the beginning, there is only one ready task in the tree β€” the task in the root. At each moment of time, p processes choose at most p ready tasks and perform them. After that, tasks whose parents were performed become ready for the next moment of time. Once the task becomes ready, it stays ready until it is performed. You shall calculate the smallest number of time moments the system needs to perform all the tasks.
Input: ['3', '3 1', '3 2', '10 6', ''] Output:['7', '4', '173', '']
[ 3 ]
Mr. Chanek wants to knit a batik, a traditional cloth from Indonesia. The cloth forms a grid a with size n * m. There are k colors, and each cell in the grid can be one of the k colors.Define a sub-rectangle as an ordered pair of two cells ((x_1, y_1), (x_2, y_2)), denoting the top-left cell and bottom-right cell (inclusively) of a sub-rectangle in a. Two sub-rectangles ((x_1, y_1), (x_2, y_2)) and ((x_3, y_3), (x_4, y_4)) have the same pattern if and only if the following holds: they have the same width (x_2 - x_1 = x_4 - x_3); they have the same height (y_2 - y_1 = y_4 - y_3); for every pair (i, j) where 0 <=q i <=q x_2 - x_1 and 0 <=q j <=q y_2 - y_1, the color of cells (x_1 + i, y_1 + j) and (x_3 + i, y_3 + j) are equal. Count the number of possible batik color combinations, such that the subrectangles ((a_x, a_y),(a_x + r - 1, a_y + c - 1)) and ((b_x, b_y),(b_x + r - 1, b_y + c - 1)) have the same pattern.Output the answer modulo 10^9 + 7.
Input: ['3 3 2 2 2', '1 1 2 2', ''] Output:['32', '']
[ 3 ]
Mr. Chanek has a new game called Dropping Balls. Initially, Mr. Chanek has a grid a of size n * mEach cell (x,y) contains an integer a_{x,y} denoting the direction of how the ball will move. a_{x,y}=1 β€” the ball will move to the right (the next cell is (x, y + 1)); a_{x,y}=2 β€” the ball will move to the bottom (the next cell is (x + 1, y)); a_{x,y}=3 β€” the ball will move to the left (the next cell is (x, y - 1)). Every time a ball leaves a cell (x,y), the integer a_{x,y} will change to 2. Mr. Chanek will drop k balls sequentially, each starting from the first row, and on the c_1, c_2, ..., c_k-th (1 <=q c_i <=q m) columns.Determine in which column each ball will end up in (position of the ball after leaving the grid).
Input: ['5 5 3', '1 2 3 3 3', '2 2 2 2 2', '2 2 2 2 2', '2 2 2 2 2', '2 2 2 2 2', '1 2 1', ''] Output:['2 2 1 ', '']
[ 0, 4 ]
Mr. Chanek has an array a of n integers. The prettiness value of a is denoted as:\sum_{i=1}^{n} {\sum_{j=1}^{n} {\gcd(a_i, a_j) \cdot \gcd(i, j)}}where \gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.In other words, the prettiness value of an array a is the total sum of \gcd(a_i, a_j) \cdot \gcd(i, j) for all pairs (i, j).Help Mr. Chanek find the prettiness value of a, and output the result modulo 10^9 + 7!
Input: ['5', '3 6 2 1 4', ''] Output:['77', '']
[ 3 ]
Mr. Chanek opened a letter from his fellow, who is currently studying at Singanesia. Here is what it says.Define an array b (0 <=q b_i < k) with n integers. While there exists a pair (i, j) such that b_i!=b_j, do the following operation: Randomly pick a number i satisfying 0 <=q i < n. Note that each number i has a probability of \frac{1}{n} to be picked. Randomly Pick a number j satisfying 0 <=q j < k. Change the value of b_i to j. It is possible for b_i to be changed to the same value. Denote f(b) as the expected number of operations done to b until all elements of b are equal. You are given two integers n and k, and an array a (-1 <=q a_i < k) of n integers. For every index i with a_i = -1, replace a_i with a random number j satisfying 0 <=q j < k. Let c be the number of occurrences of -1 in a. There are k^c possibilites of a after the replacement, each with equal probability of being the final array.Find the expected value of f(a) modulo 10^9 + 7. Formally, let M = 10^9 + 7. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 <= x < M and x \cdot q \equiv p \pmod{M}.After reading the letter, Mr. Chanek gave the task to you. Solve it for the sake of their friendship!
Input: ['2 2', '0 1', ''] Output:['2', '']
[ 3 ]
Mr. Chanek has an integer represented by a string s. Zero or more digits have been erased and are denoted by the character _. There are also zero or more digits marked by the character X, meaning they're the same digit.Mr. Chanek wants to count the number of possible integer s, where s is divisible by 25. Of course, s must not contain any leading zero. He can replace the character _ with any digit. He can also replace the character X with any digit, but it must be the same for every character X.As a note, a leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, 0025 has two leading zeroes. An exception is the integer zero, (0 has no leading zero, but 0000 has three leading zeroes).
Input: ['25', ''] Output:['1', '']
[ 0 ]
Mr. Chanek lives in a city represented as a plane. He wants to build an amusement park in the shape of a circle of radius r. The circle must touch the origin (point (0, 0)).There are n bird habitats that can be a photo spot for the tourists in the park. The i-th bird habitat is at point p_i = (x_i, y_i). Find the minimum radius r of a park with at least k bird habitats inside. A point is considered to be inside the park if and only if the distance between p_i and the center of the park is less than or equal to the radius of the park. Note that the center and the radius of the park do not need to be integers.In this problem, it is guaranteed that the given input always has a solution with r <=q 2 \cdot 10^5.
Input: ['8 4', '-3 1', '-4 4', '1 5', '2 2', '2 -2', '-2 -4', '-1 -1', '-6 0', ''] Output:['3.1622776589', '']
[ 4 ]
A matrix of size n * m, such that each cell of it contains either 0 or 1, is considered beautiful if the sum in every contiguous submatrix of size 2 * 2 is exactly 2, i. e. every "square" of size 2 * 2 contains exactly two 1's and exactly two 0's.You are given a matrix of size n * m. Initially each cell of this matrix is empty. Let's denote the cell on the intersection of the x-th row and the y-th column as (x, y). You have to process the queries of three types: x y -1 β€” clear the cell (x, y), if there was a number in it; x y 0 β€” write the number 0 in the cell (x, y), overwriting the number that was there previously (if any); x y 1 β€” write the number 1 in the cell (x, y), overwriting the number that was there previously (if any). After each query, print the number of ways to fill the empty cells of the matrix so that the resulting matrix is beautiful. Since the answers can be large, print them modulo 998244353.
Input: ['2 2 7', '1 1 1', '1 2 1', '2 1 1', '1 1 0', '1 2 -1', '2 1 -1', '1 1 -1', ''] Output:['3', '1', '0', '1', '2', '3', '6', '']
[ 3 ]
Ivan is playing yet another roguelike computer game. He controls a single hero in the game. The hero has n equipment slots. There is a list of c_i items for the i-th slot, the j-th of them increases the hero strength by a_{i,j}. The items for each slot are pairwise distinct and are listed in the increasing order of their strength increase. So, a_{i,1} < a_{i,2} < ... < a_{i,c_i}.For each slot Ivan chooses exactly one item. Let the chosen item for the i-th slot be the b_i-th item in the corresponding list. The sequence of choices [b_1, b_2, ..., b_n] is called a build.The strength of a build is the sum of the strength increases of the items in it. Some builds are banned from the game. There is a list of m pairwise distinct banned builds. It's guaranteed that there's at least one build that's not banned.What is the build with the maximum strength that is not banned from the game? If there are multiple builds with maximum strength, print any of them.
Input: ['3', '3 1 2 3', '2 1 5', '3 2 4 6', '2', '3 2 3', '3 2 2', ''] Output:['2 2 3 ', '']
[ 0, 2, 4 ]
Recently, Petya learned about a new game "Slay the Dragon". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of n heroes, the strength of the i-th hero is equal to a_i.According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to x, then you have to send a hero with a strength of at least x to kill it. If the dragon's attack power is y, then the total strength of the heroes defending the castle should be at least y.The player can increase the strength of any hero by 1 for one gold coin. This operation can be done any number of times.There are m dragons in the game, the i-th of them has defense equal to x_i and attack power equal to y_i. Petya was wondering what is the minimum number of coins he needs to spend to defeat the i-th dragon.Note that the task is solved independently for each dragon (improvements are not saved).
Input: ['4', '3 6 2 3', '5', '3 12', '7 9', '4 14', '1 10', '8 7', ''] Output:['1', '2', '4', '0', '2', '']
[ 2, 4, 4 ]
You are given four integer values a, b, c and m.Check if there exists a string that contains: a letters 'A'; b letters 'B'; c letters 'C'; no other letters; exactly m pairs of adjacent equal letters (exactly m such positions i that the i-th letter is equal to the (i+1)-th one).
Input: ['3', '2 2 1 0', '1 1 1 1', '1 2 3 2', ''] Output:['YES', 'NO', 'YES', '']
[ 2, 3 ]
You are given two arrays a and b of length n. Array a contains each odd integer from 1 to 2n in an arbitrary order, and array b contains each even integer from 1 to 2n in an arbitrary order.You can perform the following operation on those arrays: choose one of the two arrays pick an index i from 1 to n-1 swap the i-th and the (i+1)-th elements of the chosen array Compute the minimum number of operations needed to make array a lexicographically smaller than array b.For two different arrays x and y of the same length n, we say that x is lexicographically smaller than y if in the first position where x and y differ, the array x has a smaller element than the corresponding element in y.
Input: ['3', '2', '3 1', '4 2', '3', '5 3 1', '2 4 6', '5', '7 5 9 1 3', '2 4 6 10 8', ''] Output:['0', '2', '3', '']
[ 2, 3 ]
You are given a digital clock with n digits. Each digit shows an integer from 0 to 9, so the whole clock shows an integer from 0 to 10^n-1. The clock will show leading zeroes if the number is smaller than 10^{n-1}.You want the clock to show 0 with as few operations as possible. In an operation, you can do one of the following: decrease the number on the clock by 1, or swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show 0.
Input: ['7', '3', '007', '4', '1000', '5', '00000', '3', '103', '4', '2020', '9', '123456789', '30', '001678294039710047203946100020', ''] Output:['7', '2', '0', '5', '6', '53', '115', '']
[ 2 ]
You are given a strictly convex polygon with n vertices.You will make k cuts that meet the following conditions: each cut is a segment that connects two different nonadjacent vertices; two cuts can intersect only at vertices of the polygon. Your task is to maximize the area of the smallest region that will be formed by the polygon and those k cuts.
Input: ['8 4', '-2 -4', '2 -2', '4 2', '1 5', '0 5', '-4 4', '-5 0', '-5 -1', ''] Output:['11', '']
[ 4 ]
There are currently n hot topics numbered from 0 to n-1 at your local bridge club and 2^n players numbered from 0 to 2^n-1. Each player holds a different set of views on those n topics, more specifically, the i-th player holds a positive view on the j-th topic if i\ \&\ 2^j > 0, and a negative view otherwise. Here \& denotes the bitwise AND operation.You are going to organize a bridge tournament capable of accommodating at most k pairs of players (bridge is played in teams of two people). You can select teams arbitrarily while each player is in at most one team, but there is one catch: two players cannot be in the same pair if they disagree on 2 or more of those n topics, as they would argue too much during the play.You know that the i-th player will pay you a_i dollars if they play in this tournament. Compute the maximum amount of money that you can earn if you pair the players in your club optimally.
Input: ['3 1', '8 3 5 7 1 10 3 2', ''] Output:['13', '']
[ 2 ]
You are given a 1 by n pixel image. The i-th pixel of the image has color a_i. For each color, the number of pixels of that color is at most 20.You can perform the following operation, which works like the bucket tool in paint programs, on this image: pick a color β€” an integer from 1 to n; choose a pixel in the image; for all pixels connected to the selected pixel, change their colors to the selected color (two pixels of the same color are considered connected if all the pixels between them have the same color as those two pixels). Compute the minimum number of operations needed to make all the pixels in the image have the same color.
Input: ['3', '5', '1 2 3 2 1', '4', '1 1 2 2', '5', '1 2 1 4 2', ''] Output:['2', '1', '3', '']
[ 2 ]
You are given a sequence a of length n consisting of 0s and 1s.You can perform the following operation on this sequence: Pick an index i from 1 to n-2 (inclusive). Change all of a_{i}, a_{i+1}, a_{i+2} to a_{i} \oplus a_{i+1} \oplus a_{i+2} simultaneously, where \oplus denotes the bitwise XOR operation Find a sequence of at most n operations that changes all elements of a to 0s or report that it's impossible.We can prove that if there exists a sequence of operations of any length that changes all elements of a to 0s, then there is also such a sequence of length not greater than n.
Input: ['3', '3', '0 0 0', '5', '1 1 1 1 0', '4', '1 0 0 1', ''] Output:['YES', '0', 'YES', '2', '3 1', 'NO', '']
[ 0, 2 ]
You are given a book with n chapters.Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list.Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter.Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.
Input: ['5', '4', '1 2', '0', '2 1 4', '1 2', '5', '1 5', '1 1', '1 2', '1 3', '1 4', '5', '0', '0', '2 1 2', '1 2', '2 2 1', '4', '2 2 3', '0', '0', '2 3 2', '5', '1 2', '1 3', '1 4', '1 5', '0', ''] Output:['2', '-1', '1', '2', '5', '']
[ 0, 4 ]
Polycarp plans to undergo a full physical examination at his local clinic. There are n doctors, numbered from 1 to n. The i-th doctor takes patients from minute L_i to minute R_i, so Polycarp can visit him at any minute in this range. It takes each doctor exactly one minute to examine Polycarp's health.Polycarp wants to arrive at the clinic at some minute x and visit all n doctors in some order without waiting or visiting any doctor several times.More formally, he chooses an integer x and a permutation p_1, p_2, ..., p_n (a sequence of n integers from 1 to n such that each integer appears exactly once), then proceeds to visit: doctor p_1 at minute x; doctor p_2 at minute x+1; ... doctor p_n at minute x+n-1. The p_i-th doctor should be able to take patients at minute x+i-1, so the following should hold: L[p_i] <= x + i - 1 <= R[p_i].Determine if it's possible for Polycarp to choose such a minute x and a permutation p that he'll be able to visit all n doctors in without waiting or visiting any doctor several times. If there are multiple answers, print any of them.
Input: ['5', '3', '2 3 1', '3 3 2', '8', '6 6 5 4 9 4 3 6', '7 6 10 6 9 6 6 8', '2', '4 2', '4 2', '3', '2 2 2', '3 3 3', '1', '5', '10', ''] Output:['1', '3 1 2 ', '3', '7 4 6 2 1 8 5 3 ', '-1', '-1', '7', '1 ', '']
[ 4 ]
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example: bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"); bracket sequences ")(", "(" and ")" are not. You are given two strings s and a, the string s has length n, the string a has length n - 3. The string s is a bracket sequence (i. e. each element of this string is either an opening bracket character or a closing bracket character). The string a is a binary string (i. e. each element of this string is either 1 or 0).The string a imposes some constraints on the string s: for every i such that a_i is 1, the string s_i s_{i+1} s_{i+2} s_{i+3} should be a regular bracket sequence. Characters of a equal to 0 don't impose any constraints.Initially, the string s may or may not meet these constraints. You can perform the following operation any number of times: replace some character of s with its inverse (i. e. you can replace an opening bracket with a closing bracket, or vice versa).Determine if it is possible to change some characters in s so that it meets all of the constraints, and if it is possible, calculate the minimum number of characters to be changed.
Input: ['6', '4', '))((', '1', '4', '))((', '0', '4', '()()', '0', '6', '))(()(', '101', '6', '))(()(', '001', '5', '(((((', '11', ''] Output:['2', '0', '0', '4', '1', '-1', '']
[ 2 ]
Kotlin Heroes competition is nearing completion. This time n programmers took part in the competition. Now organizers are thinking how to entertain spectators as well. One of the possibilities is holding sweepstakes. So for now they decided to conduct a survey among spectators.In total, organizers asked m viewers two questions: Who will take the first place? Who will take the last place? After receiving answers, organizers ranked all spectators based on the number of programmers they guessed right. Suppose, there are c_2 viewers who guessed right both first and last place, c_1 viewers who guessed either first or last place right and c_0 viewers who didn't guess at all. All c_2 viewers will get rank 1, all viewers with one right answer will get rank c_2 + 1 and all remaining viewers β€” rank c_2 + c_1 + 1.You were one of the interviewed spectators. Also, as one of the organizers, you have access to survey results, but not to competition results. Calculate, what is the worst rank you can possibly get according to organizers' ranking system?
Input: ['2 3', '1 2', '2 1', '2 1', ''] Output:['3', '']
[ 0, 3 ]
Alex has bought a new novel that was published in n volumes. He has read these volumes one by one, and each volume has taken him several (maybe one) full days to read. So, on the first day, he was reading the first volume, and on each of the following days, he was reading either the same volume he had been reading on the previous day, or the next volume.Let v_i be the number of the volume Alex was reading on the i-th day. Here are some examples: one of the possible situations is v_1 = 1, v_2 = 1, v_3 = 2, v_4 = 3, v_5 = 3 β€” this situation means that Alex has spent two days (1-st and 2-nd) on the first volume, one day (3-rd) on the second volume, and two days (4-th and 5-th) on the third volume; a situation v_1 = 2, v_2 = 2, v_3 = 3 is impossible, since Alex started with the first volume (so v_1 cannot be anything but 1); a situation v_1 = 1, v_2 = 2, v_3 = 3, v_4 = 1 is impossible, since Alex won't return to the first volume after reading the third one; a situation v_1 = 1, v_2 = 3 is impossible, since Alex doesn't skip volumes. You know that Alex was reading the volume v_a on the day a, and the volume v_c on the day c. Now you want to guess which volume was he reading on the day b, which is between the days a and c (so a < b < c). There may be some ambiguity, so you want to make any valid guess (i. e. choose some volume number v_b so it's possible that Alex was reading volume v_a on day a, volume v_b on day b, and volume v_c on day c).
Input: ['4', '1', '1 1', '100 1', '99', '4', '10 1', '20 4', '16', '100', '1 1', '100 100', '42', '100', '1 1', '100 2', '99', ''] Output:['1', '2', '42', '1']
[ 3 ]
You are given a simple undirected graph with n vertices, n is even. You are going to write a letter on each vertex. Each letter should be one of the first k letters of the Latin alphabet.A path in the graph is called Hamiltonian if it visits each vertex exactly once. A string is called palindromic if it reads the same from left to right and from right to left. A path in the graph is called palindromic if the letters on the vertices in it spell a palindromic string without changing the order.A string of length n is good if: each letter is one of the first k lowercase Latin letters; if you write the i-th letter of the string on the i-th vertex of the graph, there will exist a palindromic Hamiltonian path in the graph. Note that the path doesn't necesserily go through the vertices in order 1, 2, ..., n.Count the number of good strings.
Input: ['4 3 3', '1 2', '2 3', '3 4', ''] Output:['9', '']
[ 0 ]
2^k teams participate in a playoff tournament. The tournament consists of 2^k - 1 games. They are held as follows: first of all, the teams are split into pairs: team 1 plays against team 2, team 3 plays against team 4 (exactly in this order), and so on (so, 2^{k-1} games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only 2^{k-1} teams remain. If only one team remains, it is declared the champion; otherwise, 2^{k-2} games are played: in the first one of them, the winner of the game "1 vs 2" plays against the winner of the game "3 vs 4", then the winner of the game "5 vs 6" plays against the winner of the game "7 vs 8", and so on. This process repeats until only one team remains.After the tournament ends, the teams are assigned places according to the tournament phase when they were eliminated. In particular: the winner of the tournament gets place 1; the team eliminated in the finals gets place 2; both teams eliminated in the semifinals get place 3; all teams eliminated in the quarterfinals get place 5; all teams eliminated in the 1/8 finals get place 9, and so on. For example, this picture describes one of the possible ways the tournament can go with k = 3, and the resulting places of the teams: After a tournament which was conducted by the aforementioned rules ended, its results were encoded in the following way. Let p_i be the place of the i-th team in the tournament. The hash value of the tournament h is calculated as h = (\sum \limits_{i=1}^{2^k} i \cdot A^{p_i}) \bmod 998244353, where A is some given integer.Unfortunately, due to a system crash, almost all tournament-related data was lost. The only pieces of data that remain are the values of k, A and h. You are asked to restore the resulting placing of the teams in the tournament, if it is possible at all.
Input: ['3 1337 75275197', ''] Output:['5 3 5 2 1 5 5 3 ', '']
[ 0 ]
There is a city that can be represented as a square grid with corner points in (0, 0) and (10^6, 10^6).The city has n vertical and m horizontal streets that goes across the whole city, i. e. the i-th vertical streets goes from (x_i, 0) to (x_i, 10^6) and the j-th horizontal street goes from (0, y_j) to (10^6, y_j). All streets are bidirectional. Borders of the city are streets as well.There are k persons staying on the streets: the p-th person at point (x_p, y_p) (so either x_p equal to some x_i or y_p equal to some y_j, or both).Let's say that a pair of persons form an inconvenient pair if the shortest path from one person to another going only by streets is strictly greater than the Manhattan distance between them.Calculate the number of inconvenient pairs of persons (pairs (x, y) and (y, x) are the same pair).Let's recall that Manhattan distance between points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|.
Input: ['2', '2 2 4', '0 1000000', '0 1000000', '1 0', '1000000 1', '999999 1000000', '0 999999', '5 4 9', '0 1 2 6 1000000', '0 4 8 1000000', '4 4', '2 5', '2 2', '6 3', '1000000 1', '3 8', '5 8', '8 8', '6 8', ''] Output:['2', '5', '']
[ 4 ]
n people gathered to hold a jury meeting of the upcoming competition, the i-th member of the jury came up with a_i tasks, which they want to share with each other.First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation p of numbers from 1 to n (an array of size n where each integer from 1 to n occurs exactly once).Then the discussion goes as follows: If a jury member p_1 has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If a jury member p_2 has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. ... If a jury member p_n has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends. A permutation p is nice if none of the jury members tell two or more of their own tasks in a row. Count the number of nice permutations. The answer may be really large, so print it modulo 998\,244\,353.
Input: ['4', '2', '1 2', '3', '5 5 5', '4', '1 3 3 7', '6', '3 4 2 1 3 3', ''] Output:['1', '6', '0', '540', '']
[ 3 ]
Alice has recently received an array a_1, a_2, ..., a_n for her birthday! She is very proud of her array, and when she showed her friend Bob the array, he was very happy with her present too!However, soon Bob became curious, and as any sane friend would do, asked Alice to perform q operations of two types on her array: 1 x y: update the element a_x to y (set a_x = y). 2 l r: calculate how many non-decreasing subarrays exist within the subarray [a_l, a_{l+1}, ..., a_r]. More formally, count the number of pairs of integers (p,q) such that l <= p <= q <= r and a_p <= a_{p+1} <= ... <= a_{q-1} <= a_q. Help Alice answer Bob's queries!
Input: ['5 6', '3 1 4 1 5', '2 2 5', '2 1 3', '1 4 4', '2 2 5', '1 2 6', '2 2 5', ''] Output:['6', '4', '10', '7', '']
[ 3 ]
On the board, Bob wrote n positive integers in base 10 with sum s (i. e. in decimal numeral system). Alice sees the board, but accidentally interprets the numbers on the board as base-11 integers and adds them up (in base 11).What numbers should Bob write on the board, so Alice's sum is as large as possible?
Input: ['6', '97 2', '17 1', '111 4', '100 2', '10 9', '999999 3', ''] Output:['70 27 ', '17 ', '3 4 100 4', '10 90', '1 1 2 1 1 1 1 1 1 ', '999900 90 9', '']
[ 2, 3 ]
Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully β€” instead of carrying to the next column, she carries to the column two columns to the left.For example, the regular way to evaluate the sum 2039 + 2976 would be as shown: However, Alice evaluates it as shown: In particular, this is what she does: add 9 and 6 to make 15, and carry the 1 to the column two columns to the left, i. e. to the column "0 9"; add 3 and 7 to make 10 and carry the 1 to the column two columns to the left, i. e. to the column "2 2"; add 1, 0, and 9 to make 10 and carry the 1 to the column two columns to the left, i. e. to the column above the plus sign; add 1, 2 and 2 to make 5; add 1 to make 1. Thus, she ends up with the incorrect result of 15005.Alice comes up to Bob and says that she has added two numbers to get a result of n. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of n. Note that pairs (a, b) and (b, a) are considered different if a!=b.
Input: ['5', '100', '12', '8', '2021', '10000', ''] Output:['9', '4', '7', '44', '99', '']
[ 3 ]
Alice gave Bob two integers a and b (a > 0 and b >= 0). Being a curious boy, Bob wrote down an array of non-negative integers with \operatorname{MEX} value of all elements equal to a and \operatorname{XOR} value of all elements equal to b.What is the shortest possible length of the array Bob wrote?Recall that the \operatorname{MEX} (Minimum EXcluded) of an array is the minimum non-negative integer that does not belong to the array and the \operatorname{XOR} of an array is the bitwise XOR of all the elements of the array.
Input: ['5', '1 1', '2 1', '2 0', '1 10000', '2 10000', ''] Output:['3', '2', '3', '2', '3', '']
[ 2 ]
This is an interactive problem.You are given two integers c and n. The jury has a randomly generated set A of distinct positive integers not greater than c (it is generated from all such possible sets with equal probability). The size of A is equal to n.Your task is to guess the set A. In order to guess it, you can ask at most \lceil 0.65 \cdot c \rceil queries.In each query, you choose a single integer 1 <= x <= c. As the answer to this query you will be given the bitwise xor sum of all y, such that y \in A and gcd(x, y) = 1 (i.e. x and y are coprime). If there is no such y this xor sum is equal to 0.You can ask all queries at the beginning and you will receive the answers to all your queries. After that, you won't have the possibility to ask queries.You should find any set A', such that |A'| = n and A' and A have the same answers for all c possible queries.
Input: ['10 6', '', '1 4 2 11 4 4 4', '', ''] Output:['7 10 2 3 5 7 1 6', '', '1 4 5 6 8 10', '']
[ 3 ]
You are given an undirected weighted graph, consisting of n vertices and m edges.Some queries happen with this graph: Delete an existing edge from the graph. Add a non-existing edge to the graph. At the beginning and after each query, you should find four different vertices a, b, c, d such that there exists a path between a and b, there exists a path between c and d, and the sum of lengths of two shortest paths from a to b and from c to d is minimal. The answer to the query is the sum of the lengths of these two shortest paths. The length of the path is equal to the sum of weights of edges in this path.
Input: ['6 6', '1 3 6', '4 3 1', '1 4 1', '2 6 4', '2 4 2', '5 4 3', '4', '1 2 5 2', '0 1 4', '0 3 4', '1 6 1 3', ''] Output:['4', '3', '3', '7', '5', '']
[ 2 ]
There are n points and m segments on the coordinate line. The initial coordinate of the i-th point is a_i. The endpoints of the j-th segment are l_j and r_j β€” left and right endpoints, respectively.You can move the points. In one move you can move any point from its current coordinate x to the coordinate x - 1 or the coordinate x + 1. The cost of this move is 1.You should move the points in such a way that each segment is visited by at least one point. A point visits the segment [l, r] if there is a moment when its coordinate was on the segment [l, r] (including endpoints).You should find the minimal possible total cost of all moves such that all segments are visited.
Input: ['2', '4 11', '2 6 14 18', '0 3', '4 5', '11 15', '3 5', '10 13', '16 16', '1 4', '8 12', '17 19', '7 13', '14 19', '4 12', '-9 -16 12 3', '-20 -18', '-14 -13', '-10 -7', '-3 -1', '0 4', '6 11', '7 9', '8 10', '13 15', '14 18', '16 17', '18 19', ''] Output:['5', '22', '']
[ 2 ]
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex v (different from root) is the previous to v vertex on the shortest path from the root to the vertex v. Children of the vertex v are all vertices for which v is the parent.A vertex is a leaf if it has no children. We call a vertex a bud, if the following three conditions are satisfied: it is not a root, it has at least one child, and all its children are leaves. You are given a rooted tree with n vertices. The vertex 1 is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud.What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?
Input: ['5', '7', '1 2', '1 3', '1 4', '2 5', '2 6', '4 7', '6', '1 2', '1 3', '2 4', '2 5', '3 6', '2', '1 2', '7', '7 3', '1 5', '1 3', '4 6', '4 7', '2 1', '6', '2 1', '2 3', '4 5', '3 4', '3 6', ''] Output:['2', '2', '1', '2', '1', '']
[ 2 ]
It is the hard version of the problem. The only difference is that in this version 1 <= n <= 300.In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th row from m (k - 1) + 1 to m k for all rows 1 <= k <= n. 12\cdotsm - 1mm + 1m + 2\cdots2 m - 12 m2m + 12m + 2\cdots3 m - 13 m\vdots\vdots\ddots\vdots\vdotsm (n - 1) + 1m (n - 1) + 2\cdotsn m - 1n m The table with seats indices There are nm people who want to go to the cinema to watch a new film. They are numbered with integers from 1 to nm. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. i-th person has the level of sight a_i. Let's define s_i as the seat index, that will be given to i-th person. You want to give better places for people with lower sight levels, so for any two people i, j such that a_i < a_j it should be satisfied that s_i < s_j.After you will give seats to all people they will start coming to their seats. In the order from 1 to nm, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: m = 5, the person has the seat 4 in the first row, the seats 1, 3, 5 in the first row are already occupied, the seats 2 and 4 are free. The inconvenience of this person will be 2, because he will go through occupied seats 1 and 3.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).
Input: ['7', '1 2', '1 2', '3 2', '1 1 2 2 3 3', '3 3', '3 4 4 1 1 1 1 1 2', '2 2', '1 1 2 1', '4 2', '50 50 50 50 3 50 50 50', '4 2', '6 6 6 6 2 2 9 6', '2 9', '1 3 3 3 3 3 1 1 3 1 3 1 1 3 3 1 1 3', ''] Output:['1', '0', '4', '0', '0', '0', '1', '']
[ 2 ]
It is the easy version of the problem. The only difference is that in this version n = 1.In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th row from m (k - 1) + 1 to m k for all rows 1 <= k <= n. 12\cdotsm - 1mm + 1m + 2\cdots2 m - 12 m2m + 12m + 2\cdots3 m - 13 m\vdots\vdots\ddots\vdots\vdotsm (n - 1) + 1m (n - 1) + 2\cdotsn m - 1n m The table with seats indices There are nm people who want to go to the cinema to watch a new film. They are numbered with integers from 1 to nm. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. i-th person has the level of sight a_i. Let's define s_i as the seat index, that will be given to i-th person. You want to give better places for people with lower sight levels, so for any two people i, j such that a_i < a_j it should be satisfied that s_i < s_j.After you will give seats to all people they will start coming to their seats. In the order from 1 to nm, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: m = 5, the person has the seat 4 in the first row, the seats 1, 3, 5 in the first row are already occupied, the seats 2 and 4 are free. The inconvenience of this person will be 2, because he will go through occupied seats 1 and 3.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).
Input: ['4', '1 3', '1 2 3', '1 5', '2 1 5 3 3', '1 2', '2 1', '1 6', '2 3 2 1 1 1', ''] Output:['3', '6', '0', '1', '']
[ 2 ]