question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of n high school students numbered from 1 to n. Initially, each student i is on position i. Each student i is characterized by two numbers β€” a_i and b_i. Dissatisfaction of the person i equals the product of a_i by the number of people standing to the left of his position, add the product b_i by the number of people standing to the right of his position. Formally, the dissatisfaction of the student i, which is on the position j, equals a_i \cdot (j-1) + b_i \cdot (n-j).The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.Although Stas is able to solve such problems, this was not given to him. He turned for help to you.
Input: ['3', '4 2', '2 3', '6 1', ''] Output:['12']
[ 2, 3 ]
Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.Consider two infinite sets of numbers. The first set consists of odd positive numbers (1, 3, 5, 7, ...), and the second set consists of even positive numbers (2, 4, 6, 8, ...). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage β€” the first two numbers from the second set, on the third stage β€” the next four numbers from the first set, on the fourth β€” the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another. The ten first written numbers: 1, 2, 4, 3, 5, 7, 9, 6, 8, 10. Let's number the numbers written, starting with one.The task is to find the sum of numbers with numbers from l to r for given integers l and r. The answer may be big, so you need to find the remainder of the division by 1000000007 (10^9+7).Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.
Input: ['1 3', ''] Output:['7']
[ 3 ]
Student Dima from Kremland has a matrix a of size n * m filled with non-negative integers.He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him!Formally, he wants to choose an integers sequence c_1, c_2, ..., c_n (1 <=q c_j <=q m) so that the inequality a_{1, c_1} \oplus a_{2, c_2} \oplus ... \oplus a_{n, c_n} > 0 holds, where a_{i, j} is the matrix element from the i-th row and the j-th column.Here x \oplus y denotes the bitwise XOR operation of integers x and y.
Input: ['3 2', '0 0', '0 0', '0 0', ''] Output:['NIE', '']
[ 0 ]
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next β€” "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".Help Maxim solve the problem that the teacher gave him.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input: ['4', 'ZCTH', ''] Output:['2']
[ 0 ]
One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: By the pieces lay a large square wooden board. The board is divided into n^2 cells arranged into n rows and n columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free.Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board?
Input: ['3', '#.#', '...', '#.#', ''] Output:['YES', '']
[ 2 ]
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!In the morning, there are n opportunities to buy shares. The i-th of them allows to buy as many shares as you want, each at the price of s_i bourles.In the evening, there are m opportunities to sell shares. The i-th of them allows to sell as many shares as you want, each at the price of b_i bourles. You can't sell more shares than you have.It's morning now and you possess r bourles and no shares.What is the maximum number of bourles you can hold after the evening?
Input: ['3 4 11', '4 2 5', '4 4 5 4', ''] Output:['26', '']
[ 2 ]
Codefortia is a small island country located somewhere in the West Pacific. It consists of n settlements connected by m bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to a or b seconds. It's guaranteed that one can go between any pair of settlements by following a sequence of roads.Codefortia was recently struck by the financial crisis. Therefore, the king decided to abandon some of the roads so that: it will be possible to travel between each pair of cities using the remaining roads only, the sum of times required to pass each remaining road will be minimum possible (in other words, remaining roads must form minimum spanning tree, using the time to pass the road as its weight), among all the plans minimizing the sum of times above, the time required to travel between the king's residence (in settlement 1) and the parliament house (in settlement p) using the remaining roads only will be minimum possible. The king, however, forgot where the parliament house was. For each settlement p = 1, 2, ..., n, can you tell what is the minimum time required to travel between the king's residence and the parliament house (located in settlement p) after some roads are abandoned?
Input: ['5 5 20 25', '1 2 25', '2 3 25', '3 4 20', '4 5 20', '5 1 20', ''] Output:['0 25 60 40 20', '']
[ 0, 2 ]
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it β€” either 1 or 2.However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.Can you win the prize? Hurry up, the bags are waiting!
Input: ['5', '1 2 1 2 1', ''] Output:['1 1 1 2 2', '']
[ 2, 3 ]
Consider an undirected graph G with n vertices. There is a value a_i in each vertex.Two vertices i and j are connected with an edge if and only if gcd(a_i, a_j) > 1, where gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.Consider a set of vertices. Let's call a vertex in this set fair if it is connected with an edge with all other vertices in this set.You need to find a set of k vertices (where k is a given integer, 2 \cdot k <= n) where all vertices are fair or all vertices are not fair. One can show that such a set always exists.
Input: ['6 3', '6 15 10 8 14 12', ''] Output:['2 4 5']
[ 3 ]
There are n stones arranged on an axis. Initially the i-th stone is located at the coordinate s_i. There may be more than one stone in a single place.You can perform zero or more operations of the following type: take two stones with indices i and j so that s_i <=q s_j, choose an integer d (0 <=q 2 \cdot d <=q s_j - s_i), and replace the coordinate s_i with (s_i + d) and replace coordinate s_j with (s_j - d). In other words, draw stones closer to each other. You want to move the stones so that they are located at positions t_1, t_2, ..., t_n. The order of the stones is not important β€” you just want for the multiset of the stones resulting positions to be the same as the multiset of t_1, t_2, ..., t_n.Detect whether it is possible to move the stones this way, and if yes, construct a way to do so. You don't need to minimize the number of moves.
Input: ['5', '2 2 7 4 9', '5 4 5 5 5', ''] Output:['YES', '4', '4 3 1', '2 3 1', '2 5 2', '1 5 2']
[ 2, 3 ]
You are given n pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n). All of the integers in the pairs are distinct and are in the range from 1 to 2 \cdot n inclusive.Let's call a sequence of integers x_1, x_2, ..., x_{2k} good if either x_1 < x_2 > x_3 < ... < x_{2k-2} > x_{2k-1} < x_{2k}, or x_1 > x_2 < x_3 > ... > x_{2k-2} < x_{2k-1} > x_{2k}. You need to choose a subset of distinct indices i_1, i_2, ..., i_t and their order in a way that if you write down all numbers from the pairs in a single sequence (the sequence would be a_{i_1}, b_{i_1}, a_{i_2}, b_{i_2}, ..., a_{i_t}, b_{i_t}), this sequence is good.What is the largest subset of indices you can choose? You also need to construct the corresponding index sequence i_1, i_2, ..., i_t.
Input: ['5', '1 7', '6 4', '2 10', '9 8', '3 5', ''] Output:['3', '1 5 3', '']
[ 2 ]
Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.There are n flights from A to B, they depart at time moments a_1, a_2, a_3, ..., a_n and arrive at B t_a moments later.There are m flights from B to C, they depart at time moments b_1, b_2, b_3, ..., b_m and arrive at C t_b moments later.The connection time is negligible, so one can use the i-th flight from A to B and the j-th flight from B to C if and only if b_j >= a_i + t_a.You can cancel at most k flights. If you cancel a flight, Arkady can not use it.Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel k flights. If you can cancel k or less flights in such a way that it is not possible to reach C at all, print -1.
Input: ['4 5 1 1 2', '1 3 5 7', '1 2 3 9 10', ''] Output:['11', '']
[ 0, 4 ]
Let's call a string good if and only if it consists of only two types of letters β€” 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.What is the length of the longest good string you can obtain this way?
Input: ['1 1 1', ''] Output:['4', '']
[ 2 ]
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 <=q i < n) are adjacent, and so are points n and 1.There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 <=q k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input: ['12 6', '1 3', '3 7', '5 7', '7 11', '9 11', '11 3', ''] Output:['Yes', '']
[ 0 ]
A frog is initially at position 0 on the number line. The frog has two positive integers a and b. From a position k, it can either jump to position k+a or k-b.Let f(x) be the number of distinct integers the frog can reach if it never jumps on an integer outside the interval [0, x]. The frog doesn't need to visit all these integers in one trip, that is, an integer is counted if the frog can somehow reach it if it starts from 0.Given an integer m, find \sum_{i=0}^{m} f(i). That is, find the sum of all f(i) for i from 0 to m.
Input: ['7 5 3', ''] Output:['19', '']
[ 3 ]
Input: ['3', ''] Output:['13', '']
[ 0 ]
InputThe input contains a single integer a (1 <= a <= 99).OutputOutput "YES" or "NO".ExamplesInput5 OutputYES Input13 OutputNO Input24 OutputNO Input46 OutputYES
Input: ['5', ''] Output:['YES', '']
[ 0 ]
Two integer sequences existed initially, one of them was strictly increasing, and another one β€” strictly decreasing.Strictly increasing sequence is a sequence of integers [x_1 < x_2 < ... < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > ... > y_l]. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.Elements of increasing sequence were inserted between elements of the decreasing one (and, possibly, before its first element and after its last element) without changing the order. For example, sequences [1, 3, 4] and [10, 4, 2] can produce the following resulting sequences: [10, \textbf{1}, \textbf{3}, 4, 2, \textbf{4}], [\textbf{1}, \textbf{3}, \textbf{4}, 10, 4, 2]. The following sequence cannot be the result of these insertions: [\textbf{1}, 10, \textbf{4}, 4, \textbf{3}, 2] because the order of elements in the increasing sequence was changed.Let the obtained sequence be a. This sequence a is given in the input. Your task is to find any two suitable initial sequences. One of them should be strictly increasing, and another one β€” strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence a into one increasing sequence and one decreasing sequence, print "NO".
Input: ['9', '5 1 3 6 8 2 9 0 10', ''] Output:['YES', '1 0 0 0 0 1 0 1 0 ', '']
[ 2 ]
You are given two strings s and t, both consisting of exactly k lowercase Latin letters, s is lexicographically less than t.Let's consider list of all strings consisting of exactly k lowercase Latin letters, lexicographically not less than s and not greater than t (including s and t) in lexicographical order. For example, for k=2, s="az" and t="bf" the list will be ["az", "ba", "bb", "bc", "bd", "be", "bf"].Your task is to print the median (the middle element) of this list. For the example above this will be "bc".It is guaranteed that there is an odd number of strings lexicographically not less than s and not greater than t.
Input: ['2', 'az', 'bf', ''] Output:['bc', '']
[ 3 ]
You are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero): Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|; Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i - |a_i - a_j|. The value |x| means the absolute value of x. For example, |4| = 4, |-3| = 3.Your task is to find the minimum number of operations required to obtain the array of equal elements and print the order of operations to do it.It is guaranteed that you always can obtain the array of equal elements using such operations.Note that after each operation each element of the current array should not exceed 10^{18} by absolute value.
Input: ['5', '2 4 6 6 6', ''] Output:['2', '1 2 3 ', '1 1 2 ', '']
[ 2 ]
Polycarp has an array a consisting of n integers.He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.Formally: If it is the first move, he chooses any element and deletes it; If it is the second or any next move: if the last deleted element was odd, Polycarp chooses any even element and deletes it; if the last deleted element was even, Polycarp chooses any odd element and deletes it. If after some move Polycarp cannot make a move, the game ends. Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.Help Polycarp find this value.
Input: ['5', '1 5 7 8 2', ''] Output:['0', '']
[ 2 ]
Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper.Help Kurt find the maximum possible product of digits among all integers from 1 to n.
Input: ['390', ''] Output:['216', '']
[ 0, 3 ]
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n. Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.A cyclic shift of a permutation (p_1, p_2, ..., p_n) is a permutation (p_i, p_{i + 1}, ..., p_{n}, p_1, p_2, ..., p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, ..., a_{i_k} for some i_1, i_2, ..., i_k such that l <=q i_1 < i_2 < ... < i_k <=q r.
Input: ['3 6 32 1 31 2 3 1 2 31 52 63 5'] Output:['110']
[ 3 ]
Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through n \cdot k cities. The cities are numerated from 1 to n \cdot k, the distance between the neighboring cities is exactly 1 km.Sergey does not like beetles, he loves burgers. Fortunately for him, there are n fast food restaurants on the circle, they are located in the 1-st, the (k + 1)-st, the (2k + 1)-st, and so on, the ((n-1)k + 1)-st cities, i.e. the distance between the neighboring cities with fast food restaurants is k km.Sergey began his journey at some city s and traveled along the circle, making stops at cities each l km (l > 0), until he stopped in s once again. Sergey then forgot numbers s and l, but he remembers that the distance from the city s to the nearest fast food restaurant was a km, and the distance from the city he stopped at after traveling the first l km from s to the nearest fast food restaurant was b km. Sergey always traveled in the same direction along the circle, but when he calculated distances to the restaurants, he considered both directions.Now Sergey is interested in two integers. The first integer x is the minimum number of stops (excluding the first) Sergey could have done before returning to s. The second integer y is the maximum number of stops (excluding the first) Sergey could have done before returning to s.
Input: ['2 3', '1 1', ''] Output:['1 6', '']
[ 0, 3 ]
Treeland consists of n cities and n-1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed k and the number of companies taking part in the privatization is minimal.Choose the number of companies r such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most k. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal r that there is such assignment to companies from 1 to r that the number of cities which are not good doesn't exceed k. The picture illustrates the first example (n=6, k=2). The answer contains r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 3) is not good. The number of such vertices (just one) doesn't exceed k=2. It is impossible to have at most k=2 not good cities in case of one company.
Input: ['6 2', '1 4', '4 3', '3 5', '3 6', '5 2', ''] Output:['2', '1 2 1 1 2 ']
[ 2, 4 ]
This problem is given in two editions, which differ exclusively in the constraints on the number n.You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 <= l <= r <= n). Thus, a block is defined by a pair of indices (l, r).Find a set of blocks (l_1, r_1), (l_2, r_2), ..., (l_k, r_k) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i \neq j either r_i < l_j or r_j < l_i. For each block the sum of its elements is the same. Formally, a[l_1]+a[l_1+1]+...+a[r_1]=a[l_2]+a[l_2+1]+...+a[r_2]= ... = a[l_k]+a[l_k+1]+...+a[r_k]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), ..., (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.
Input: ['7', '4 1 2 2 1 5 3', ''] Output:['3', '7 7', '2 3', '4 5', '']
[ 2 ]
This problem is given in two editions, which differ exclusively in the constraints on the number n.You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 <= l <= r <= n). Thus, a block is defined by a pair of indices (l, r).Find a set of blocks (l_1, r_1), (l_2, r_2), ..., (l_k, r_k) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i \neq j either r_i < l_j or r_j < l_i. For each block the sum of its elements is the same. Formally, a[l_1]+a[l_1+1]+...+a[r_1]=a[l_2]+a[l_2+1]+...+a[r_2]= ... = a[l_k]+a[l_k+1]+...+a[r_k]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), ..., (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.
Input: ['7', '4 1 2 2 1 5 3', ''] Output:['3', '7 7', '2 3', '4 5', '']
[ 2 ]
A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly n minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of n numbers: d_1, d_2, ..., d_n (-10^6 <= d_i <= 10^6). The i-th element means that monster's hp (hit points) changes by the value d_i during the i-th minute of each round. Formally, if before the i-th minute of a round the monster's hp is h, then after the i-th minute it changes to h := h + d_i.The monster's initial hp is H. It means that before the battle the monster has H hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 0. Print -1 if the battle continues infinitely.
Input: ['1000 6', '-100 -200 -300 125 77 -4', ''] Output:['9', '']
[ 3 ]
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.
Input: ['10', 'codeforces', 'dodivthree', ''] Output:['5', '7 8', '4 9', '2 2', '9 10', '3 1', '']
[ 2 ]
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].Polycarp invented a really cool permutation p_1, p_2, ..., p_n of length n. It is very disappointing, but he forgot this permutation. He only remembers the array q_1, q_2, ..., q_{n-1} of length n-1, where q_i=p_{i+1}-p_i.Given n and q=q_1, q_2, ..., q_{n-1}, help Polycarp restore the invented permutation.
Input: ['3', '-2 1', ''] Output:['3 1 2 ']
[ 3 ]
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input: ['120 51840', ''] Output:['7', '']
[ 3 ]
You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the total area of all triangles is equal to the area of the given polygon. The weight of a triangulation is the sum of weigths of triangles it consists of, where the weight of a triagle is denoted as the product of labels of its vertices.Calculate the minimum weight among all triangulations of the polygon.
Input: ['3', ''] Output:['6', '']
[ 2, 3 ]
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i β€” its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) \cdot 6 = 96.You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input: ['4 3', '4 7', '15 1', '3 6', '6 8', ''] Output:['78', '']
[ 0 ]
Vivek initially has an empty array a and some integer constant m.He performs the following algorithm: Select a random integer x uniformly in range from 1 to m and append it to the end of a. Compute the greatest common divisor of integers in a. In case it equals to 1, break Otherwise, return to step 1. Find the expected length of a. It can be shown that it can be represented as \frac{P}{Q} where P and Q are coprime integers and Q\neq 0 \pmod{10^9+7}. Print the value of P \cdot Q^{-1} \pmod{10^9+7}.
Input: ['1', ''] Output:['1', '']
[ 3 ]
You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red.You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, ..., a_k] good if it satisfies the following criterion: We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. If you walked over at least one black edge during this process, then the sequence is good. Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3].There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7.
Input: ['4 4', '1 2 1', '2 3 1', '3 4 1', ''] Output:['252']
[ 3 ]
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock.You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 <= x_i <= a_i), then for all 1 <= j < i at least one of the following must hold: x_j = 0 (you bought zero chocolates of type j) x_j < x_i (you bought less chocolates of type j than of type i) For example, the array x = [0, 0, 1, 2, 10] satisfies the requirement above (assuming that all a_i >= x_i), while arrays x = [0, 1, 0], x = [5, 5] and x = [3, 2] don't.Calculate the maximum number of chocolates you can buy.
Input: ['5', '1 2 1 3 6', ''] Output:['10']
[ 2 ]
Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0).Split the artists into two performances in such a way that: each artist plays in exactly one performance, the number of artists in the two performances is equal (i.e. equal to \frac{n}{2}), the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance.
Input: ['4', '0011', '0101', ''] Output:['1 4', '']
[ 0, 2, 3 ]
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from the left sushi as t_i, where t_i = 1 means it is with tuna, and t_i = 2 means it is with eel.Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment [2, 2, 2, 1, 1, 1] is valid, but subsegment [1, 2, 1, 2, 1, 2] is not, because both halves contain both types of sushi.Find the length of the longest continuous subsegment of sushi Arkady can buy.
Input: ['7', '2 2 2 1 1 2 2', ''] Output:['4', '']
[ 2, 4 ]
Vasya likes to travel by train, but doesn't like when the car he travels in is located in the tail of the train.Vasya gets on the train at the station. The train consists of n cars indexed from 1 to n counting from the locomotive (head of the train). Three types of events occur while the train is moving: Some number of cars are added to the head of the train; Some number of cars are added to the tail of the train; Vasya recalculates the values of the convenience of the cars (read more about it below). At each moment of time we will index the cars from the head of the train, starting from 1. Note that when adding new cars to the head of the train, the indexing of the old ones may shift.To choose which car to go in, Vasya will use the value A_i for each car (where i is a car index), which is calculated as follows: At the beginning of the trip A_i=0, as well as for the new cars at the time of their addition. During the next recalculation Vasya chooses some positive integers b and s and adds to all A_i value b + (i - 1) \cdot s. Vasya hasn't decided yet where he will get on the train and where will get off the train, so after each event of one of the three types he wants to know the least index of the car, such that its value A_i is minimal. Since there is a lot of cars, Vasya asked you to write a program that answers his question.
Input: ['1 8', '1 1', '3 1 1', '3 1 1', '2 1', '2 1', '3 1 1', '2 1', '3 1 5', ''] Output:['1 0', '1 1', '1 2', '3 0', '3 0', '1 3', '5 0', '1 4', '']
[ 2 ]
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule s, which can be represented as a binary string, in which the i-th symbol is '1' if students will write the contest in the i-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule t (which can be described in the same format as schedule s). Since the number of days in the current may be different from number of days in schedule t, Gleb required that the camp's schedule must be altered so that the number of occurrences of t in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
Input: ['101101', '110', ''] Output:['110110']
[ 2 ]
In this task, Nastya asked us to write a formal statement.An array a of length n and an array k of length n-1 are given. Two types of queries should be processed: increase a_i by x. Then if a_{i+1} < a_i + k_i, a_{i+1} becomes exactly a_i + k_i; again, if a_{i+2} < a_{i+1} + k_{i+1}, a_{i+2} becomes exactly a_{i+1} + k_{i+1}, and so far for a_{i+3}, ..., a_n; print the sum of the contiguous subarray from the l-th element to the r-th element of the array a. It's guaranteed that initially a_i + k_i <=q a_{i+1} for all 1 <=q i <=q n-1.
Input: ['3', '1 2 3', '1 -1', '5', 's 2 3', '+ 1 2', 's 1 2', '+ 3 1', 's 2 3', ''] Output:['5', '7', '8', '']
[ 4 ]
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
Input: ['2 11 21 2'] Output:['1']
[ 2 ]
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible.There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are closed, and there is one stone on every manhole. There is exactly one coin under every manhole, and to win the game Nastya should pick all the coins. Initially Nastya stands near the k-th manhole from the left. She is thinking what to do.In one turn, Nastya can do one of the following: if there is at least one stone on the manhole Nastya stands near, throw exactly one stone from it onto any other manhole (yes, Nastya is strong). go to a neighboring manhole; if there are no stones on the manhole Nastya stays near, she can open it and pick the coin from it. After it she must close the manhole immediately (it doesn't require additional moves). The figure shows the intermediate state of the game. At the current position Nastya can throw the stone to any other manhole or move left or right to the neighboring manholes. If she were near the leftmost manhole, she could open it (since there are no stones on it). Nastya can leave the room when she picks all the coins. Monsters are everywhere, so you need to compute the minimum number of moves Nastya has to make to pick all the coins.Note one time more that Nastya can open a manhole only when there are no stones onto it.
Input: ['2 2', ''] Output:['6', '']
[ 3 ]
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to find any spanning tree of this graph such that the degree of the first vertex (vertex with label 1 on it) is equal to D (or say that there are no such spanning trees). Recall that the degree of a vertex is the number of edges incident to it.
Input: ['4 5 1', '1 2', '1 3', '1 4', '2 3', '3 4', ''] Output:['YES', '2 1', '2 3', '3 4', '']
[ 2 ]
You are given two arrays a and b, each contains n integers.You want to create a new array c as follows: choose some real (i.e. not necessarily integer) number d, and then for every i \in [1, n] let c_i := d \cdot a_i + b_i.Your goal is to maximize the number of zeroes in array c. What is the largest possible answer, if you choose d optimally?
Input: ['5', '1 2 3 4 5', '2 4 7 11 3', ''] Output:['2', '']
[ 3 ]
International Women's Day is coming soon! Polycarp is preparing for the holiday.There are n candy boxes in the shop for sale. The i-th box contains d_i candies.Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i!=j) can be combined as a gift if d_i + d_j is divisible by k.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.
Input: ['7 2', '1 2 2 3 2 4 10', ''] Output:['6', '']
[ 3 ]
You have a set of items, each having some integer weight not greater than 8. You denote that a subset of items is good if total weight of items in the subset does not exceed W.You want to calculate the maximum possible weight of a good subset of items. Note that you have to consider the empty set and the original set when calculating the answer.
Input: ['10', '1 2 3 4 5 6 7 8', ''] Output:['10', '']
[ 2 ]
Berland SU holds yet another training contest for its students today. n students came, each of them brought his laptop. However, it turned out that everyone has forgot their chargers!Let students be numbered from 1 to n. Laptop of the i-th student has charge a_i at the beginning of the contest and it uses b_i of charge per minute (i.e. if the laptop has c charge at the beginning of some minute, it becomes c - b_i charge at the beginning of the next minute). The whole contest lasts for k minutes.Polycarp (the coach of Berland SU) decided to buy a single charger so that all the students would be able to successfully finish the contest. He buys the charger at the same moment the contest starts.Polycarp can choose to buy the charger with any non-negative (zero or positive) integer power output. The power output is chosen before the purchase, it can't be changed afterwards. Let the chosen power output be x. At the beginning of each minute (from the minute contest starts to the last minute of the contest) he can plug the charger into any of the student's laptops and use it for some integer number of minutes. If the laptop is using b_i charge per minute then it will become b_i - x per minute while the charger is plugged in. Negative power usage rate means that the laptop's charge is increasing. The charge of any laptop isn't limited, it can become infinitely large. The charger can be plugged in no more than one laptop at the same time.The student successfully finishes the contest if the charge of his laptop never is below zero at the beginning of some minute (from the minute contest starts to the last minute of the contest, zero charge is allowed). The charge of the laptop of the minute the contest ends doesn't matter.Help Polycarp to determine the minimal possible power output the charger should have so that all the students are able to successfully finish the contest. Also report if no such charger exists.
Input: ['2 4', '3 2', '4 2', ''] Output:['5', '']
[ 2, 4 ]
You have a long fence which consists of n sections. Unfortunately, it is not painted, so you decided to hire q painters to paint it. i-th painter will paint all sections x such that l_i <= x <= r_i.Unfortunately, you are on a tight budget, so you may hire only q - 2 painters. Obviously, only painters you hire will do their work.You want to maximize the number of painted sections if you choose q - 2 painters optimally. A section is considered painted if at least one painter paints it.
Input: ['7 5', '1 4', '4 5', '5 6', '6 7', '3 5', ''] Output:['7', '']
[ 0 ]
You came to a local shop and want to buy some chocolate bars. There are n bars in the shop, i-th of them costs a_i coins (and you want to buy all of them).You have m different coupons that allow you to buy chocolate bars. i-th coupon allows you to buy q_i chocolate bars while you have to pay only for the q_i - 1 most expensive ones (so, the cheapest bar of those q_i bars is for free).You can use only one coupon; if you use coupon i, you have to choose q_i bars and buy them using the coupon, and buy all the remaining n - q_i bars without any discounts.To decide which coupon to choose, you want to know what will be the minimum total amount of money you have to pay if you use one of the coupons optimally.
Input: ['7', '7 1 3 1 4 10 8', '2', '3 4', ''] Output:['27', '30', '']
[ 2 ]
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; "))" and ")((" are bracket sequences (but not regular ones), and "(a)" and "(1)+(1)" are not bracket sequences at all.You have a number of strings; each string is a bracket sequence of length 2. So, overall you have cnt_1 strings "((", cnt_2 strings "()", cnt_3 strings ")(" and cnt_4 strings "))". You want to write all these strings in some order, one after another; after that, you will get a long bracket sequence of length 2(cnt_1 + cnt_2 + cnt_3 + cnt_4). You wonder: is it possible to choose some order of the strings you have such that you will get a regular bracket sequence? Note that you may not remove any characters or strings, and you may not add anything either.
Input: ['3', '1', '4', '3', ''] Output:['1', '']
[ 2 ]
Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings s of length m and t is a string t + s_1 + t + s_2 + ... + t + s_m + t, where s_i denotes the i-th symbol of the string s, and "+" denotes string concatenation. For example, the product of strings "abc" and "de" is a string "deadebdecde", while the product of the strings "ab" and "z" is a string "zazbz". Note, that unlike the numbers multiplication, the product of strings s and t is not necessarily equal to product of t and s.Roman was jealous of Denis, since he invented such a cool operation, and hence decided to invent something string-related too. Since Roman is beauty-lover, he decided to define the beauty of the string as the length of the longest substring, consisting of only one letter. For example, the beauty of the string "xayyaaabca" is equal to 3, since there is a substring "aaa", while the beauty of the string "qwerqwer" is equal to 1, since all neighboring symbols in it are different.In order to entertain Roman, Denis wrote down n strings p_1, p_2, p_3, ..., p_n on the paper and asked him to calculate the beauty of the string ( ... (((p_1 \cdot p_2) \cdot p_3) \cdot ... ) \cdot p_n, where s \cdot t denotes a multiplication of strings s and t. Roman hasn't fully realized how Denis's multiplication works, so he asked you for a help. Denis knows, that Roman is very impressionable, he guarantees, that the beauty of the resulting string is at most 10^9.
Input: ['3', 'a', 'b', 'a', ''] Output:['3', '']
[ 2 ]
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n * m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
Input: ['3 4', '>>>>', '>>>>', '>>>>', ''] Output:['Yes', '2 2 2 ', '1 1 1 1 ', '']
[ 2 ]
Cowboy Vlad has a birthday today! There are n children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.Formally, let's number children from 1 to n in a circle order, that is, for every i child with number i will stand next to the child with number i+1, also the child with number 1 stands next to the child with number n. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.
Input: ['5', '2 1 1 3 2', ''] Output:['1 2 3 2 1', '']
[ 2, 4 ]
You still have partial information about the score during the historic football match. You are given a set of pairs (a_i, b_i), indicating that at some point during the match the score was "a_i: b_i". It is known that if the current score is Β«x:yΒ», then after the goal it will change to "x+1:y" or "x:y+1". What is the largest number of times a draw could appear on the scoreboard?The pairs "a_i:b_i" are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.
Input: ['32 03 13 4'] Output:['2']
[ 2 ]
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 >= w_2. In this game, exactly one ship is used, made up of two rectangles. There are no other ships on the field.The rectangles are placed on field in the following way: the second rectangle is on top the first rectangle; they are aligned to the left, i.e. their left sides are on the same line; the rectangles are adjacent to each other without a gap. See the pictures in the notes: the first rectangle is colored red, the second rectangle is colored blue.Formally, let's introduce a coordinate system. Then, the leftmost bottom cell of the first rectangle has coordinates (1, 1), the rightmost top cell of the first rectangle has coordinates (w_1, h_1), the leftmost bottom cell of the second rectangle has coordinates (1, h_1 + 1) and the rightmost top cell of the second rectangle has coordinates (w_2, h_1 + h_2).After the ship is completely destroyed, all cells neighboring by side or a corner with the ship are marked. Of course, only cells, which don't belong to the ship are marked. On the pictures in the notes such cells are colored green.Find out how many cells should be marked after the ship is destroyed. The field of the game is infinite in any direction.
Input: ['2 1 2 1', ''] Output:['12', '']
[ 3 ]
Alice lives on a flat planet that can be modeled as a square grid of size n * n, with rows and columns enumerated from 1 to n. We represent the cell at the intersection of row r and column c with ordered pair (r, c). Each cell in the grid is either land or water. An example planet with n = 5. It also appears in the first sample test. Alice resides in land cell (r_1, c_1). She wishes to travel to land cell (r_2, c_2). At any moment, she may move to one of the cells adjacent to where she isβ€”in one of the four directions (i.e., up, down, left, or right).Unfortunately, Alice cannot swim, and there is no viable transportation means other than by foot (i.e., she can walk only on land). As a result, Alice's trip may be impossible.To help Alice, you plan to create at most one tunnel between some two land cells. The tunnel will allow Alice to freely travel between the two endpoints. Indeed, creating a tunnel is a lot of effort: the cost of creating a tunnel between cells (r_s, c_s) and (r_t, c_t) is (r_s-r_t)^2 + (c_s-c_t)^2.For now, your task is to find the minimum possible cost of creating at most one tunnel so that Alice could travel from (r_1, c_1) to (r_2, c_2). If no tunnel needs to be created, the cost is 0.
Input: ['5', '1 1', '5 5', '00001', '11111', '00111', '00110', '00110', ''] Output:['10', '']
[ 0 ]
Sasha and Dima want to buy two n-tier cakes. Each cake should consist of n different tiers: from the size of 1 to the size of n. Tiers should go in order from the smallest to the biggest (from top to bottom).They live on the same street, there are 2 \cdot n houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the i-th house you can buy a tier of the size a_i (1 <= a_i <= n).Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: 1, then 2, then 3 and so on up to n.Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly 1.
Input: ['3', '1 1 2 2 3 3', ''] Output:['9', '']
[ 2 ]
This is an interactive problem.A legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster.To help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains n vertices, enumerated from 1 through n. She also allows you to ask her some questions as follows. For each question, you should tell Mikaela some two disjoint non-empty sets of vertices S and T, along with any vertex v that you like. Then, Mikaela will count and give you the number of pairs of vertices (s, t) where s \in S and t \in T such that the simple path from s to t contains v.Mikaela the Goddess is busy and will be available to answer at most 11\,111 questions.This is your only chance. Your task is to determine the tree and report its edges.
Input: ['55'] Output:['31 2 324 52ANSWER1 22 33 42 5']
[ 4 ]
In Morse code, an letter of English alphabet is represented as a string of some length from 1 to 4. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1".Because there are 2^1+2^2+2^3+2^4 = 30 strings with length 1 to 4 containing only "0" and/or "1", not all of them correspond to one of the 26 English letters. In particular, each string of "0" and/or "1" of length at most 4 translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111".You will work with a string S, which is initially empty. For m times, either a dot or a dash will be appended to S, one at a time. Your task is to find and report, after each of these modifications to string S, the number of non-empty sequences of English letters that are represented with some substring of S in Morse code.Since the answers can be incredibly tremendous, print them modulo 10^9 + 7.
Input: ['3111'] Output:['137']
[ 4 ]
Alice received a set of Toy Trainβ„’ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 <=q i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 <=q i <=q m), now at station a_i, should be delivered to station b_i (a_i \neq b_i). The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input: ['5 7', '2 4', '5 1', '2 3', '3 4', '4 1', '5 3', '3 5', ''] Output:['10 9 10 10 9 ', '']
[ 0, 2 ]
This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.Alice received a set of Toy Trainβ„’ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 <=q i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 <=q i <=q m), now at station a_i, should be delivered to station b_i (a_i \neq b_i). The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input: ['5 7', '2 4', '5 1', '2 3', '3 4', '4 1', '5 3', '3 5', ''] Output:['10 9 10 10 9 ', '']
[ 0, 2 ]
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.Mike has n sweets with sizes a_1, a_2, ..., a_n. All his sweets have different sizes. That is, there is no such pair (i, j) (1 <=q i, j <=q n) such that i!=j and a_i = a_j.Since Mike has taught for many years, he knows that if he gives two sweets with sizes a_i and a_j to one child and a_k and a_p to another, where (a_i + a_j) \neq (a_k + a_p), then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset. Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can. Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.
Input: ['8', '1 8 3 11 4 9 2 7', ''] Output:['3', '']
[ 0 ]
Little W and Little P decided to send letters to each other regarding the most important events during a day. There are n events during a day: at time moment t_i something happens to the person p_i (p_i is either W or P, denoting Little W and Little P, respectively), so he needs to immediately send a letter to the other person. They can send a letter using one of the two ways: Ask Friendly O to deliver the letter directly. Friendly O takes d acorns for each letter. Leave the letter at Wise R's den. Wise R values free space, so he takes c \cdot T acorns for storing a letter for a time segment of length T. The recipient can take a letter from Wise R either when he leaves his own letter at Wise R's den, or at time moment t_{n + 1}, when everybody comes to Wise R for a tea. It is not possible to take a letter from Wise R's den at other time moments. The friends can store as many letters at Wise R's den as they want, paying for each one separately. Help the friends determine the minimum possible total cost of sending all letters.
Input: ['5 1 4', '0 P', '1 W', '3 P', '5 P', '8 P', '10', ''] Output:['16', '']
[ 2 ]
A positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x. Find out if what Baron told can be true.
Input: ['2', ''] Output:['6', '']
[ 0 ]
You are given a rooted tree with n vertices, the root of the tree is the vertex 1. Each vertex has some non-negative price. A leaf of the tree is a non-root vertex that has degree 1.Arkady and Vasily play a strange game on the tree. The game consists of three stages. On the first stage Arkady buys some non-empty set of vertices of the tree. On the second stage Vasily puts some integers into all leaves of the tree. On the third stage Arkady can perform several (possibly none) operations of the following kind: choose some vertex v he bought on the first stage and some integer x, and then add x to all integers in the leaves in the subtree of v. The integer x can be positive, negative of zero.A leaf a is in the subtree of a vertex b if and only if the simple path between a and the root goes through b.Arkady's task is to make all integers in the leaves equal to zero. What is the minimum total cost s he has to pay on the first stage to guarantee his own win independently of the integers Vasily puts on the second stage? Also, we ask you to find all such vertices that there is an optimal (i.e. with cost s) set of vertices containing this one such that Arkady can guarantee his own win buying this set on the first stage.
Input: ['5', '5 1 3 2 1', '1 2', '2 3', '2 4', '1 5', ''] Output:['4 3', '2 4 5 ', '']
[ 2 ]
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add 1 to 9, to subtract 1 from 0 and to subtract 1 from the leading 1. Once the number on the screen becomes equal to b, the player wins the jackpot. a and b have the same number of digits.Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.
Input: ['3', '223', '322', ''] Output:['2', '1 1', '2 -1', '']
[ 2, 3 ]
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m >= n \cdot k), and that means every citizen will get a wreath.Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana.Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces?
Input: ['7 3 2 2', '1 2 3 3 2 1 2', '2 2', ''] Output:['1', '4 ', '']
[ 2 ]
You have received your birthday gifts β€” n triples of integers! The i-th of them is \lbrace a_{i}, b_{i}, c_{i} \rbrace. All numbers are greater than or equal to 0, and strictly smaller than 2^{k}, where k is a fixed integer.One day, you felt tired playing with triples. So you came up with three new integers x, y, z, and then formed n arrays. The i-th array consists of a_i repeated x times, b_i repeated y times and c_i repeated z times. Thus, each array has length (x + y + z).You want to choose exactly one integer from each array such that the XOR (bitwise exclusive or) of them is equal to t. Output the number of ways to choose the numbers for each t between 0 and 2^{k} - 1, inclusive, modulo 998244353.
Input: ['1 1', '1 2 3', '1 0 1', ''] Output:['2 4 ', '']
[ 3 ]
Pavel has several sticks with lengths equal to powers of two.He has a_0 sticks of length 2^0 = 1, a_1 sticks of length 2^1 = 2, ..., a_{n-1} sticks of length 2^{n-1}. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.It is forbidden to break sticks, and each triangle should consist of exactly three sticks.Find the maximum possible number of triangles.
Input: ['5', '1 2 2 2 2', ''] Output:['3', '']
[ 0, 2, 4 ]
Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.In return, the fleas made a bigger ukulele for her: it has n strings, and each string has (10^{18} + 1) frets numerated from 0 to 10^{18}. The fleas use the array s_1, s_2, ..., s_n to describe the ukulele's tuning, that is, the pitch of the j-th fret on the i-th string is the integer s_i + j.Miyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them.Each question is in the form of: "How many different pitches are there, if we consider frets between l and r (inclusive) on all strings?"Miyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task!Formally, you are given a matrix with n rows and (10^{18}+1) columns, where the cell in the i-th row and j-th column (0 <= j <= 10^{18}) contains the integer s_i + j. You are to answer q queries, in the k-th query you have to answer the number of distinct integers in the matrix from the l_k-th to the r_k-th columns, inclusive.
Input: ['63 1 4 1 5 937 70 28 17'] Output:['5 10 18']
[ 4 ]
Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.You are given two matrices A and B of size n * m, each of which consists of 0 and 1 only. You can apply the following operation to the matrix A arbitrary number of times: take any submatrix of the matrix A that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain 0, will be replaced by 1, and all corners of the submatrix that contain 1, will be replaced by 0). You have to answer whether you can obtain the matrix B from the matrix A. An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow. Ramesses don't want to perform these operations by himself, so he asks you to answer this question.A submatrix of matrix M is a matrix which consist of all elements which come from one of the rows with indices x_1, x_1+1, ..., x_2 of matrix M and one of the columns with indices y_1, y_1+1, ..., y_2 of matrix M, where x_1, x_2, y_1, y_2 are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells (x_1, y_1), (x_1, y_2), (x_2, y_1), (x_2, y_2), where the cell (i,j) denotes the cell on the intersection of the i-th row and the j-th column.
Input: ['3 3', '0 1 0', '0 1 0', '1 0 0', '1 0 0', '1 0 0', '1 0 0', ''] Output:['Yes', '']
[ 2, 3 ]
Alyona has recently bought a miniature fridge that can be represented as a matrix with h rows and 2 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part. An example of a fridge with h = 7 and two shelves. The shelves are shown in black. The picture corresponds to the first example. Alyona has n bottles of milk that she wants to put in the fridge. The i-th bottle is a_i cells tall and 1 cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.Alyona is interested in the largest integer k such that she can put bottles 1, 2, ..., k in the fridge at the same time. Find this largest k.
Input: ['5 7', '2 3 5 4 1', ''] Output:['3', '']
[ 2, 4 ]
Ilya lives in a beautiful city of Chordalsk.There are n houses on the street Ilya lives, they are numerated from 1 to n from left to right; the distance between every two neighboring houses is equal to 1 unit. The neighboring houses are 1 and 2, 2 and 3, ..., n-1 and n. The houses n and 1 are not neighboring.The houses are colored in colors c_1, c_2, ..., c_n so that the i-th house is colored in the color c_i. Everyone knows that Chordalsk is not boring, so there are at least two houses colored in different colors.Ilya wants to select two houses i and j so that 1 <=q i < j <=q n, and they have different colors: c_i \neq c_j. He will then walk from the house i to the house j the distance of (j-i) units.Ilya loves long walks, so he wants to choose the houses so that the distance between them is the maximum possible.Help Ilya, find this maximum possible distance.
Input: ['5', '1 2 3 2 3', ''] Output:['4', '']
[ 2 ]
The only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of m pages.Polycarp also has n cups of coffee. The coffee in the i-th cup Polycarp has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least).Let's consider some day of Polycarp's work. Consider Polycarp drinks k cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are a_{i_1}, a_{i_2}, ..., a_{i_k}. Then the first cup he drinks gives him energy to write a_{i_1} pages of coursework, the second cup gives him energy to write max(0, a_{i_2} - 1) pages, the third cup gives him energy to write max(0, a_{i_3} - 2) pages, ..., the k-th cup gives him energy to write max(0, a_{i_k} - k + 1) pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.
Input: ['5 8', '2 3 1 1 2', ''] Output:['4', '']
[ 2, 4 ]
The only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of m pages.Polycarp also has n cups of coffee. The coffee in the i-th cup has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not usually being written in a single day (in a perfect world of Berland, at least). Some of them require multiple days of hard work.Let's consider some day of Polycarp's work. Consider Polycarp drinks k cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are a_{i_1}, a_{i_2}, ..., a_{i_k}. Then the first cup he drinks gives him energy to write a_{i_1} pages of coursework, the second cup gives him energy to write max(0, a_{i_2} - 1) pages, the third cup gives him energy to write max(0, a_{i_3} - 2) pages, ..., the k-th cup gives him energy to write max(0, a_{i_k} - k + 1) pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.
Input: ['5 8', '2 3 1 1 2', ''] Output:['4', '']
[ 0, 2 ]
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water.There are only two types of water bottles in the nearby shop β€” 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop.The bottle of the first type costs a burles and the bottle of the second type costs b burles correspondingly.Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly n liters of water in the nearby shop if the bottle of the first type costs a burles and the bottle of the second type costs b burles. You also have to answer q independent queries.
Input: ['4', '10 1 3', '7 3 2', '1 1000 1', '1000000000000 42 88', ''] Output:['10', '9', '1000', '42000000000000', '']
[ 3 ]
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.You are given a string t consisting of n lowercase Latin letters. This string was cyphered as follows: initially, the jury had a string s consisting of n lowercase Latin letters. Then they applied a sequence of no more than n (possibly zero) operations. i-th operation is denoted by two integers a_i and b_i (1 <= a_i, b_i <= n), and means swapping two elements of the string with indices a_i and b_i. All operations were done in the order they were placed in the sequence. For example, if s is xyz and 2 following operations are performed: a_1 = 1, b_1 = 2; a_2 = 2, b_2 = 3, then after the first operation the current string is yxz, and after the second operation the current string is yzx, so t is yzx.You are asked to restore the original string s. Unfortunately, you have no information about the operations used in the algorithm (you don't even know if there were any operations in the sequence). But you may run the same sequence of operations on any string you want, provided that it contains only lowercase Latin letters and its length is n, and get the resulting string after those operations.Can you guess the original string s asking the testing system to run the sequence of swaps no more than 3 times?The string s and the sequence of swaps are fixed in each test; the interactor doesn't try to adapt the test to your solution.
Input: ['yzx', 'aab', 'baa', 'aba'] Output:['? baa', '? aba', '? aab', '! xyz', '']
[ 3 ]
Reziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split.Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic gem is chosen and split, it takes M units of space (since it is split into M gems); if a magic gem is not split, it takes 1 unit.How many different configurations of the resulting set of gems can Reziba have, such that the total amount of space taken is N units? Print the answer modulo 1000000007 (10^9+7). Two configurations are considered different if the number of magic gems Reziba takes to form them differs, or the indices of gems Reziba has to split differ.
Input: ['4 2', ''] Output:['5', '']
[ 3 ]
You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast β€” the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day β€” s_2, the n-th day β€” s_n and (n+1)-th day β€” s_1 again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2).You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2).
Input: ['0 0', '4 6', '3', 'UUU', ''] Output:['5', '']
[ 4 ]
There are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy).You have time to use some emotes only m times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than k times in a row (otherwise the opponent will think that you're trolling him).Note that two emotes i and j (i!=j) such that a_i = a_j are considered different.You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.
Input: ['6 9 2', '1 3 3 7 4 2', ''] Output:['54', '']
[ 2, 3 ]
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 <= l <= r <= n) with maximum arithmetic mean \frac{1}{r - l + 1}\sum\limits_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding).If there are many such subsegments find the longest one.
Input: ['5', '6 1 6 6 0', ''] Output:['2', '']
[ 3 ]
You are given an array a_1, a_2, ..., a_n.You need to perform q queries of the following two types: "MULTIPLY l r x" β€” for every i (l <= i <= r) multiply a_i by x. "TOTIENT l r" β€” print \varphi(\prod \limits_{i=l}^{r} a_i) taken modulo 10^9+7, where \varphi denotes Euler's totient function. The Euler's totient function of a positive integer n (denoted as \varphi(n)) is the number of integers x (1 <= x <= n) such that \gcd(n,x) = 1.
Input: ['4 45 9 1 2TOTIENT 3 3TOTIENT 3 4MULTIPLY 4 4 3TOTIENT 4 4'] Output:['112']
[ 3 ]
This is an interactive problem!An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element (x_i - x_{i - 1}, where i >= 2) is constant β€” such difference is called a common difference of the sequence.That is, an arithmetic progression is a sequence of form x_i = x_1 + (i - 1) d, where d is a common difference of the sequence.There is a secret list of n integers a_1, a_2, ..., a_n.It is guaranteed that all elements a_1, a_2, ..., a_n are between 0 and 10^9, inclusive.This list is special: if sorted in increasing order, it will form an arithmetic progression with positive common difference (d > 0). For example, the list [14, 24, 9, 19] satisfies this requirement, after sorting it makes a list [9, 14, 19, 24], which can be produced as x_n = 9 + 5 \cdot (n - 1).Also you are also given a device, which has a quite discharged battery, thus you can only use it to perform at most 60 queries of following two types: Given a value i (1 <= i <= n), the device will show the value of the a_i. Given a value x (0 <= x <= 10^9), the device will return 1 if an element with a value strictly greater than x exists, and it will return 0 otherwise.Your can use this special device for at most 60 queries. Could you please find out the smallest element and the common difference of the sequence? That is, values x_1 and d in the definition of the arithmetic progression. Note that the array a is not sorted.
Input: ['4', '', '0', '', '1', '', '14', '', '24', '', '9', '', '19', '', ''] Output:['', '> 25', '', '> 15', '', '? 1', '', '? 2', '', '? 3', '', '? 4', '', '! 9 5']
[ 4 ]
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis. Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n\,! (factorial of n).
Input: ['6 9'] Output:['1']
[ 0, 3 ]
An array b is called to be a subarray of a if it forms a continuous subsequence of a, that is, if it is equal to a_l, a_{l + 1}, ..., a_r for some l, r.Suppose m is some known constant. For any array, having m or more elements, let's define it's beauty as the sum of m largest elements of that array. For example: For array x = [4, 3, 1, 5, 2] and m = 3, the 3 largest elements of x are 5, 4 and 3, so the beauty of x is 5 + 4 + 3 = 12. For array x = [10, 10, 10] and m = 2, the beauty of x is 10 + 10 = 20.You are given an array a_1, a_2, ..., a_n, the value of the said constant m and an integer k. Your need to split the array a into exactly k subarrays such that: Each element from a belongs to exactly one subarray. Each subarray has at least m elements. The sum of all beauties of k subarrays is maximum possible.
Input: ['9 2 3', '5 2 5 2 4 1 1 3 2', ''] Output:['21', '3 5 ']
[ 2 ]
The Duck songFor simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen: Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively. Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only. On the other hand, Dmitry is not a fan of black grapes β€” any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes. Michal has a common taste β€” he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input: ['1 6 24 3 3'] Output:['YES']
[ 0, 2 ]
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer x, then choose one machine and reduce the power of its machine by x times, and at the same time increase the power of one another machine by x times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices i and j, and one integer x such that x is a divisor of a_i, and change powers as following: a_i = \frac{a_i}{x}, a_j = a_j \cdot xSasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!
Input: ['5', '1 2 3 4 5', ''] Output:['14', '']
[ 2 ]
Sasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in the country are directed, it's possible to reach the city y from the city x only if x < y. Once Sasha decided to go on a trip around the country and to visit all n cities. He will move with the help of his car, Cheetah-2677. The tank capacity of this model is v liters, and it spends exactly 1 liter of fuel for 1 kilometer of the way. At the beginning of the journey, the tank is empty. Sasha is located in the city with the number 1 and wants to get to the city with the number n. There is a gas station in each city. In the i-th city, the price of 1 liter of fuel is i dollars. It is obvious that at any moment of time, the tank can contain at most v liters of fuel.Sasha doesn't like to waste money, that's why he wants to know what is the minimum amount of money is needed to finish the trip if he can buy fuel in any city he wants. Help him to figure it out!
Input: ['4 2', ''] Output:['4', '']
[ 2, 3 ]
There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain.Each colony arrangement can be expressed as a string of even length, where the i-th character of the string represents the type of villain in the i-th hole. Iron Man can destroy a colony only if the colony arrangement is such that all villains of a certain type either live in the first half of the colony or in the second half of the colony.His assistant Jarvis has a special power. It can swap villains of any two holes, i.e. swap any two characters in the string; he can do this operation any number of times.Now Iron Man asks Jarvis q questions. In each question, he gives Jarvis two numbers x and y. Jarvis has to tell Iron Man the number of distinct colony arrangements he can create from the original one using his powers such that all villains having the same type as those originally living in x-th hole or y-th hole live in the same half and the Iron Man can destroy that colony arrangement.Two colony arrangements are considered to be different if there exists a hole such that different types of villains are present in that hole in the arrangements.
Input: ['abba', '2', '1 4', '1 2', ''] Output:['2', '0', '']
[ 3 ]
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B \cdot n_a \cdot l amount of power, where n_a is the number of avengers and l is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
Input: ['2 2 1 2', '1 3', ''] Output:['6', '']
[ 0, 3, 4 ]
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are n superheroes in avengers team having powers a_1, a_2, ..., a_n, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by 1. They can do at most m operations. Also, on a particular superhero at most k operations can be done.Can you help the avengers team to maximize the average power of their crew?
Input: ['2 4 6', '4 7', ''] Output:['11.00000000000000000000', '']
[ 0, 3 ]
Grigory has n magic stones, conveniently numbered from 1 to n. The charge of the i-th stone is equal to c_i.Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index i, where 2 <= i <= n - 1), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its own charge, but acquires the charges from neighboring stones. In other words, its charge c_i changes to c_i' = c_{i + 1} + c_{i - 1} - c_i.Andrew, Grigory's friend, also has n stones with charges t_i. Grigory is curious, whether there exists a sequence of zero or more synchronization operations, which transforms charges of Grigory's stones into charges of corresponding Andrew's stones, that is, changes c_i into t_i for all i?
Input: ['4', '7 2 4 12', '7 15 10 12', ''] Output:['Yes', '']
[ 3 ]
Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the greatest common divisor (GCD) of integers a \oplus b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function:f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.Here \oplus denotes the bitwise XOR operation, and \& denotes the bitwise AND operation.The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder.You are given q integers a_1, a_2, ..., a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally).
Input: ['3', '2', '3', '5', ''] Output:['3', '1', '7', '']
[ 3 ]
You have a long stick, consisting of m segments enumerated from 1 to m. Each segment is 1 centimeter long. Sadly, some segments are broken and need to be repaired.You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length t placed at some position s will cover segments s, s+1, ..., s+t-1.You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.Time is money, so you want to cut at most k continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?
Input: ['4 100 220 30 75 80'] Output:['17']
[ 2 ]
You are given an integer n (n >= 0) represented with k digits in base (radix) b. So,n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + ... a_{k-1} \cdot b + a_k.For example, if b=17, k=3 and a=[11, 15, 7] then n=11\cdot17^2+15\cdot17+7=3179+255+7=3441.Determine whether n is even or odd.
Input: ['13 33 2 7'] Output:['even']
[ 3 ]
Once, during a lesson, Sasha got bored and decided to talk with his friends. Suddenly, he saw Kefa. Since we can talk endlessly about Kefa, we won't even start doing that. The conversation turned to graphs. Kefa promised Sasha to tell him about one interesting fact from graph theory if Sasha helps Kefa to count the number of beautiful trees. In this task, a tree is a weighted connected graph, consisting of n vertices and n-1 edges, and weights of edges are integers from 1 to m. Kefa determines the beauty of a tree as follows: he finds in the tree his two favorite vertices β€” vertices with numbers a and b, and counts the distance between them. The distance between two vertices x and y is the sum of weights of edges on the simple path from x to y. If the distance between two vertices a and b is equal to m, then the tree is beautiful.Sasha likes graph theory, and even more, Sasha likes interesting facts, that's why he agreed to help Kefa. Luckily, Sasha is familiar with you the best programmer in Byteland. Help Sasha to count the number of beautiful trees for Kefa. Two trees are considered to be distinct if there is an edge that occurs in one of them and doesn't occur in the other one. Edge's weight matters.Kefa warned Sasha, that there can be too many beautiful trees, so it will be enough to count the number modulo 10^9 + 7.
Input: ['3 2 1 3', ''] Output:['5', '']
[ 0, 3 ]
Fedya and Sasha are friends, that's why Sasha knows everything about Fedya.Fedya keeps his patience in an infinitely large bowl. But, unlike the bowl, Fedya's patience isn't infinite, that is why let v be the number of liters of Fedya's patience, and, as soon as v becomes equal to 0, the bowl will burst immediately. There is one tap in the bowl which pumps s liters of patience per second. Notice that s can be negative, in that case, the tap pumps out the patience. Sasha can do different things, so he is able to change the tap's speed. All actions that Sasha does can be represented as q queries. There are three types of queries: "1 t s" β€” add a new event, means that starting from the t-th second the tap's speed will be equal to s. "2 t" β€” delete the event which happens at the t-th second. It is guaranteed that such event exists. "3 l r v" β€” Sasha wonders: if you take all the events for which l <= t <= r and simulate changes of Fedya's patience from the very beginning of the l-th second till the very beginning of the r-th second inclusive (the initial volume of patience, at the beginning of the l-th second, equals to v liters) then when will be the moment when the bowl will burst. If that does not happen, then the answer will be -1. Since Sasha does not want to check what will happen when Fedya's patience ends, and he has already come up with the queries, he is asking you to help him and find the answer for each query of the 3-rd type.It is guaranteed that at any moment of time, there won't be two events which happen at the same second.
Input: ['6', '1 2 1', '1 4 -3', '3 1 6 1', '3 1 6 3', '3 1 6 4', '3 1 6 5', ''] Output:['5', '5.666667', '6', '-1', '']
[ 4 ]
You are given an undirected weighted connected graph with n vertices and m edges without loops and multiple edges.The i-th edge is e_i = (u_i, v_i, w_i); the distance between vertices u_i and v_i along the edge e_i is w_i (1 <= w_i). The graph is connected, i. e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.A minimum spanning tree (MST) in case of positive weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by 1. You can increase the weight of each edge multiple (possibly, zero) times.Suppose that the initial MST cost is k. Your problem is to increase weights of some edges with minimum possible number of operations in such a way that the cost of MST in the obtained graph remains k, but MST is unique (it means that there is only one way to choose MST in the obtained graph).Your problem is to calculate the minimum number of operations required to do it.
Input: ['8 10', '1 2 1', '2 3 2', '2 4 5', '1 4 2', '6 3 3', '6 1 3', '3 5 2', '3 7 1', '4 8 1', '6 2 4', ''] Output:['1', '']
[ 2, 4 ]
The only difference between easy and hard versions is a number of elements in the array.You are given an array a consisting of n integers. The value of the i-th element of the array is a_i.You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 <= l_j <= r_j <= n.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0].You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value \max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input: ['5 4', '2 -2 3 1 2', '1 3', '4 5', '2 5', '1 3', ''] Output:['6', '2', '1 4 ', '']
[ 0, 2 ]