question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
There is a street with n houses in a line, numbered from 1 to n. The house i is initially painted in color c_i. The street is considered beautiful if all houses are painted in the same color. Tom, the painter, is in charge of making the street beautiful. Tom's painting capacity is defined by an integer, let's call it k.On one day, Tom can do the following repainting process that consists of two steps: He chooses two integers l and r such that 1 <= l <= r <= n and r - l + 1 = k . For each house i such that l <= i <= r, he can either repaint it with any color he wants, or ignore it and let it keep its current color. Note that in the same day Tom can use different colors to repaint different houses.Tom wants to know the minimum number of days needed to repaint the street so that it becomes beautiful. | Input: ['3', '10 2', '1 1 2 2 1 1 2 2 2 1', '7 1', '1 2 3 4 5 6 7', '10 3', '1 3 3 3 3 1 2 1 3 3', ''] Output:['3', '6', '2', ''] | [
0,
0,
2
] |
There is a prison that can be represented as a rectangular matrix with n rows and m columns. Therefore, there are n \cdot m prison cells. There are also n \cdot m prisoners, one in each prison cell. Let's denote the cell in the i-th row and the j-th column as (i, j).There's a secret tunnel in the cell (r, c), that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell (i, j) can move to cells ( i - 1 , j ) , ( i + 1 , j ) , ( i , j - 1 ) , or ( i , j + 1 ), as long as the target cell is inside the prison. They can also choose to stay in cell (i, j).The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell ( r , c ) if they move optimally. Note that there can be any number of prisoners in the same cell at the same time. | Input: ['3', '10 10 1 1', '3 5 2 4', '10 2 5 1', ''] Output:['18', '4', '6', ''] | [
0,
3
] |
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k\cdot b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them? | Input: ['7', '1 1 1 1', '2 2 2 2', '1 2 3 4', '4 3 2 1', '228 21 11 3', '239 21 11 3', '1000000 1 1000000 1', ''] Output:['1', '2', '1', '5', '534', '-1', '500000500000', ''] | [
2,
3,
4
] |
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.Tenten keeps a record for all events, and she ends up with a list of the following types of records: + means that she placed another shuriken on the showcase; - x means that the shuriken of price x was bought. Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out! | Input: ['4', '+', '+', '- 2', '+', '- 3', '+', '- 1', '- 4', ''] Output:['YES', '4 2 3 1 ', ''] | [
2
] |
After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j.Tayuya wants to play a melody of n notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference.For example, if a = [1, 1, 2, 2, 3, 3], and the sequence of notes is 4, 11, 11, 12, 12, 13, 13 (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7, as shown on the picture. | Input: ['1 4 100 10 30 5', '6', '101 104 105 110 130 200', ''] Output:['0', ''] | [
0,
4
] |
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is even.In order to open a door, Naruto must find such n seals with integer energies b_1, b_2, ..., b_n that the following equality holds: a_{1} \cdot b_{1} + a_{2} \cdot b_{2} + ... + a_{n} \cdot b_{n} = 0. All b_i must be nonzero as well as a_i are, and also must not exceed 100 by absolute value. Please find required seals for every room there. | Input: ['2', '2', '1 100', '4', '1 2 3 6', ''] Output:['-100 1', '1 1 1 -1', ''] | [
3
] |
Let's consider the following game of Alice and Bob on a directed acyclic graph. Each vertex may contain an arbitrary number of chips. Alice and Bob make turns alternating. Alice goes first. In one turn player can move exactly one chip along any edge outgoing from the vertex that contains this chip to the end of this edge. The one who cannot make a turn loses. Both players play optimally.Consider the following process that takes place every second on a given graph with n vertices: An integer v is chosen equiprobably from [1, n + 1]. If v <=q n, we add a chip to the v-th vertex and go back to step 1. If v = n + 1, Alice and Bob play the game with the current arrangement of chips and the winner is determined. After that, the process is terminated. Find the probability that Alice will win the game. It can be shown that the answer can be represented as \frac{P}{Q}, where P and Q are coprime integers and Q \not\equiv 0 \pmod{998\,244\,353}. Print the value of P \cdot Q^{-1} \bmod 998\,244\,353. | Input: ['1 0', ''] Output:['0', ''] | [
3
] |
According to a legend the Hanoi Temple holds a permutation of integers from 1 to n. There are n stones of distinct colors lying in one line in front of the temple. Monks can perform the following operation on stones: choose a position i (1 <= i <= n) and cyclically shift stones at positions i, p[i], p[p[i]], .... That is, a stone from position i will move to position p[i], a stone from position p[i] will move to position p[p[i]], and so on, a stone from position j, such that p[j] = i, will move to position i.Each day the monks must obtain a new arrangement of stones using an arbitrary number of these operations. When all possible arrangements will have been obtained, the world will end. You are wondering, what if some elements of the permutation could be swapped just before the beginning? How many days would the world last?You want to get a permutation that will allow the world to last as long as possible, using the minimum number of exchanges of two elements of the permutation.Two arrangements of stones are considered different if there exists a position i such that the colors of the stones on that position are different in these arrangements. | Input: ['3', '3', '2 3 1', '3', '2 1 3', '3', '1 2 3', ''] Output:['3 0', '3 1', '3 2', ''] | [
2,
3
] |
You've got a string S consisting of n lowercase English letters from your friend. It turned out that this is a number written in poman numerals. The poman numeral system is long forgotten. All that's left is the algorithm to transform number from poman numerals to the numeral system familiar to us. Characters of S are numbered from 1 to n from left to right. Let's denote the value of S as f(S), it is defined as follows: If |S| > 1, an arbitrary integer m (1 <= m < |S|) is chosen, and it is defined that f(S) = -f(S[1, m]) + f(S[m + 1, |S|]), where S[l, r] denotes the substring of S from the l-th to the r-th position, inclusively. Otherwise S = c, where c is some English letter. Then f(S) = 2^{pos(c)}, where pos(c) is the position of letter c in the alphabet (pos(a) = 0, pos(z) = 25). Note that m is chosen independently on each step.Your friend thinks it is possible to get f(S) = T by choosing the right m on every step. Is he right? | Input: ['2 -1', 'ba', ''] Output:['Yes', ''] | [
2,
3
] |
Currently, XXOC's rap is a string consisting of zeroes, ones, and question marks. Unfortunately, haters gonna hate. They will write x angry comments for every occurrence of subsequence 01 and y angry comments for every occurrence of subsequence 10. You should replace all the question marks with 0 or 1 in such a way that the number of angry comments would be as small as possible.String b is a subsequence of string a, if it can be obtained by removing some characters from a. Two occurrences of a subsequence are considered distinct if sets of positions of remaining characters are distinct. | Input: ['0?1', '2 3', ''] Output:['4', ''] | [
0,
2
] |
We call a positive integer number fair if it is divisible by each of its nonzero digits. For example, 102 is fair (because it is divisible by 1 and 2), but 282 is not, because it isn't divisible by 8. Given a positive integer n. Find the minimum integer x, such that n <=q x and x is fair. | Input: ['4', '1', '282', '1234567890', '1000000000000000000', ''] Output:['1', '288', '1234568040', '1000000000000000000', ''] | [
0
] |
There are n points on a plane. The i-th point has coordinates (x_i, y_i). You have two horizontal platforms, both of length k. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same y-coordinate) and have integer borders. If the left border of the platform is (x, y) then the right border is (x + k, y) and all points between borders (including borders) belong to the platform.Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same y-coordinate.When you place both platforms on a plane, all points start falling down decreasing their y-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.Your task is to find the maximum number of points you can save if you place both platforms optimally.You have to answer t independent test cases.For better understanding, please read the Note section below to see a picture for the first test case. | Input: ['4', '7 1', '1 5 2 3 1 5 4', '1 3 6 7 2 5 4', '1 1', '1000000000', '1000000000', '5 10', '10 7 5 15 8', '20 199 192 219 1904', '10 10', '15 19 8 17 20 10 9 2 10 19', '12 13 6 17 1 14 7 9 19 3', ''] Output:['6', '1', '5', '10', ''] | [
4
] |
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.You have to answer t independent test cases. | Input: ['5', '2 1', '1 1', '500 4', '217871987498122 10', '100000000000000001 1', ''] Output:['8', '0', '500', '2128012501878', '899999999999999999', ''] | [
2,
3
] |
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: The array consists of n distinct positive (greater than 0) integers. The array contains two elements x and y (these elements are known for you) such that x < y. If you sort the array in increasing order (such that a_1 < a_2 < ... < a_n), differences between all adjacent (consecutive) elements are equal (i.e. a_2 - a_1 = a_3 - a_2 = ... = a_n - a_{n-1}). It can be proven that such an array always exists under the constraints given below.Among all possible arrays that satisfy the given conditions, we ask you to restore one which has the minimum possible maximum element. In other words, you have to minimize \max(a_1, a_2, ..., a_n).You have to answer t independent test cases. | Input: ['5', '2 1 49', '5 20 50', '6 20 50', '5 3 8', '9 13 22', ''] Output:['1 49 ', '20 40 30 50 10', '26 32 20 38 44 50 ', '8 23 18 13 3 ', '1 10 13 4 19 22 25 16 7 '] | [
0,
3
] |
You are given four integers a, b, x and y. Initially, a >= x and b >= y. You can do the following operation no more than n times: Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y. Your task is to find the minimum possible product of a and b (a \cdot b) you can achieve by applying the given operation no more than n times.You have to answer t independent test cases. | Input: ['7', '10 10 8 5 3', '12 8 8 7 2', '12343 43 4543 39 123212', '1000000000 1000000000 1 1 1', '1000000000 1000000000 1 1 1000000000', '10 11 2 1 5', '10 11 9 1 10', ''] Output:['70', '77', '177177', '999999999000000000', '999999999', '55', '10', ''] | [
0,
2,
3
] |
You are given two integers a and b.In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k \in [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.Your task is to find the minimum number of moves required to obtain b from a.You have to answer t independent test cases. | Input: ['6', '5 5', '13 42', '18 4', '1337 420', '123456789 1000000000', '100500 9000', ''] Output:['0', '3', '2', '92', '87654322', '9150', ''] | [
2,
3
] |
You are given a positive integer k and an array a_1, a_2, ..., a_n of non-negative distinct integers not smaller than k and not greater than 2^c-1.In each of the next k seconds, one element is chosen randomly equiprobably out of all n elements and decreased by 1.For each integer x, 0 <=q x <=q 2^c - 1, you need to find the probability that in the end the bitwise XOR of all elements of the array is equal to x. Each of these values can be represented as an irreducible fraction \frac{p}{q}, and you need to find the value of p \cdot q^{-1} modulo 998\,244\,353. | Input: ['4 1 3', '1 2 3 4', ''] Output:['0 0 0 748683265 0 499122177 0 748683265 ', ''] | [
3
] |
You are given a sequence a_1, a_2, ..., a_n of non-negative integers.You need to find the largest number m of triples (i_1, j_1, k_1), (i_2, j_2, k_2), ..., (i_m, j_m, k_m) such that: 1 <=q i_p < j_p < k_p <=q n for each p in 1, 2, ..., m; a_{i_p} = a_{k_p} = 0, a_{j_p} \neq 0; all a_{j_1}, a_{j_2}, ..., a_{j_m} are different; all i_1, j_1, k_1, i_2, j_2, k_2, ..., i_m, j_m, k_m are different. | Input: ['8', '1', '1', '2', '0 0', '3', '0 1 0', '6', '0 0 1 2 0 0', '6', '0 1 0 0 1 0', '6', '0 1 3 2 0 0', '6', '0 0 0 0 5 0', '12', '0 1 0 2 2 2 0 0 3 3 4 0', ''] Output:['0', '0', '1', '2', '1', '1', '1', '2', ''] | [
2,
4
] |
You are given m sets of integers A_1, A_2, ..., A_m; elements of these sets are integers between 1 and n, inclusive.There are two arrays of positive integers a_1, a_2, ..., a_m and b_1, b_2, ..., b_n. In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.You can make several (maybe none) operations (some sets can become empty).After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y \in A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.You call a cycle i_1 \to e_1 \to i_2 \to e_2 \to ... \to i_k \to e_k \to i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.Find the minimum number of coins you should pay to get a graph without rainbow cycles. | Input: ['3 2', '1 2 3', '4 5', '2 1 2', '2 1 2', '2 1 2', ''] Output:['11', ''] | [
2
] |
There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points.Searchlight j can see a robber i if a_i <=q c_j and b_i <=q d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i).What is the minimum number of moves you need to perform to reach a safe configuration? | Input: ['1 1', '0 0', '2 3', ''] Output:['3', ''] | [
0,
4
] |
There is a road with length l meters. The start of the road has coordinate 0, the end of the road has coordinate l.There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end and the second car will drive from the end to the start.Initially, they will drive with a speed of 1 meter per second. There are n flags at different coordinates a_1, a_2, ..., a_n. Each time when any of two cars drives through a flag, the speed of that car increases by 1 meter per second.Find how long will it take for cars to meet (to reach the same coordinate). | Input: ['5', '2 10', '1 9', '1 10', '1', '5 7', '1 2 3 4 6', '2 1000000000', '413470354 982876160', '9 478', '1 10 25 33 239 445 453 468 477', ''] Output:['3.000000000000000', '3.666666666666667', '2.047619047619048', '329737645.750000000000000', '53.700000000000000', ''] | [
3,
4
] |
You are given a non-decreasing array of non-negative integers a_1, a_2, ..., a_n. Also you are given a positive integer k.You want to find m non-decreasing arrays of non-negative integers b_1, b_2, ..., b_m, such that: The size of b_i is equal to n for all 1 <=q i <=q m. For all 1 <=q j <=q n, a_j = b_{1, j} + b_{2, j} + ... + b_{m, j}. In the other word, array a is the sum of arrays b_i. The number of different elements in the array b_i is at most k for all 1 <=q i <=q m. Find the minimum possible value of m, or report that there is no possible m. | Input: ['6', '4 1', '0 0 0 1', '3 1', '3 3 3', '11 3', '0 1 2 2 3 3 3 4 4 4 4', '5 3', '1 2 3 4 5', '9 4', '2 2 3 5 7 11 13 13 17', '10 7', '0 1 1 2 3 3 4 5 5 6', ''] Output:['-1', '1', '2', '2', '2', '1', ''] | [
2,
3
] |
Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.There are n cities in the republic, some of them are connected by m directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city 1, travel to the city n by roads along some path, give a concert and fly away.As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads β in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from 1 to n, and for security reasons it has to be the shortest possible.Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from 1 to n or the shortest path's length would be greatest possible.A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length. | Input: ['3 4', '1 2 0', '1 3 1', '2 3 0', '2 3 1', ''] Output:['2', '011'] | [
2
] |
This is an interactive problem.We hid from you a permutation p of length n, consisting of the elements from 1 to n. You want to guess it. To do that, you can give us 2 different indices i and j, and we will reply with p_{i} \bmod p_{j} (remainder of division p_{i} by p_{j}).We have enough patience to answer at most 2 \cdot n queries, so you should fit in this constraint. Can you do it?As a reminder, a permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). | Input: ['3', '', '1', '', '2', '', '1', '', '0'] Output:['? 1 2', '', '? 3 2', '', '? 1 3', '', '? 2 1', '', '! 1 3 2'] | [
3
] |
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.You're given n positive integers a_1, a_2, ..., a_n. Using each of them exactly at once, you're to make such sequence b_1, b_2, ..., b_n that sequence c_1, c_2, ..., c_n is lexicographically maximal, where c_i=GCD(b_1,...,b_i) - the greatest common divisor of the first i elements of b. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.A sequence a is lexicographically smaller than a sequence b if and only if one of the following holds: a is a prefix of b, but a!=b; in the first position where a and b differ, the sequence a has a smaller element than the corresponding element in b. | Input: ['7', '2', '2 5', '4', '1 8 2 3', '3', '3 8 9', '5', '64 25 75 100 50', '1', '42', '6', '96 128 88 80 52 7', '5', '2 4 8 16 17', ''] Output:['5 2 ', '8 2 1 3 ', '9 3 8 ', '100 50 25 75 64 ', '42 ', '128 96 80 88 52 7 ', '17 2 4 8 16 ', ''] | [
0,
2,
3
] |
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most \frac{n}{2} elements (where n β length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + ...c = 0). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has a = [1, 0, 1, 0, 0, 0] and she removes 2nd and 4th elements, a will become equal [1, 1, 0, 0] and its alternating sum is 1 - 1 + 0 - 0 = 0.Help her! | Input: ['4', '2', '1 0', '2', '0 0', '4', '0 1 1 1', '4', '1 1 0 0', ''] Output:['1', '0', '1', '0', '2', '1 1', '4', '1 1 0 0', ''] | [
3
] |
This is an interactive problem.There is an unknown integer x (1<= x<= n). You want to find x.At first, you have a set of integers \{1, 2, ..., n\}. You can perform the following operations no more than 10000 times: A a: find how many numbers are multiples of a in the current set. B a: find how many numbers are multiples of a in this set, and then delete all multiples of a, but x will never be deleted (even if it is a multiple of a). In this operation, a must be greater than 1. C a: it means that you know that x=a. This operation can be only performed once. Remember that in the operation of type B a>1 must hold.Write a program, that will find the value of x. | Input: ['10', '', '2', '', '4', '', '0'] Output:['', 'B 4', '', 'A 2', '', 'A 8', '', 'C 4', ''] | [
3
] |
You are given a sequence of n integers a_1, a_2, ..., a_n.You have to construct two sequences of integers b and c with length n that satisfy: for every i (1<=q i<=q n) b_i+c_i=a_i b is non-decreasing, which means that for every 1<i<=q n, b_i>=q b_{i-1} must hold c is non-increasing, which means that for every 1<i<=q n, c_i<=q c_{i-1} must hold You have to minimize \max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c.Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, ..., a_r. You have to find the minimum possible value of \max(b_i,c_i) for the initial sequence and for sequence after each change. | Input: ['4', '2 -1 7 3', '2', '2 4 -3', '3 4 2', ''] Output:['5', '5', '6', ''] | [
2,
3
] |
You are given an array of integers a_1,a_2,...,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t). | Input: ['4', '5', '-1 -2 -3 -4 -5', '6', '-1 -2 -3 1 2 -1', '6', '-1 0 0 0 -1 -1', '6', '-9 -7 -5 -3 -2 1', ''] Output:['-120', '12', '0', '945', ''] | [
0,
2
] |
Given a set of integers (it can contain equal elements).You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B).Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: mex(\{1,4,0,2,2,1\})=3 mex(\{3,3,2,1,3,0,0\})=4 mex(\varnothing)=0 (mex for empty set) The set is splitted into two subsets A and B if for any integer number x the number of occurrences of x into this set is equal to the sum of the number of occurrences of x into A and the number of occurrences of x into B. | Input: ['4', '6', '0 2 1 5 0 1', '3', '0 1 2', '4', '0 2 0 1', '6', '1 2 3 4 5 6', ''] Output:['5', '3', '4', '0', ''] | [
2,
3
] |
This is an interactive problem.Consider a fixed positive integer n. Two players, First and Second play a game as follows: First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants). To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.You are given the integer n. Your task is to decide which player you wish to play as and win the game. | Input: ['2', '', '1 1 2 2', '', '0', ''] Output:['', 'Second', '', '1 3', '', ''] | [
3
] |
Let a_1, ..., a_n be an array of n positive integers. In one operation, you can choose an index i such that a_i = i, and remove a_i from the array (after the removal, the remaining parts are concatenated).The weight of a is defined as the maximum number of elements you can remove.You must answer q independent queries (x, y): after replacing the x first elements of a and the y last elements of a by n+1 (making them impossible to remove), what would be the weight of a? | Input: ['13 5', '2 2 3 9 5 4 6 5 7 8 3 11 13', '3 1', '0 0', '2 4', '5 0', '0 12', ''] Output:['5', '11', '6', '1', '0', ''] | [
2,
4
] |
The mythic world of Chess Land is a rectangular grid of squares with R rows and C columns, R being greater than or equal to C. Its rows and columns are numbered from 1 to R and 1 to C, respectively. The inhabitants of Chess Land are usually mentioned as pieces in everyday language, and there are 5 specific types of them roaming the land: pawns, rooks, bishops, queens and kings. Contrary to popular belief, chivalry is long dead in Chess Land, so there are no knights to be found.Each piece is unique in the way it moves around from square to square: in one step, a pawn can move one row forward (i.e. from row r to r+1), without changing columns; a rook can move any number of columns left/right without changing rows OR move any number of rows forward/backward without changing columns; a bishop can move to any square of the two diagonals intersecting at its currently occupied square; a queen can move to any square where a rook or a bishop could move to from her position; and a king can move to any of the 8 adjacent squares. In the following figure, we marked by X the squares each piece can move to in a single step (here, the rows are numbered from bottom to top, and the columns from left to right). Recently, Chess Land has become a dangerous place: pieces that are passing through the land can get captured unexpectedly by unknown forces and simply disappear. As a consequence, they would like to reach their destinations as fast (i.e. in as few moves) as possible, and they are also interested in the number of different ways it is possible for them to reach it, using the minimal number of steps β because more paths being available could mean lower chances of getting captured. Two paths are considered different if they differ in at least one visited square.For this problem, let us assume that pieces are entering Chess Land in a given column of row 1, and exit the land in a given column of row R. Your task is to answer Q questions: given the type of a piece, the column it enters row 1 and the column it must reach in row R in order to exit, compute the minimal number of moves it has to make in Chess Land, and the number of different ways it is able to do so. | Input: ['8 8 5', 'P 1 2', 'R 4 8', 'Q 2 3', 'B 3 6', 'K 5 5', ''] Output:['0 0', '2 2', '2 5', '2 2', '7 393', ''] | [
3
] |
Once upon a time, in the Land of the Shamans, everyone lived on the Sky-High Beanstalk. Each shaman had a unique identifying number i between 0 and N-1, and an altitude value H_i, representing how high he lived above ground level. The distance between two altitudes is the absolute value of their difference.All shamans lived together in peace, until one of them stole the formula of the world-famous Potion of Great Power. To cover his/her tracks, the Thief has put a Curse on the land: most inhabitants could no longer trust each other...Despite the very difficult circumstances, the Order of Good Investigators have gained the following information about the Curse: When the Curse first takes effect, everyone stops trusting each other. The Curse is unstable: at the end of each day (exactly at midnight), one pair of shamans will start or stop trusting each other. Unfortunately, each shaman will only ever trust at most D others at any given time. They have also reconstructed a log of who trusted whom: for each night they know which pair of shamans started/stopped trusting each other.They believe the Thief has whispered the formula to an Evil Shaman. To avoid detection, both of them visited the home of one of their (respective) trusted friends. During the visit, the Thief whispered the formula to the Evil Shaman through the window. (Note: this trusted friend did not have to be home at the time. In fact, it's even possible that they visited each other's houses β shamans are weird.)Fortunately, whispers only travel short distances, so the Order knows the two trusted friends visited (by the Thief and the Evil Shaman) must live very close to each other.They ask you to help with their investigation. They would like to test their suspicions: what if the Thief was x, the Evil Shaman was y, and the formula was whispered on day v? What is the smallest distance the whispered formula had to travel? That is, what is the minimum distance between the apartments of some shamans x' and y' (i.e. \min<=ft(<=ft|H_{x'} - H_{y'}\right|\right)), such that x' was a trusted friend of x and y' was a trusted friend of y on day v?They will share all their information with you, then ask you a number of questions. You need to answer each question immediately, before receiving the next one. | Input: ['6 5 11 4', '2 42 1000 54 68 234', '0 1', '2 0', '3 4', '3 5', '3 5', '1 3', '5 3', '0 5', '3 0', '1 3', '3 5', '0 3 4', '3 0 8', '0 5 5', '3 0 11'] Output:['', '', '', '', '', '', '', '', '', '', '', '', '', '26', '0', '1000000000', '14'] | [
4
] |
Everybody knows that BalΓ‘zs has the fanciest fence in the whole town. It's built up from N fancy sections. The sections are rectangles standing closely next to each other on the ground. The ith section has integer height h_i and integer width w_i. We are looking for fancy rectangles on this fancy fence. A rectangle is fancy if: its sides are either horizontal or vertical and have integer lengths the distance between the rectangle and the ground is integer the distance between the rectangle and the left side of the first section is integer it's lying completely on sections What is the number of fancy rectangles? This number can be very big, so we are interested in it modulo 10^9+7. | Input: ['2', '1 2', '1 2', ''] Output:['12', ''] | [
3
] |
You are given an array a of length 2^n. You should process q queries on it. Each query has one of the following 4 types: Replace(x, k) β change a_x to k; Reverse(k) β reverse each subarray [(i-1) \cdot 2^k+1, i \cdot 2^k] for all i (i >= 1); Swap(k) β swap subarrays [(2i-2) \cdot 2^k+1, (2i-1) \cdot 2^k] and [(2i-1) \cdot 2^k+1, 2i \cdot 2^k] for all i (i >= 1); Sum(l, r) β print the sum of the elements of subarray [l, r]. Write a program that can quickly process given queries. | Input: ['2 3', '7 4 9 9', '1 2 8', '3 1', '4 2 4', ''] Output:['24', ''] | [
4
] |
You are given a tree that consists of n nodes. You should label each of its n-1 edges with an integer in such way that satisfies the following conditions: each integer must be greater than 0; the product of all n-1 numbers should be equal to k; the number of 1-s among all n-1 integers must be minimum possible. Let's define f(u,v) as the sum of the numbers on the simple path from node u to node v. Also, let \sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j) be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo 10^9 + 7.In this problem, since the number k can be large, the result of the prime factorization of k is given instead. | Input: ['3', '4', '1 2', '2 3', '3 4', '2', '2 2', '4', '3 4', '1 3', '3 2', '2', '3 2', '7', '6 1', '2 3', '4 6', '7 3', '5 1', '3 6', '4', '7 5 13 3', ''] Output:['17', '18', '286', ''] | [
2,
3
] |
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0. In one operation, you can choose two different indices i and j (1 <= i, j <= n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y. Now you'd like to make a non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array a is non-decreasing if and only if a_1 <= a_2 <= ... <= a_n. | Input: ['4', '1', '8', '6', '4 3 6 6 2 9', '4', '4 5 6 7', '5', '7 5 2 2 4', ''] Output:['YES', 'YES', 'YES', 'NO', ''] | [
3
] |
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively.You can rearrange the elements in both sequences a and b however you like. After that, let's define a sequence c as follows:c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}You'd like to make \sum_{i=1}^n c_i (the sum of all elements of the sequence c) as large as possible. What is the maximum possible sum? | Input: ['3', '2 3 2', '3 3 1', '4 0 1', '2 3 0', '0 0 1', '0 0 1', ''] Output:['4', '2', '0', ''] | [
2,
3
] |
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. The description of the first test case. Since sometimes it's impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point B exist? | Input: ['6', '4 0', '5 8', '0 1000000', '0 0', '1 0', '1000000 1000000', ''] Output:['0', '3', '1000000', '0', '1', '0', ''] | [
3
] |
Polycarp plays a (yet another!) strategic computer game. In this game, he leads an army of mercenaries.Polycarp wants to gather his army for a quest. There are n mercenaries for hire, and the army should consist of some subset of them.The i-th mercenary can be chosen if the resulting number of chosen mercenaries is not less than l_i (otherwise he deems the quest to be doomed) and not greater than r_i (he doesn't want to share the trophies with too many other mercenaries). Furthermore, m pairs of mercenaries hate each other and cannot be chosen for the same quest. How many non-empty subsets does Polycarp need to consider? In other words, calculate the number of non-empty subsets of mercenaries such that the size of this subset belongs to [l_i, r_i] for each chosen mercenary, and there are no two mercenaries in the subset that hate each other.The answer may be large, so calculate it modulo 998244353. | Input: ['3 0', '1 1', '2 3', '1 3', ''] Output:['3', ''] | [
0,
3
] |
You are given an integer value x and a string s consisting of digits from 1 to 9 inclusive.A substring of a string is a contiguous subsequence of that string.Let f(l, r) be the sum of digits of a substring s[l..r].Let's call substring s[l_1..r_1] x-prime if f(l_1, r_1) = x; there are no values l_2, r_2 such that l_1 <= l_2 <= r_2 <= r_1; f(l_2, r_2) \neq x; x is divisible by f(l_2, r_2). You are allowed to erase some characters from the string. If you erase a character, the two resulting parts of the string are concatenated without changing their order.What is the minimum number of characters you should erase from the string so that there are no x-prime substrings in it? If there are no x-prime substrings in the given string s, then print 0. | Input: ['116285317', '8', ''] Output:['2', ''] | [
0
] |
You have a multiset containing several integers. Initially, it contains a_1 elements equal to 1, a_2 elements equal to 2, ..., a_n elements equal to n.You may apply two types of operations: choose two integers l and r (l <= r), then remove one occurrence of l, one occurrence of l + 1, ..., one occurrence of r from the multiset. This operation can be applied only if each number from l to r occurs at least once in the multiset; choose two integers i and x (x >= 1), then remove x occurrences of i from the multiset. This operation can be applied only if the multiset contains at least x occurrences of i. What is the minimum number of operations required to delete all elements from the multiset? | Input: ['4', '1 4 1 1', ''] Output:['2', ''] | [
2
] |
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that: 1 <= i < j < k < l <= n; a_i = a_k and a_j = a_l; | Input: ['2', '5', '2 2 2 2 2', '6', '1 3 3 1 2 3', ''] Output:['5', '2', ''] | [
0,
3
] |
Consider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows: if the character w_{i-x} exists and is equal to 1, then s_i is 1 (formally, if i > x and w_{i-x} = 1, then s_i = 1); if the character w_{i+x} exists and is equal to 1, then s_i is 1 (formally, if i + x <= n and w_{i+x} = 1, then s_i = 1); if both of the aforementioned conditions are false, then s_i is 0. You are given the integer x and the resulting string s. Reconstruct the original string w. | Input: ['3', '101110', '2', '01', '1', '110', '1', ''] Output:['111011', '10', '-1', ''] | [
0,
2
] |
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower β at most f units.In the blacksmith shop, you found cnt_s swords and cnt_w war axes. Each sword weights s units and each war axe β w units. You don't care what to take, since each of them will melt into one steel ingot.What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop? | Input: ['3', '33 27', '6 10', '5 6', '100 200', '10 10', '5 5', '1 19', '1 3', '19 5', ''] Output:['11', '20', '3', ''] | [
0,
2,
3
] |
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := <=ft\lfloor\frac{w_i}{2}\right\rfloor).Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins.Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make \sum\limits_{v \in leaves} w(root, v) <= S, where leaves is the list of all leaves.You have to answer t independent test cases. | Input: ['4', '4 18', '2 1 9 2', '3 2 4 1', '4 1 1 2', '3 20', '2 1 8 1', '3 1 7 2', '5 50', '1 3 100 1', '1 5 10 2', '2 3 123 2', '5 4 55 1', '2 100', '1 2 409 2', ''] Output:['0', '0', '11', '6', ''] | [
2,
4
] |
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex 1 is the root of this tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := <=ft\lfloor\frac{w_i}{2}\right\rfloor).Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make \sum\limits_{v \in leaves} w(root, v) <= S, where leaves is the list of all leaves.You have to answer t independent test cases. | Input: ['3', '3 20', '2 1 8', '3 1 7', '5 50', '1 3 100', '1 5 10', '2 3 123', '5 4 55', '2 100', '1 2 409', ''] Output:['0', '8', '3', ''] | [
2
] |
You are given a binary string s consisting of n zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer t independent test cases. | Input: ['4', '4', '0011', '6', '111111', '5', '10101', '8', '01010000', ''] Output:['2', '1 2 2 1 ', '6', '1 2 3 4 5 6 ', '1', '1 1 1 1 1 ', '4', '1 1 1 1 1 2 3 4 ', ''] | [
2
] |
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are k teams (a_1, b_1), (a_2, b_2), ..., (a_k, b_k), where a_i is the weight of the first participant of the i-th team and b_i is the weight of the second participant of the i-th team, then the condition a_1 + b_1 = a_2 + b_2 = ... = a_k + b_k = s, where s is the total weight of each team, should be satisfied.Your task is to choose such s that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer t independent test cases. | Input: ['5', '5', '1 2 3 4 5', '8', '6 6 6 6 6 6 8 8', '8', '1 2 2 1 2 1 1 2', '3', '1 3 3', '6', '1 1 3 4 2 2', ''] Output:['2', '3', '4', '1', '2', ''] | [
0,
2
] |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.During one move, you can choose some gift 1 <= i <= n and do one of the following operations: eat exactly one candy from this gift (decrease a_i by one); eat exactly one orange from this gift (decrease b_i by one); eat exactly one candy and exactly one orange from this gift (decrease both a_i and b_i by one). Of course, you can not eat a candy or orange if it's not present in the gift (so neither a_i nor b_i can become less than zero).As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: a_1 = a_2 = ... = a_n and b_1 = b_2 = ... = b_n (and a_i equals b_i is not necessary).Your task is to find the minimum number of moves required to equalize all the given gifts.You have to answer t independent test cases. | Input: ['5', '3', '3 5 6', '3 2 3', '5', '1 2 3 4 5', '5 4 3 2 1', '3', '1 1 1', '2 2 2', '6', '1 1000000000 1000000000 1000000000 1000000000 1000000000', '1 1 1 1 1 1', '3', '10 12 8', '7 5 4', ''] Output:['6', '16', '0', '4999999995', '7', ''] | [
2
] |
You are given the array a consisting of n positive (greater than zero) integers.In one move, you can choose two indices i and j (i!=j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| <= 1) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer t independent test cases. | Input: ['5', '3', '1 2 2', '4', '5 5 5 5', '3', '1 2 4', '4', '1 3 4 4', '1', '100', ''] Output:['YES', 'YES', 'NO', 'NO', 'YES', ''] | [
2
] |
A running competition is going to be held soon. The stadium where the competition will be held can be represented by several segments on the coordinate plane: two horizontal segments: one connecting the points (0, 0) and (x, 0), the other connecting the points (0, y) and (x, y); n + 1 vertical segments, numbered from 0 to n. The i-th segment connects the points (a_i, 0) and (a_i, y); 0 = a_0 < a_1 < a_2 < ... < a_{n - 1} < a_n = x. For example, here is a picture of the stadium with x = 10, y = 5, n = 3 and a = [0, 3, 5, 10]: A lap is a route that goes along the segments, starts and finishes at the same point, and never intersects itself (the only two points of a lap that coincide are its starting point and ending point). The length of a lap is a total distance travelled around it. For example, the red route in the picture representing the stadium is a lap of length 24.The competition will be held in q stages. The i-th stage has length l_i, and the organizers want to choose a lap for each stage such that the length of the lap is a divisor of l_i. The organizers don't want to choose short laps for the stages, so for each stage, they want to find the maximum possible length of a suitable lap.Help the organizers to calculate the maximum possible lengths of the laps for the stages! In other words, for every l_i, find the maximum possible integer L such that l_i \bmod L = 0, and there exists a lap of length exactly L.If it is impossible to choose such a lap then print -1. | Input: ['3 10 5', '0 3 5 10', '6', '24 30 14 16 18 10', ''] Output:['24 30 14 16 -1 -1 '] | [
3
] |
Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won x rounds in a row. For example, if Bob won five rounds in a row and x = 2, then two sets ends.You know that Alice and Bob have already played n rounds, and you know the results of some rounds. For each x from 1 to n, calculate the maximum possible number of sets that could have already finished if each set lasts until one of the players wins x rounds in a row. It is possible that the last set is still not finished β in that case, you should not count it in the answer. | Input: ['6', '11?000', ''] Output:['6 3 2 1 0 0 ', ''] | [
2,
4
] |
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: first, second, third. This order deals 5 + 1 + 2 \cdot 8 = 22 damage; first, third, second. This order deals 5 + 8 + 2 \cdot 1 = 15 damage; second, first, third. This order deals 1 + 2 \cdot 5 + 8 = 19 damage; second, third, first. This order deals 1 + 2 \cdot 8 + 2 \cdot 5 = 27 damage; third, first, second. This order deals 8 + 2 \cdot 5 + 1 = 19 damage; third, second, first. This order deals 8 + 2 \cdot 1 + 2 \cdot 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. | Input: ['6', '1 5', '0 10', '1 -5', '0 5', '1 11', '0 -10', ''] Output:['5', '25', '10', '15', '36', '21', ''] | [
2,
3,
4
] |
You are given three multisets of pairs of colored sticks: R pairs of red sticks, the first pair has length r_1, the second pair has length r_2, ..., the R-th pair has length r_R; G pairs of green sticks, the first pair has length g_1, the second pair has length g_2, ..., the G-th pair has length g_G; B pairs of blue sticks, the first pair has length b_1, the second pair has length b_2, ..., the B-th pair has length b_B; You are constructing rectangles from these pairs of sticks with the following process: take a pair of sticks of one color; take a pair of sticks of another color different from the first one; add the area of the resulting rectangle to the total area. Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.What is the maximum area you can achieve? | Input: ['1 1 1', '3', '5', '4', ''] Output:['20', ''] | [
2
] |
You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (\sum\limits_{i=l}^{r} a_i = r - l + 1).For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0].Calculate the number of good subarrays of the array a. | Input: ['3', '3', '120', '5', '11011', '6', '600005', ''] Output:['3', '6', '1', ''] | [
3
] |
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.For example, if the string is 10110, there are 6 possible moves (deleted characters are bold): \textbf{1}0110 \to 0110; 1\textbf{0}110 \to 1110; 10\textbf{1}10 \to 1010; 101\textbf{1}0 \to 1010; 10\textbf{11}0 \to 100; 1011\textbf{0} \to 1011. After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I.βe. the following sequence of moves is valid: 10\textbf{11}0 \to 1\textbf{00} \to 1.The game ends when the string becomes empty, and the score of each player is the number of 1-characters deleted by them.Each player wants to maximize their score. Calculate the resulting score of Alice. | Input: ['5', '01111001', '0000', '111111', '101010101', '011011110111', ''] Output:['4', '0', '6', '3', '6', ''] | [
2
] |
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i <= a_{i + 1}). Find three indices i, j, k such that 1 <= i < j < k <= n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. | Input: ['3', '7', '4 6 11 11 15 18 20', '4', '10 10 10 11', '3', '1 1 1000000000', ''] Output:['2 3 6', '-1', '1 2 3', ''] | [
3
] |
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 <= i <= n-1 then a_i = c^i.Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1. Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence. | Input: ['3', '1 3 2', ''] Output:['1', ''] | [
0,
3
] |
You are given n strings s_1, s_2, ..., s_n consisting of lowercase Latin letters.In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal? | Input: ['4', '2', 'caa', 'cbb', '3', 'cba', 'cba', 'cbb', '4', 'ccab', 'cbac', 'bca', 'acbcc', '4', 'acb', 'caf', 'c', 'cbafc', ''] Output:['YES', 'NO', 'YES', 'NO', ''] | [
2
] |
Ziota found a video game called "Monster Invaders".Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns.For the sake of simplicity, we only consider two different types of monsters and three different types of guns.Namely, the two types of monsters are: a normal monster with 1 hp. a boss with 2 hp. And the three types of guns are: Pistol, deals 1 hp in damage to one monster, r_1 reloading time Laser gun, deals 1 hp in damage to all the monsters in the current level (including the boss), r_2 reloading time AWP, instantly kills any monster, r_3 reloading time The guns are initially not loaded, and the Ziota can only reload 1 gun at a time.The levels of the game can be considered as an array a_1, a_2, ..., a_n, in which the i-th stage has a_i normal monsters and 1 boss. Due to the nature of the game, Ziota cannot use the Pistol (the first type of gun) or AWP (the third type of gun) to shoot the boss before killing all of the a_i normal monsters.If Ziota damages the boss but does not kill it immediately, he is forced to move out of the current level to an arbitrary adjacent level (adjacent levels of level i (1 < i < n) are levels i - 1 and i + 1, the only adjacent level of level 1 is level 2, the only adjacent level of level n is level n - 1). Ziota can also choose to move to an adjacent level at any time. Each move between adjacent levels are managed by portals with d teleportation time.In order not to disrupt the space-time continuum within the game, it is strictly forbidden to reload or shoot monsters during teleportation. Ziota starts the game at level 1. The objective of the game is rather simple, to kill all the bosses in all the levels. He is curious about the minimum time to finish the game (assuming it takes no time to shoot the monsters with a loaded gun and Ziota has infinite ammo on all the three guns). Please help him find this value. | Input: ['4 1 3 4 3', '3 2 5 1', ''] Output:['34'] | [
2
] |
T is playing a game with his friend, HL.There are n piles of stones, the i-th pile initially has a_i stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in the previous turn (the pile that was chosen by the other player, or if the current turn is the first turn then the player can choose any non-empty pile). The player who cannot choose a pile in his turn loses, and the game ends.Assuming both players play optimally, given the starting configuration of t games, determine the winner of each game. | Input: ['2', '1', '2', '2', '1 1', ''] Output:['T', 'HL', ''] | [
0,
2
] |
You are given an array a of n integers.You want to make all elements of a equal to zero by doing the following operation exactly three times: Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of a equal to zero. | Input: ['4', '1 3 2 4', ''] Output:['1 1 ', '-1', '3 4', '4 2', '2 4', '-3 -6 -6'] | [
2
] |
Boboniu likes bit operations. He wants to play a game with you.Boboniu gives you two sequences of non-negative integers a_1,a_2,...,a_n and b_1,b_2,...,b_m.For each i (1<= i<= n), you're asked to choose a j (1<= j<= m) and let c_i=a_i\& b_j, where \& denotes the bitwise AND operation. Note that you can pick the same j for different i's.Find the minimum possible c_1 | c_2 | ... | c_n, where | denotes the bitwise OR operation. | Input: ['4 2', '2 6 4 0', '2 4', ''] Output:['2'] | [
0,
2
] |
Boboniu gives you r red balls, g green balls, b blue balls, w white balls. He allows you to do the following operation as many times as you want: Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations. | Input: ['4', '0 1 1 1', '8 1 9 3', '0 0 0 0', '1000000000 1000000000 1000000000 1000000000', ''] Output:['No', 'Yes', 'Yes', 'Yes', ''] | [
0,
3
] |
Since Boboniu finished building his Jianghu, he has been doing Kungfu on these mountains every day. Boboniu designs a map for his n mountains. He uses n-1 roads to connect all n mountains. Every pair of mountains is connected via roads.For the i-th mountain, Boboniu estimated the tiredness of doing Kungfu on the top of it as t_i. He also estimated the height of each mountain as h_i.A path is a sequence of mountains M such that for each i (1 <= i < |M|), there exists a road between M_i and M_{i+1}. Boboniu would regard the path as a challenge if for each i (1<= i<|M|), h_{M_i}<= h_{M_{i+1}}.Boboniu wants to divide all n-1 roads into several challenges. Note that each road must appear in exactly one challenge, but a mountain may appear in several challenges. Boboniu wants to minimize the total tiredness to do all the challenges. The tiredness of a challenge M is the sum of tiredness of all mountains in it, i.e. \sum_{i=1}^{|M|}t_{M_i}. He asked you to find the minimum total tiredness. As a reward for your work, you'll become a guardian in his Jianghu. | Input: ['5', '40 10 30 50 20', '2 3 2 3 1', '1 2', '1 3', '2 4', '2 5', ''] Output:['160', ''] | [
2
] |
Boboniu defines BN-string as a string s of characters 'B' and 'N'.You can perform the following operations on the BN-string s: Remove a character of s. Remove a substring "BN" or "NB" of s. Add a character 'B' or 'N' to the end of s. Add a string "BN" or "NB" to the end of s. Note that 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.Boboniu thinks that BN-strings s and t are similar if and only if: |s|=|t|. There exists a permutation p_1, p_2, ..., p_{|s|} such that for all i (1<= i<= |s|), s_{p_i}=t_i. Boboniu also defines \text{dist}(s,t), the distance between s and t, as the minimum number of operations that makes s similar to t.Now Boboniu gives you n non-empty BN-strings s_1,s_2,..., s_n and asks you to find a non-empty BN-string t such that the maximum distance to string s is minimized, i.e. you need to minimize \max_{i=1}^n \text{dist}(s_i,t). | Input: ['3', 'B', 'N', 'BN', ''] Output:['1', 'BN', ''] | [
4,
4
] |
Boboniu has a directed graph with n vertices and m edges.The out-degree of each vertex is at most k.Each edge has an integer weight between 1 and m. No two edges have equal weights.Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,...,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1<= c_i<= i) smallest weight among all edges outgoing from u.Now Boboniu asks you to calculate the number of tuples (c_1,c_2,...,c_k) such that 1<= c_i<= i for all i (1<= i<= k). Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules. | Input: ['4 6 3', '4 2 1', '1 2 2', '2 4 3', '4 1 4', '4 3 5', '3 1 6', ''] Output:['2', ''] | [
0
] |
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.Du will chat in the group for n days. On the i-th day: If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, \cdots, \min(i+d,n)-th days. Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak.Du asked you to find the maximum total fun factor among all possible permutations of a. | Input: ['5 2 11', '8 10 15 23 5', ''] Output:['48', ''] | [
2
] |
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | Input: ['4', '7', '1 7 1 6 4 4 6', '8', '1 1 4 6 4 6 4 7', '3', '3 3 3', '6', '2 5 2 3 1 4', ''] Output:['3', '2', '0', '4', ''] | [
2,
3
] |
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has n planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: + x: the storehouse received a plank with length x - x: one plank with length x was removed from the storehouse (it is guaranteed that the storehouse had some planks with length x). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides. | Input: ['6', '1 1 1 2 1 1', '6', '+ 2', '+ 1', '- 1', '+ 2', '- 1', '+ 2', ''] Output:['NO', 'YES', 'NO', 'NO', 'NO', 'YES', ''] | [
2
] |
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size 1*1, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors. | Input: ['2', '3', '4', ''] Output:['2', '3', ''] | [
2,
3
] |
As Kevin is in BigMan's house, suddenly a trap sends him onto a grid with n rows and m columns.BigMan's trap is configured by two arrays: an array a_1,a_2,...,a_n and an array b_1,b_2,...,b_m.In the i-th row there is a heater which heats the row by a_i degrees, and in the j-th column there is a heater which heats the column by b_j degrees, so that the temperature of cell (i,j) is a_i+b_j.Fortunately, Kevin has a suit with one parameter x and two modes: heat resistance. In this mode suit can stand all temperatures greater or equal to x, but freezes as soon as reaches a cell with temperature less than x. cold resistance. In this mode suit can stand all temperatures less than x, but will burn as soon as reaches a cell with temperature at least x.Once Kevin lands on a cell the suit automatically turns to cold resistance mode if the cell has temperature less than x, or to heat resistance mode otherwise, and cannot change after that.We say that two cells are adjacent if they share an edge.Let a path be a sequence c_1,c_2,...,c_k of cells such that c_i and c_{i+1} are adjacent for 1 <=q i <=q k-1.We say that two cells are connected if there is a path between the two cells consisting only of cells that Kevin can step on.A connected component is a maximal set of pairwise connected cells.We say that a connected component is good if Kevin can escape the grid starting from it β when it contains at least one border cell of the grid, and that it's bad otherwise.To evaluate the situation, Kevin gives a score of 1 to each good component and a score of 2 for each bad component.The final score will be the difference between the total score of components with temperatures bigger than or equal to x and the score of components with temperatures smaller than x.There are q possible values of x that Kevin can use, and for each of them Kevin wants to know the final score.Help Kevin defeat BigMan! | Input: ['5 5 1', '1 3 2 3 1', '1 3 2 3 1', '5', ''] Output:['-1', ''] | [
3
] |
zscoder has a deck of n+m custom-made cards, which consists of n cards labelled from 1 to n and m jokers. Since zscoder is lonely, he wants to play a game with himself using those cards. Initially, the deck is shuffled uniformly randomly and placed on the table. zscoder has a set S which is initially empty. Every second, zscoder draws the top card from the deck. If the card has a number x written on it, zscoder removes the card and adds x to the set S. If the card drawn is a joker, zscoder places all the cards back into the deck and reshuffles (uniformly randomly) the n+m cards to form a new deck (hence the new deck now contains all cards from 1 to n and the m jokers). Then, if S currently contains all the elements from 1 to n, the game ends. Shuffling the deck doesn't take time at all. What is the expected number of seconds before the game ends? We can show that the answer can be written in the form \frac{P}{Q} where P, Q are relatively prime integers and Q \neq 0 \bmod 998244353. Output the value of (P \cdot Q^{-1}) modulo 998244353. | Input: ['2 1', ''] Output:['5', ''] | [
3
] |
Omkar has a pie tray with k (2 <=q k <=q 20) spots. Each spot in the tray contains either a chocolate pie or a pumpkin pie. However, Omkar does not like the way that the pies are currently arranged, and has another ideal arrangement that he would prefer instead.To assist Omkar, n elves have gathered in a line to swap the pies in Omkar's tray. The j-th elf from the left is able to swap the pies at positions a_j and b_j in the tray.In order to get as close to his ideal arrangement as possible, Omkar may choose a contiguous subsegment of the elves and then pass his pie tray through the subsegment starting from the left. However, since the elves have gone to so much effort to gather in a line, they request that Omkar's chosen segment contain at least m (1 <=q m <=q n) elves.Formally, Omkar may choose two integers l and r satisfying 1 <=q l <=q r <=q n and r - l + 1 >=q m so that first the pies in positions a_l and b_l will be swapped, then the pies in positions a_{l + 1} and b_{l + 1} will be swapped, etc. until finally the pies in positions a_r and b_r are swapped.Help Omkar choose a segment of elves such that the amount of positions in Omkar's final arrangement that contain the same type of pie as in his ideal arrangement is the maximum possible. Note that since Omkar has a big imagination, it might be that the amounts of each type of pie in his original arrangement and in his ideal arrangement do not match. | Input: ['4 2 5', '11000', '00011', '1 3', '3 5', '4 2', '3 4', ''] Output:['5', '1 3', ''] | [
3
] |
Omkar is standing at the foot of Celeste mountain. The summit is n meters away from him, and he can see all of the mountains up to the summit, so for all 1 <=q j <=q n he knows that the height of the mountain at the point j meters away from himself is h_j meters. It turns out that for all j satisfying 1 <=q j <=q n - 1, h_j < h_{j + 1} (meaning that heights are strictly increasing).Suddenly, a landslide occurs! While the landslide is occurring, the following occurs: every minute, if h_j + 2 <=q h_{j + 1}, then one square meter of dirt will slide from position j + 1 to position j, so that h_{j + 1} is decreased by 1 and h_j is increased by 1. These changes occur simultaneously, so for example, if h_j + 2 <=q h_{j + 1} and h_{j + 1} + 2 <=q h_{j + 2} for some j, then h_j will be increased by 1, h_{j + 2} will be decreased by 1, and h_{j + 1} will be both increased and decreased by 1, meaning that in effect h_{j + 1} is unchanged during that minute.The landslide ends when there is no j such that h_j + 2 <=q h_{j + 1}. Help Omkar figure out what the values of h_1, ..., h_n will be after the landslide ends. It can be proven that under the given constraints, the landslide will always end in finitely many minutes.Note that because of the large amount of input, it is recommended that your code uses fast IO. | Input: ['4', '2 6 7 8', ''] Output:['5 5 6 7', ''] | [
2,
3,
4
] |
This is an interactive problem.Omkar has just come across a duck! The duck is walking on a grid with n rows and n columns (2 <=q n <=q 25) so that the grid contains a total of n^2 cells. Let's denote by (x, y) the cell in the x-th row from the top and the y-th column from the left. Right now, the duck is at the cell (1, 1) (the cell in the top left corner) and would like to reach the cell (n, n) (the cell in the bottom right corner) by moving either down 1 cell or to the right 1 cell each second.Since Omkar thinks ducks are fun, he wants to play a game with you based on the movement of the duck. First, for each cell (x, y) in the grid, you will tell Omkar a nonnegative integer a_{x,y} not exceeding 10^{16}, and Omkar will then put a_{x,y} uninteresting problems in the cell (x, y). After that, the duck will start their journey from (1, 1) to (n, n). For each cell (x, y) that the duck crosses during their journey (including the cells (1, 1) and (n, n)), the duck will eat the a_{x,y} uninteresting problems in that cell. Once the duck has completed their journey, Omkar will measure their mass to determine the total number k of uninteresting problems that the duck ate on their journey, and then tell you k.Your challenge, given k, is to exactly reproduce the duck's path, i. e. to tell Omkar precisely which cells the duck crossed on their journey. To be sure of your mastery of this game, Omkar will have the duck complete q different journeys (1 <=q q <=q 10^3). Note that all journeys are independent: at the beginning of each journey, the cell (x, y) will still contain a_{x,y} uninteresting tasks. | Input: ['4', '', '', '', '', '3', '23', '', '', '', '', '', '', '', '26', '', '', '', '', '', '', '', '27', '', '', '', '', '', '', '', ''] Output:['1 2 3 6', '4 6 2 10', '9 0 7 3', '2 8 8 2', '', '', '1 1', '1 2', '1 3', '2 3', '2 4', '3 4', '4 4', '', '1 1', '2 1', '3 1', '3 2', '3 3', '3 4', '4 4', '', '1 1', '1 2', '1 3', '1 4', '2 4', '3 4', '4 4', ''] | [
3
] |
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are n players arranged in a circle, so that for all j such that 2 <=q j <=q n, player j - 1 is to the left of the player j, and player j is to the right of player j - 1. Additionally, player n is to the left of player 1, and player 1 is to the right of player n.Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either 0, 1, or 2 other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly 1 other player, then they should logically attack that player in response. If instead a player is being attacked by 0 or 2 other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the n players in the game to make them instead attack another player β i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy. | Input: ['5', '4', 'RLRL', '6', 'LRRRRL', '8', 'RLLRRRLL', '12', 'LLLLRRLRRRLL', '5', 'RRRRR', ''] Output:['0', '1', '1', '3', '2', ''] | [
2
] |
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In 1 operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add 1 to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array b is a subsegment of an array c if b can be obtained from c by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array b_1, b_2, ..., b_n is called nondecreasing if b_i<= b_{i+1} for every i from 1 to n-1. | Input: ['3', '4', '5 3 2 5', '5', '1 2 3 5 3', '3', '1 1 1', ''] Output:['3', '2', '0', ''] | [
2
] |
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k operations with this array.Define one operation as the following: Set d to be the maximum value of your array. For every i from 1 to n, replace a_{i} with d-a_{i}. The goal is to predict the contents in the array after k operations. Please help Ray determine what the final sequence will look like! | Input: ['3', '2 1', '-199 192', '5 19', '5 -1 4 2 0', '1 2', '69', ''] Output:['391 0', '0 6 1 3 5', '0', ''] | [
3
] |
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index i such that 1 <=q i < n and a_{i} \neq a_{i+1}, delete both a_i and a_{i+1} from the array and put a_{i}+a_{i+1} in their place. For example, for array [7, 4, 3, 7] you can choose i = 2 and the array will become [7, 4+3, 7] = [7, 7, 7]. Note that in this array you can't apply this operation anymore.Notice that one operation will decrease the size of the password by 1. What is the shortest possible length of the password after some number (possibly 0) of operations? | Input: ['2', '4', '2 1 3 1', '2', '420 420', ''] Output:['1', '2', ''] | [
2,
3
] |
You have a simple and connected undirected graph consisting of n nodes and m edges.Consider any way to pair some subset of these n nodes such that no node is present in more than one pair. This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most 2 edges (out of the 6 possible edges). More formally, for any two pairs, (a,b) and (c,d), the induced subgraph with nodes \{a,b,c,d\} should have at most 2 edges. Please note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.Now, do one of the following: Find a simple path consisting of at least \lceil \frac{n}{2} \rceil nodes. Here, a path is called simple if it does not visit any node multiple times. Find a valid pairing in which at least \lceil \frac{n}{2} \rceil nodes are paired. It can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement. | Input: ['4', '6 5', '1 4', '2 5', '3 6', '1 5', '3 5', '6 5', '1 4', '2 5', '3 6', '1 5', '3 5', '12 14', '1 2', '2 3', '3 4', '4 1', '1 5', '1 12', '2 6', '2 7', '3 8', '3 9', '4 10', '4 11', '2 4', '1 3', '12 14', '1 2', '2 3', '3 4', '4 1', '1 5', '1 12', '2 6', '2 7', '3 8', '3 9', '4 10', '4 11', '2 4', '1 3', ''] Output:['PATH', '4 ', '1 5 3 6', 'PAIRING', '2', '1 6', '2 4', 'PAIRING', '3', '1 8', '2 5', '4 10', 'PAIRING', '4', '1 7', '2 9', '3 11', '4 5', ''] | [
2
] |
A binary matrix is called good if every even length square sub-matrix has an odd number of ones. Given a binary matrix a consisting of n rows and m columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all. All the terms above have their usual meanings β refer to the Notes section for their formal definitions. | Input: ['3 3', '101', '001', '110', ''] Output:['2'] | [
0,
2
] |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).Consider a permutation p of length n, we build a graph of size n using it as follows: For every 1 <=q i <=q n, find the largest j such that 1 <=q j < i and p_j > p_i, and add an undirected edge between node i and node j For every 1 <=q i <=q n, find the smallest j such that i < j <=q n and p_j > p_i, and add an undirected edge between node i and node j In cases where no such j exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.For clarity, consider as an example n = 4, and p = [3,1,4,2]; here, the edges of the graph are (1,3),(2,1),(2,3),(4,3).A permutation p is cyclic if the graph built using p has at least one simple cycle. Given n, find the number of cyclic permutations of length n. Since the number may be very large, output it modulo 10^9+7.Please refer to the Notes section for the formal definition of a simple cycle | Input: ['4', ''] Output:['16'] | [
3
] |
Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j). Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept on that will move to the cell (i,j+1). Similarly, if the cell (i,j) is assigned direction D, any luggage kept on that will move to the cell (i+1,j). If at any moment, the luggage moves out of the grid, it is considered to be lost. There is a counter at the cell (n,m) from where all luggage is picked. A conveyor belt is called functional if and only if any luggage reaches the counter regardless of which cell it is placed in initially. More formally, for every cell (i,j), any luggage placed in this cell should eventually end up in the cell (n,m). This may not hold initially; you are, however, allowed to change the directions of some cells to make the conveyor belt functional. Please determine the minimum amount of cells you have to change.Please note that it is always possible to make any conveyor belt functional by changing the directions of some set of cells. | Input: ['4', '3 3', 'RRD', 'DDR', 'RRC', '1 4', 'DDDC', '6 9', 'RDDDDDRRR', 'RRDDRRDDD', 'RRDRDRRDR', 'DDDDRDDRR', 'DRRDRDDDR', 'DDRDRRDDC', '1 1', 'C', ''] Output:['1', '3', '9', '0', ''] | [
0,
2
] |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).For a positive integer n, we call a permutation p of length n good if the following condition holds for every pair i and j (1 <= i <= j <= n) β (p_i \text{ OR } p_{i+1} \text{ OR } ... \text{ OR } p_{j-1} \text{ OR } p_{j}) >= j-i+1, where \text{OR} denotes the bitwise OR operation. In other words, a permutation p is good if for every subarray of p, the \text{OR} of all elements in it is not less than the number of elements in that subarray. Given a positive integer n, output any good permutation of length n. We can show that for the given constraints such a permutation always exists. | Input: ['3', '1', '3', '7', ''] Output:['1', '3 1 2', '4 3 5 2 7 1 6', ''] | [
3
] |
Berland year consists of m months with d days each. Months are numbered from 1 to m. Berland week consists of w days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than w days.A pair (x, y) such that x < y is ambiguous if day x of month y is the same day of the week as day y of month x.Count the number of ambiguous pairs. | Input: ['5', '6 7 4', '10 7 12', '12 30 7', '1 1 1', '3247834 10298779 625324', ''] Output:['6', '9', '5', '0', '116461800', ''] | [
3
] |
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. \sum\limits_{i=1}^{n}{\text{intersection_length}([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.What is the minimum number of steps you need to make I greater or equal to k? | Input: ['3', '3 5', '1 2', '3 4', '2 1000000000', '1 1', '999999999 999999999', '10 3', '5 10', '7 8', ''] Output:['7', '2000000000', '0', ''] | [
0,
2,
3
] |
Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1.Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}.Let's say string t is good if its left cyclic shift is equal to its right cyclic shift.You are given string s which consists of digits 0β9.What is the minimum number of characters you need to erase from s to make it good? | Input: ['3', '95831', '100120013', '252525252525', ''] Output:['3', '5', '0', ''] | [
0,
2
] |
You are given an array a_1, a_2, ..., a_n, consisting of n positive integers. Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves: move right β go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n. move left β go from your current index x to x-1 and add a_{x-1} to your score. This move can only be performed if x>1. Also, you can't perform two or more moves to the left in a row. You want to perform exactly k moves. Also, there should be no more than z moves to the left among them.What is the maximum score you can achieve? | Input: ['4', '5 4 0', '1 5 4 3 2', '5 4 1', '1 5 4 3 2', '5 4 4', '10 20 30 40 50', '10 7 3', '4 6 8 2 9 9 7 4 10 9', ''] Output:['15', '19', '150', '56', ''] | [
0,
2
] |
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.You are given two integers l and r. Find two integers x and y such that l <= x < y <= r and l <= LCM(x, y) <= r. | Input: ['4', '1 1337', '13 69', '2 4', '88 89', ''] Output:['6 7', '14 21', '2 4', '-1 -1', ''] | [
2,
3
] |
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined: Choose position i (1 <= i <= n); Add a_i to ans; If b_i \neq -1 then add a_i to a_{b_i}. What is the maximum ans you can get by performing the operation on each i (1 <= i <= n) exactly once?Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them. | Input: ['3', '1 2 3', '2 3 -1', ''] Output:['10', '1 2 3 ', ''] | [
2
] |
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are n cities and nβ1 undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from 1 to n and the city 1 is a capital. In other words, the country has a tree structure.There are m citizens living in the country. A p_i people live in the i-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the i-th city calculates a happiness index h_i as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city i the happiness index will be equal exactly to h_i". | Input: ['2', '7 4', '1 0 1 1 0 1 0', '4 0 0 -1 0 -1 0', '1 2', '1 3', '1 4', '3 5', '3 6', '3 7', '5 11', '1 2 5 2 1', '-11 -2 -6 -2 -1', '1 2', '1 3', '1 4', '3 5', ''] Output:['YES', 'YES', ''] | [
2,
3
] |
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.In the beginning, uncle Bogdan wrote on a board a positive integer x consisting of n digits. After that, he wiped out x and wrote integer k instead, which was the concatenation of binary representations of digits x consists of (without leading zeroes). For example, let x = 729, then k = 111101001 (since 7 = 111, 2 = 10, 9 = 1001).After some time, uncle Bogdan understood that he doesn't know what to do with k and asked Denis to help. Denis decided to wipe last n digits of k and named the new number as r.As a result, Denis proposed to find such integer x of length n that r (as number) is maximum possible. If there are multiple valid x then Denis is interested in the minimum one.All crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you?Note: in this task, we compare integers (x or k) as numbers (despite what representations they are written in), so 729 < 1999 or 111 < 1000. | Input: ['2', '1', '3', ''] Output:['8', '998', ''] | [
2,
3
] |
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer x as nearly prime if it can be represented as p \cdot q, where 1 < p < q and p and q are prime numbers. For example, integers 6 and 10 are nearly primes (since 2 \cdot 3 = 6 and 2 \cdot 5 = 10), but integers 1, 3, 4, 16, 17 or 44 are not.Captain Flint guessed an integer n and asked you: can you represent it as the sum of 4 different positive integers where at least 3 of them should be nearly prime.Uncle Bogdan easily solved the task and joined the crew. Can you do the same? | Input: ['7', '7', '23', '31', '36', '44', '100', '258', ''] Output:['NO', 'NO', 'YES', '14 10 6 1', 'YES', '5 6 10 15', 'YES', '6 7 10 21', 'YES', '2 10 33 55', 'YES', '10 21 221 6'] | [
0,
2,
3
] |
This problem is split into two tasks. In this task, you are required to find the minimum possible answer. In the task Village (Maximum) you are required to find the maximum possible answer. Each task is worth 50 points.There are N houses in a certain village. A single villager lives in each of the houses. The houses are connected by roads. Each road connects two houses and is exactly 1 kilometer long. From each house it is possible to reach any other using one or several consecutive roads. In total there are N-1 roads in the village.One day all villagers decided to move to different houses β that is, after moving each house should again have a single villager living in it, but no villager should be living in the same house as before. We would like to know the smallest possible total length in kilometers of the shortest paths between the old and the new houses for all villagers. Example village with seven houses For example, if there are seven houses connected by roads as shown on the figure, the smallest total length is 8 km (this can be achieved by moving 1 \to 6, 2 \to 4, 3 \to 1, 4 \to 2, 5 \to 7, 6 \to 3, 7 \to 5).Write a program that finds the smallest total length of the shortest paths in kilometers and an example assignment of the new houses to the villagers. | Input: ['4', '1 2', '2 3', '3 4', ''] Output:['4', '2 1 4 3', ''] | [
2
] |
You are given an undirected graph where each edge has one of two colors: black or red.Your task is to assign a real number to each node so that: for each black edge the sum of values at its endpoints is 1; for each red edge the sum of values at its endpoints is 2; the sum of the absolute values of all assigned numbers is the smallest possible. Otherwise, if it is not possible, report that there is no feasible assignment of the numbers. | Input: ['4 4', '1 2 1', '2 3 2', '1 3 2', '3 4 1', ''] Output:['YES', '0.5 0.5 1.5 -0.5', ''] | [
3,
4,
4
] |
Serge, the chef of the famous restaurant "Salt, Pepper & Garlic" is trying to obtain his first Michelin star. He has been informed that a secret expert plans to visit his restaurant this evening.Even though the expert's name hasn't been disclosed, Serge is certain he knows which dish from the menu will be ordered as well as what the taste preferences of the expert are. Namely, the expert requires an extremely precise proportion of salt, pepper and garlic powder in his dish.Serge keeps a set of bottles with mixtures of salt, pepper and garlic powder on a special shelf in the kitchen. For each bottle, he knows the exact amount of each of the ingredients in kilograms. Serge can combine any number of bottled mixtures (or just use one of them directly) to get a mixture of particular proportions needed for a certain dish.Luckily, the absolute amount of a mixture that needs to be added to a dish is so small that you can assume that the amounts in the bottles will always be sufficient. However, the numeric values describing the proportions may be quite large.Serge would like to know whether it is possible to obtain the expert's favourite mixture from the available bottles, and if soβwhat is the smallest possible number of bottles needed to achieve that.Furthermore, the set of bottles on the shelf may change over time as Serge receives new ones or lends his to other chefs. So he would like to answer this question after each such change.For example, assume that expert's favorite mixture is 1:1:1 and there are three bottles of mixtures on the shelf: \begin{array}{cccc} \hline \text{Mixture} & \text{Salt} & \text{Pepper} & \text{Garlic powder} \\ \hline 1 & 10 & 20 & 30 \\ 2 & 300 & 200 & 100 \\ 3 & 12 & 15 & 27 \\ \hline \end{array} Amount of ingredient in the bottle, kg To obtain the desired mixture it is enough to use an equivalent amount of mixtures from bottles 1 and 2. If bottle 2 is removed, then it is no longer possible to obtain it.Write a program that helps Serge to solve this task! | Input: ['1 2 3', '6', 'A 5 6 7', 'A 3 10 17', 'R 1', 'A 15 18 21', 'A 5 10 15', 'R 3', ''] Output:['0', '2', '0', '2', '1', '1', ''] | [
3
] |
Linda likes to change her hair color from time to time, and would be pleased if her boyfriend Archie would notice the difference between the previous and the new color. Archie always comments on Linda's hair color if and only if he notices a difference β so Linda always knows whether Archie has spotted the difference or not.There is a new hair dye series in the market where all available colors are numbered by integers from 1 to N such that a smaller difference of the numerical values also means less visual difference.Linda assumes that for these series there should be some critical color difference C (1 <= C <= N) for which Archie will notice color difference between the current color \mathrm{color}_{\mathrm{new}} and the previous color \mathrm{color}_{\mathrm{prev}} if <=ft|\mathrm{color}_{\mathrm{new}} - \mathrm{color}_{\mathrm{prev}}\right| >= C and will not if <=ft|\mathrm{color}_{\mathrm{new}} - \mathrm{color}_{\mathrm{prev}}\right| < C.Now she has bought N sets of hair dye from the new series β one for each of the colors from 1 to N, and is ready to set up an experiment. Linda will change her hair color on a regular basis and will observe Archie's reaction β whether he will notice the color change or not. Since for the proper dye each set should be used completely, each hair color can be obtained no more than once.Before the experiment, Linda was using a dye from a different series which is not compatible with the new one, so for the clearness of the experiment Archie's reaction to the first used color is meaningless.Her aim is to find the precise value of C in a limited number of dyes. Write a program which finds the value of C by experimenting with the given N colors and observing Archie's reactions to color changes. | Input: ['1', '', '7', '', '1', '', '1', '', '0', '', '0', '', '1', ''] Output:['', '? 2', '', '? 7', '', '? 4', '', '? 1', '', '? 5', '', '= 4'] | [
4
] |
Subsets and Splits