question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i!=t_{i + 1} should be satisfied.Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them. | Input: ['9', 'RBGRRBRGG', ''] Output:['2', 'RBGRGBRGR', ''] | [
2
] |
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is t, then for each i, j such that t_i = t_j should be satisfied |i-j|~ mod~ 3 = 0. The value |x| means absolute value of x, the operation x~ mod~ y means remainder of x when divided by y.For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them. | Input: ['3', 'BRB', ''] Output:['1', 'GRB', ''] | [
0,
2,
3
] |
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list.For example, if x=4 and y=6 then the given list can be any permutation of the list [1, 2, 4, 1, 2, 3, 6]. Some of the possible lists are: [1, 1, 2, 4, 6, 3, 2], [4, 6, 1, 1, 2, 3, 2] or [1, 6, 3, 2, 4, 1, 2].Your problem is to restore suitable positive integer numbers x and y that would yield the same list of divisors (possibly in different order).It is guaranteed that the answer exists, i.e. the given list of divisors corresponds to some positive integers x and y. | Input: ['10', '10 2 8 1 2 4 1 20 4 5', ''] Output:['20 8', ''] | [
0,
2,
3
] |
Vasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit.Vasya has n problems to choose from. They are numbered from 1 to n. The difficulty of the i-th problem is d_i. Moreover, the problems are given in the increasing order by their difficulties. The difficulties of all tasks are pairwise distinct. In order to add the i-th problem to the contest you need to pay c_i burles to its author. For each problem in the contest Vasya gets a burles.In order to create a contest he needs to choose a consecutive subsegment of tasks.So the total earnings for the contest are calculated as follows: if Vasya takes problem i to the contest, he needs to pay c_i to its author; for each problem in the contest Vasya gets a burles; let gap(l, r) = \max\limits_{l <= i < r} (d_{i + 1} - d_i)^2. If Vasya takes all the tasks with indices from l to r to the contest, he also needs to pay gap(l, r). If l = r then gap(l, r) = 0. Calculate the maximum profit that Vasya can earn by taking a consecutive segment of tasks. | Input: ['5 10', '1 15', '5 3', '6 11', '7 2', '11 22', ''] Output:['13', ''] | [
4
] |
You are given a binary matrix A of size n * n. Let's denote an x-compression of the given matrix as a matrix B of size \frac{n}{x} * \frac{n}{x} such that for every i \in [1, n], j \in [1, n] the condition A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil] is met.Obviously, x-compression is possible only if x divides n, but this condition is not enough. For example, the following matrix of size 2 * 2 does not have any 2-compression: 01 10 For the given matrix A, find maximum x such that an x-compression of this matrix is possible.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input. | Input: ['8', 'E7', 'E7', 'E7', '00', '00', 'E7', 'E7', 'E7', ''] Output:['1', ''] | [
3
] |
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.You are given a sequence of hits, the i-th hit deals a_i units of damage to the opponent's character. To perform the i-th hit you have to press the button s_i on your gamepad. Hits are numbered from 1 to n.You know that if you press some button more than k times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of a_i over all i for the hits which weren't skipped.Note that if you skip the hit then the counter of consecutive presses the button won't reset.Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons. | Input: ['7 3', '1 5 16 18 7 2 10', 'baaaaca', ''] Output:['54', ''] | [
2
] |
Today at the lesson of mathematics, Petya learns about the digital root.The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. Let's denote the digital root of x as S(x). Then S(5)=5, S(38)=S(3+8=11)=S(1+1=2)=2, S(10)=S(1+0=1)=1.As a homework Petya got n tasks of the form: find k-th positive number whose digital root is x.Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all n tasks from Petya's homework. | Input: ['3', '1 5', '5 2', '3 1', ''] Output:['5', '38', '19', ''] | [
3
] |
You are given a sequence s consisting of n digits from 1 to 9.You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is t_1, t_2, ..., t_k, where k is the number of element in a division, then for each i from 1 to k-1 the condition t_{i} < t_{i + 1} (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if s=654 then you can divide it into parts [6, 54] and it will be suitable division. But if you will divide it into parts [65, 4] then it will be bad division because 65 > 4. If s=123 then you can divide it into parts [1, 23], [1, 2, 3] but not into parts [12, 3].Your task is to find any suitable division for each of the q independent queries. | Input: ['4', '6', '654321', '4', '1337', '2', '33', '4', '2122', ''] Output:['YES', '3', '6 54 321', 'YES', '3', '1 3 37', 'NO', 'YES', '2', '21 22', ''] | [
2
] |
Lunar New Year is approaching, and Bob received a gift from his friend recently — a recursive sequence! He loves this sequence very much and wants to play with it.Let f_1, f_2, ..., f_i, ... be an infinite sequence of positive integers. Bob knows that for i > k, f_i can be obtained by the following recursive equation:f_i = <=ft(f_{i - 1} ^ {b_1} \cdot f_{i - 2} ^ {b_2} \cdot \cdots \cdot f_{i - k} ^ {b_k}\right) \bmod p,which in short isf_i = <=ft(\prod_{j = 1}^{k} f_{i - j}^{b_j}\right) \bmod p,where p = 998\,244\,353 (a widely-used prime), b_1, b_2, ..., b_k are known integer constants, and x \bmod y denotes the remainder of x divided by y.Bob lost the values of f_1, f_2, ..., f_k, which is extremely troublesome – these are the basis of the sequence! Luckily, Bob remembers the first k - 1 elements of the sequence: f_1 = f_2 = ... = f_{k - 1} = 1 and the n-th element: f_n = m. Please find any possible value of f_k. If no solution exists, just tell Bob that it is impossible to recover his favorite sequence, regardless of Bob's sadness. | Input: ['3', '2 3 5', '4 16', ''] Output:['4', ''] | [
3
] |
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, ..., a_n is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: x is a prefix of y, but x!=y (this is impossible in this problem as all considered sequences have the same length); in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. | Input: ['3 2', '1 2', '1 3', ''] Output:['1 2 3 ', ''] | [
2
] |
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.There are n positive integers a_1, a_2, ..., a_n on Bob's homework paper, where n is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least 2 numbers. Suppose the numbers are divided into m groups, and the sum of the numbers in the j-th group is s_j. Bob's aim is to minimize the sum of the square of s_j, that is \sum_{j = 1}^{m} s_j^2.Bob is puzzled by this hard problem. Could you please help him solve it? | Input: ['4', '8 5 2 3', ''] Output:['164', ''] | [
2,
3
] |
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types: 1 — Hiasat can change his handle. 2 s — friend s visits Hiasat's profile. The friend s will be happy, if each time he visits Hiasat's profile his handle would be s.Hiasat asks you to help him, find the maximum possible number of happy friends he can get. | Input: ['5 3', '1', '2 motarack', '2 mike', '1', '2 light', ''] Output:['2', ''] | [
0
] |
Ayoub had an array a of integers of size n and this array had two interesting properties: All the integers in the array were between l and r (inclusive). The sum of all the elements was divisible by 3. Unfortunately, Ayoub has lost his array, but he remembers the size of the array n and the numbers l and r, so he asked you to find the number of ways to restore the array. Since the answer could be very large, print it modulo 10^9 + 7 (i.e. the remainder when dividing by 10^9 + 7). In case there are no satisfying arrays (Ayoub has a wrong memory), print 0. | Input: ['2 1 3', ''] Output:['3', ''] | [
3
] |
Given a string s of length n and integer k (1 <= k <= n). The string s has a level x, if x is largest non-negative integer, such that it's possible to find in s: x non-intersecting (non-overlapping) substrings of length k, all characters of these x substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings). A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers i and j (1 <= i <= j <= n), denoted as s[i ... j] = "s_{i}s_{i+1} ... s_{j}".For example, if k = 2, then: the string "aabb" has level 1 (you can select substring "aa"), the strings "zzzz" and "zzbzz" has level 2 (you can select two non-intersecting substrings "zz" in each of them), the strings "abed" and "aca" have level 0 (you can't find at least one substring of the length k=2 containing the only distinct character). Zuhair gave you the integer k and the string s of length n. You need to find x, the level of the string s. | Input: ['8 2', 'aaacaabb', ''] Output:['2', ''] | [
0
] |
Salem gave you n sticks with integer positive lengths a_1, a_2, ..., a_n.For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from a to b is |a - b|, where |x| means the absolute value of x.A stick length a_i is called almost good for some integer t if |a_i - t| <= 1.Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer t and the total cost of changing is minimum possible. The value of t is not fixed in advance and you can choose it as any positive integer. As an answer, print the value of t and the minimum cost. If there are multiple optimal choices for t, print any of them. | Input: ['3', '10 1 4', ''] Output:['3 7', ''] | [
0
] |
Two people are playing a game with a string s, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.Your task is to determine which player will win if both play optimally. | Input: ['abacaba', ''] Output:['No', ''] | [
3
] |
Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, ..., d_k, such that 1 <=q d_i <=q 9 for all i and d_1 + d_2 + ... + d_k = n.Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among d_1, d_2, ..., d_k. Help him! | Input: ['1', ''] Output:['1', '1 '] | [
3
] |
Let's define radix sum of number a consisting of digits a_1, ... ,a_k and number b consisting of digits b_1, ... ,b_k(we add leading zeroes to the shorter number to match longer length) as number s(a,b) consisting of digits (a_1+b_1)\mod 10, ... ,(a_k+b_k)\mod 10. The radix sum of several integers is defined as follows: s(t_1, ... ,t_n)=s(t_1,s(t_2, ... ,t_n))You are given an array x_1, ... ,x_n. The task is to compute for each integer i (0 <= i < n) number of ways to consequently choose one of the integers from the array n times, so that the radix sum of these integers is equal to i. Calculate these values modulo 2^{58}. | Input: ['2', '5 6', ''] Output:['1', '2', ''] | [
3
] |
Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with n vertices without loops and multiedges, such that a degree of any vertex is at least 3, and also he gave a number 1 <=q k <=q n. Because Johnny is not too smart, he promised to find a simple path with length at least \frac{n}{k} in the graph. In reply, Solving promised to find k simple by vertices cycles with representatives, such that: Length of each cycle is at least 3. Length of each cycle is not divisible by 3. In each cycle must be a representative - vertex, which belongs only to this cycle among all printed cycles. You need to help guys resolve the dispute, for that you need to find a solution for Johnny: a simple path with length at least \frac{n}{k} (n is not necessarily divided by k), or solution for Solving: k cycles that satisfy all the conditions above. If there is no any solution - print -1. | Input: ['4 6 2', '1 2', '1 3', '1 4', '2 3', '2 4', '3 4', ''] Output:['PATH', '4', '1 2 3 4 '] | [
3
] |
This is an interactive problem.Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him: "x", if (x \bmod a) >=q (y \bmod a). "y", if (x \bmod a) < (y \bmod a). We define (x \bmod a) as a remainder of division x by a.Vasya should guess the number a using no more, than 60 questions.It's guaranteed that Petya has a number, that satisfies the inequality 1 <=q a <=q 10^9.Help Vasya playing this game and write a program, that will guess the number a. | Input: ['start', 'x', 'x', 'start', 'x', 'x', 'y', 'start', 'x', 'x', 'y', 'y', 'end', ''] Output:['? 0 0', '? 10 1', '! 1', '? 0 0', '? 3 4', '? 2 5', '! 2', '? 2 4', '? 2 5', '? 3 10', '? 9 1', '! 3', ''] | [
4
] |
You are given a matrix a, consisting of n rows and m columns. Each cell contains an integer in it.You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be s_1, s_2, ..., s_{nm}. The traversal is k-acceptable if for all i (1 <= i <= nm - 1) |s_i - s_{i + 1}| >= k.Find the maximum integer k such that there exists some order of rows of matrix a that it produces a k-acceptable traversal. | Input: ['4 2', '9 9', '10 8', '5 3', '4 3', ''] Output:['5', ''] | [
0,
4
] |
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists. | Input: ['3', '121', ''] Output:['021', ''] | [
2
] |
You are given an array a consisting of n integer numbers.You have to color this array in k colors in such a way that: Each element of the array should be colored in some color; For each i from 1 to k there should be at least one element colored in the i-th color in the array; For each i from 1 to k all elements colored in the i-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers c_1, c_2, ... c_n, where 1 <= c_i <= k and c_i is the color of the i-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any. | Input: ['4 2', '1 2 2 3', ''] Output:['YES', '1 1 2 2', ''] | [
2
] |
You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible.The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S. | Input: ['3', ''] Output:['0', ''] | [
3
] |
You are given an array a_1, a_2, ..., a_n of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to 0. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | Input: ['4', '5 5 7 2', ''] Output:['2', ''] | [
3
] |
There are n cities along the road, which can be represented as a straight line. The i-th city is situated at the distance of a_i kilometers from the origin. All cities are situated in the same direction from the origin. There are m trucks travelling from one city to another. Each truck can be described by 4 integers: starting city s_i, finishing city f_i, fuel consumption c_i and number of possible refuelings r_i. The i-th truck will spend c_i litres of fuel per one kilometer. When a truck arrives in some city, it can be refueled (but refueling is impossible in the middle of nowhere). The i-th truck can be refueled at most r_i times. Each refueling makes truck's gas-tank full. All trucks start with full gas-tank.All trucks will have gas-tanks of the same size V litres. You should find minimum possible V such that all trucks can reach their destinations without refueling more times than allowed. | Input: ['7 6', '2 5 7 10 14 15 17', '1 3 10 0', '1 7 12 7', '4 5 13 3', '4 7 10 1', '4 7 10 1', '1 5 11 2', ''] Output:['55', ''] | [
4
] |
An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code 091), a colon (ASCII code 058), some (possibly zero) vertical line characters (ASCII code 124), another colon, and a closing bracket (ASCII code 093). The length of the accordion is the number of characters in it.For example, [::], [:||:] and [:|||:] are accordions having length 4, 6 and 7. (:|:), {:||:}, [:], ]:||:[ are not accordions. You are given a string s. You want to transform it into an accordion by removing some (possibly zero) characters from it. Note that you may not insert new characters or reorder existing ones. Is it possible to obtain an accordion by removing characters from s, and if so, what is the maximum possible length of the result? | Input: ['|[a:b:|]', ''] Output:['4', ''] | [
2
] |
You are given q queries in the following form:Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i].Can you answer all the queries?Recall that a number x belongs to segment [l, r] if l <= x <= r. | Input: ['5', '2 4 2', '5 10 4', '3 10 1', '1 2 3', '4 6 5', ''] Output:['6', '4', '1', '3', '10', ''] | [
3
] |
Ivan loves burgers and spending money. There are n burger joints on the street where Ivan lives. Ivan has q friends, and the i-th friend suggested to meet at the joint l_i and walk to the joint r_i (l_i <=q r_i). While strolling with the i-th friend Ivan can visit all joints x which satisfy l_i <=q x <=q r_i.For each joint Ivan knows the cost of the most expensive burger in it, it costs c_i burles. Ivan wants to visit some subset of joints on his way, in each of them he will buy the most expensive burger and spend the most money. But there is a small issue: his card broke and instead of charging him for purchases, the amount of money on it changes as follows.If Ivan had d burles before the purchase and he spent c burles at the joint, then after the purchase he would have d \oplus c burles, where \oplus denotes the bitwise XOR operation.Currently Ivan has 2^{2^{100}} - 1 burles and he wants to go out for a walk. Help him to determine the maximal amount of burles he can spend if he goes for a walk with the friend i. The amount of burles he spends is defined as the difference between the initial amount on his account and the final account. | Input: ['47 2 3 431 42 31 3'] Output:['737'] | [
2,
3
] |
Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to insidious taxi drivers.The mayor of the city decided to change the direction of certain roads so that the taxi drivers wouldn't be able to increase the cost of the trip endlessly. More formally, if the taxi driver is on a certain crossroads, they wouldn't be able to reach it again if he performs a nonzero trip. Traffic controllers are needed in order to change the direction the road goes. For every road it is known how many traffic controllers are needed to change the direction of the road to the opposite one. It is allowed to change the directions of roads one by one, meaning that each traffic controller can participate in reversing two or more roads.You need to calculate the minimum number of traffic controllers that you need to hire to perform the task and the list of the roads that need to be reversed. | Input: ['5 62 1 15 2 62 3 23 4 34 5 51 5 4'] Output:['2 21 3 '] | [
4
] |
NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles n and the radius of the inner circle r. NN thinks that, using this information, you can exactly determine the radius of the outer circles R so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture. | Input: ['3 1'] Output:['6.4641016'] | [
3,
4
] |
Mitya and Vasya are playing an interesting game. They have a rooted tree with n vertices, and the vertices are indexed from 1 to n. The root has index 1. Every other vertex i >= 2 has its parent p_i, and vertex i is called a child of vertex p_i.There are some cookies in every vertex of the tree: there are x_i cookies in vertex i. It takes exactly t_i time for Mitya to eat one cookie in vertex i. There is also a chip, which is initially located in the root of the tree, and it takes l_i time to move the chip along the edge connecting vertex i with its parent.Mitya and Vasya take turns playing, Mitya goes first. Mitya moves the chip from the vertex, where the chip is located, to one of its children. Vasya can remove an edge from the vertex, where the chip is located, to one of its children. Vasya can also decide to skip his turn. Mitya can stop the game at any his turn. Once he stops the game, he moves the chip up to the root, eating some cookies along his way. Mitya can decide how many cookies he would like to eat in every vertex on his way. The total time spent on descend, ascend and eating cookies should not exceed T. Please note that in the end of the game the chip is always located in the root of the tree: Mitya can not leave the chip in any other vertex, even if he has already eaten enough cookies — he must move the chip back to the root (and every move from vertex v to its parent takes l_v time).Find out what is the maximum number of cookies Mitya can eat, regardless of Vasya's actions. | Input: ['5 26', '1 5 1 7 7', '1 3 2 2 2', '1 1', '1 1', '2 0', '2 0', ''] Output:['11', ''] | [
4
] |
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw n squares in the snow with a side length of 1. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length 1, parallel to the coordinate axes, with vertices at integer points.In order to draw a segment, Sofia proceeds as follows. If she wants to draw a vertical segment with the coordinates of the ends (x, y) and (x, y+1). Then Sofia looks if there is already a drawn segment with the coordinates of the ends (x', y) and (x', y+1) for some x'. If such a segment exists, then Sofia quickly draws a new segment, using the old one as a guideline. If there is no such segment, then Sofia has to take a ruler and measure a new segment for a long time. Same thing happens when Sofia wants to draw a horizontal segment, but only now she checks for the existence of a segment with the same coordinates x, x+1 and the differing coordinate y.For example, if Sofia needs to draw one square, she will have to draw two segments using a ruler: After that, she can draw the remaining two segments, using the first two as a guide: If Sofia needs to draw two squares, she will have to draw three segments using a ruler: After that, she can draw the remaining four segments, using the first three as a guide: Sofia is in a hurry, so she wants to minimize the number of segments that she will have to draw with a ruler without a guide. Help her find this minimum number. | Input: ['1', ''] Output:['2', ''] | [
3,
4
] |
Fedya loves problems involving data structures. Especially ones about different queries on subsegments. Fedya had a nice array a_1, a_2, ... a_n and a beautiful data structure. This data structure, given l and r, 1 <= l <= r <= n, could find the greatest integer d, such that d divides each of a_l, a_{l+1}, ..., a_{r}. Fedya really likes this data structure, so he applied it to every non-empty contiguous subarray of array a, put all answers into the array and sorted it. He called this array b. It's easy to see that array b contains n(n+1)/2 elements.After that, Fedya implemented another cool data structure, that allowed him to find sum b_l + b_{l+1} + ... + b_r for given l and r, 1 <= l <= r <= n(n+1)/2. Surely, Fedya applied this data structure to every contiguous subarray of array b, called the result c and sorted it. Help Fedya find the lower median of array c.Recall that for a sorted array of length k the lower median is an element at position \lfloor \frac{k + 1}{2} \rfloor, if elements of the array are enumerated starting from 1. For example, the lower median of array (1, 1, 2, 3, 6) is 2, and the lower median of (0, 17, 23, 96) is 17. | Input: ['2', '6 3', ''] Output:['6', ''] | [
3,
4
] |
Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree!Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1.Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. | Input: ['3 5', ''] Output:['Yes', '1 1 ', ''] | [
2,
4
] |
You are given an n * m table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every 2 * 2 square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters. | Input: ['2 2', 'AG', 'CT', ''] Output:['AG', 'CT', ''] | [
0,
2,
3
] |
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v >= 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. | Input: ['5', '1 1 1 1', '1 -1 -1 -1 -1', ''] Output:['1', ''] | [
2
] |
A Thue-Morse-Radecki-Mateusz sequence (Thorse-Radewoosh sequence in short) is an infinite sequence constructed from a finite sequence \mathrm{gen} of length d and an integer m, obtained in the following sequence of steps: In the beginning, we define the one-element sequence M_0=(0). In the k-th step, k >=q 1, we define the sequence M_k to be the concatenation of the d copies of M_{k-1}. However, each of them is altered slightly — in the i-th of them (1 <=q i <=q d), each element x is changed to (x+\mathrm{gen}_i) \pmod{m}. For instance, if we pick \mathrm{gen} = (0, \color{blue}{1}, \color{green}{2}) and m = 4: M_0 = (0), M_1 = (0, \color{blue}{1}, \color{green}{2}), M_2 = (0, 1, 2, \color{blue}{1, 2, 3}, \color{green}{2, 3, 0}), M_3 = (0, 1, 2, 1, 2, 3, 2, 3, 0, \color{blue}{1, 2, 3, 2, 3, 0, 3, 0, 1}, \color{green}{2, 3, 0, 3, 0, 1, 0, 1, 2}), and so on. As you can see, as long as the first element of \mathrm{gen} is 0, each consecutive step produces a sequence whose prefix is the sequence generated in the previous step. Therefore, we can define the infinite Thorse-Radewoosh sequence M_\infty as the sequence obtained by applying the step above indefinitely. For the parameters above, M_\infty = (0, 1, 2, 1, 2, 3, 2, 3, 0, 1, 2, 3, 2, 3, 0, 3, 0, 1, ...).Mateusz picked a sequence \mathrm{gen} and an integer m, and used them to obtain a Thorse-Radewoosh sequence M_\infty. He then picked two integers l, r, and wrote down a subsequence of this sequence A := ((M_\infty)_l, (M_\infty)_{l+1}, ..., (M_\infty)_r).Note that we use the 1-based indexing both for M_\infty and A.Mateusz has his favorite sequence B with length n, and would like to see how large it is compared to A. Let's say that B majorizes sequence X of length n (let's denote it as B >=q X) if and only if for all i \in \{1, 2, ..., n\}, we have B_i >=q X_i.He now asks himself how many integers x in the range [1, |A| - n + 1] there are such that B >=q (A_x, A_{x+1}, A_{x+2}, ..., A_{x+n-1}). As both sequences were huge, answering the question using only his pen and paper turned out to be too time-consuming. Can you help him automate his research? | Input: ['2 2', '0 1', '4', '0 1 1 0', '2 21', ''] Output:['6', ''] | [
0
] |
One Saturday afternoon Egor was playing his favorite RPG game. While discovering new lands and territories, he came across the following sign: Egor is a passionate player, but he is an algorithmician as well. That's why he instantly spotted four common letters in two words on the sign above — if we permute the letters "R", "E", "G", "O" from the first word, we can obtain the letters "O", "G", "R", "E". Egor got inspired by the sign and right away he came up with a problem about permutations.You are given a permutation of length n. You have to split it into some non-empty subsequences so that each element of the permutation belongs to exactly one subsequence. Each subsequence must be monotonic — that is, either increasing or decreasing.Sequence is called to be a subsequence if it can be derived from permutation by deleting some (possibly none) elements without changing the order of the remaining elements.The number of subsequences should be small enough — let f(n) be the minimum integer k such that every permutation of length n can be partitioned into at most k monotonic subsequences.You need to split the permutation into at most f(n) monotonic subsequences. | Input: ['3', '4', '4 3 1 2', '6', '4 5 6 1 3 2', '10', '1 2 3 4 5 6 7 8 9 10', ''] Output:['2', '3 4 3 1', '1 2', '3', '2 4 1', '2 5 6', '2 3 2', '1', '10 1 2 3 4 5 6 7 8 9 10', ''] | [
2
] |
Makoto has a big blackboard with a positive integer n written on it. He will perform the following action exactly k times:Suppose the number currently written on the blackboard is v. He will randomly pick one of the divisors of v (possibly 1 and v) and replace v with this divisor. As Makoto uses his famous random number generator (RNG) and as he always uses 58 as his generator seed, each divisor is guaranteed to be chosen with equal probability.He now wonders what is the expected value of the number written on the blackboard after k steps.It can be shown that this value can be represented as \frac{P}{Q} where P and Q are coprime integers and Q \not\equiv 0 \pmod{10^9+7}. Print the value of P \cdot Q^{-1} modulo 10^9+7. | Input: ['6 1', ''] Output:['3', ''] | [
3
] |
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it? | Input: ['7', ')())', ')', '((', '((', '(', ')', ')', ''] Output:['2', ''] | [
2
] |
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero: Petr called his car dealer, who instructed him to rotate the lock's wheel exactly n times. The i-th rotation should be a_i degrees, either clockwise or counterclockwise, and after all n rotations the pointer should again point at zero.This confused Petr a little bit as he isn't sure which rotations should be done clockwise and which should be done counterclockwise. As there are many possible ways of rotating the lock, help him and find out whether there exists at least one, such that after all n rotations the pointer will point at zero again. | Input: ['3', '10', '20', '30', ''] Output:['YES', ''] | [
0
] |
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or Hearts — H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card. | Input: ['AS', '2H 4C TH JH AD', ''] Output:['YES', ''] | [
0
] |
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.Calculate the expected total number of inversions in the resulting valid permutation.It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q!=0. Report the value of P \cdot Q^{-1} \pmod {998244353}. | Input: ['3', '3 -1 -1', ''] Output:['499122179', ''] | [
3
] |
Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are p players doing penalty shoot-outs. Winner is the one who scores the most. In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability.They have just finished the game and now are waiting for the result. But there's a tiny problem! The judges have lost the paper of scores! Fortunately they have calculated sum of the scores before they get lost and also for some of the players they have remembered a lower bound on how much they scored. However, the information about the bounds is private, so Hasan only got to know his bound.According to the available data, he knows that his score is at least r and sum of the scores is s.Thus the final state of the game can be represented in form of sequence of p integers a_1, a_2, ..., a_p (0 <= a_i) — player's scores. Hasan is player number 1, so a_1 >= r. Also a_1 + a_2 + ... + a_p = s. Two states are considered different if there exists some position i such that the value of a_i differs in these states. Once again, Hasan doesn't know the exact scores (he doesn't know his exact score as well). So he considers each of the final states to be equally probable to achieve.Help Hasan find the probability of him winning.It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q!=0, P <= Q. Report the value of P \cdot Q^{-1} \pmod {998244353}. | Input: ['2 6 3'] Output:['124780545'] | [
3
] |
You are given an angle \text{ang}. The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = \text{ang} or report that there is no such n-gon. If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed 998244353. | Input: ['4', '54', '50', '2', '178', ''] Output:['10', '18', '90', '180', ''] | [
0
] |
You are given a string s of length n consisting only of lowercase Latin letters.A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one).It is guaranteed that there is at least two different characters in s.Note that you can remove the whole string and it is correct. Also note that you should remove at least one character.Since the answer can be rather large (not very large though) print it modulo 998244353.If you are Python programmer, consider using PyPy instead of Python when you submit your code. | Input: ['4', 'abaa', ''] Output:['6', ''] | [
3
] |
You are given a range of positive integers from l to r.Find such a pair of integers (x, y) that l <= x, y <= r, x!=y and x divides y.If there are multiple answers, print any of them.You are also asked to answer T independent queries. | Input: ['3', '1 10', '3 14', '1 10', ''] Output:['1 7', '3 9', '5 10', ''] | [
2,
3
] |
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph. | Input: ['3 2', '1 3 3', '2 3 5', '2 1 1', ''] Output:['5', ''] | [
2
] |
A positive integer x is called a power of two if it can be represented as x = 2^y, where y is a non-negative integer. So, the powers of two are 1, 2, 4, 8, 16, ....You are given two positive integers n and k. Your task is to represent n as the sum of exactly k powers of two. | Input: ['9 4', ''] Output:['YES', '1 2 2 4 ', ''] | [
2
] |
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative integer a_i to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of a to help out students like Mishka: a was sorted in non-decreasing order (a_1 <= a_2 <= ... <= a_n); n was even; the following sequence b, consisting of \frac n 2 elements, was formed and given out to students: b_i = a_i + a_{n - i + 1}. Professor also mentioned that any sequence a, which produces sequence b with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence a of non-negative integers, which produces sequence b with the presented technique. It is guaranteed that there exists at least one correct sequence a, which produces the given sequence b. | Input: ['4', '5 6', ''] Output:['2 3 3 3', ''] | [
2
] |
You are given a string s consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.You have to answer t independent queries. | Input: ['3', 'aa', 'abacaba', 'xdd', ''] Output:['-1', 'abaacba', 'xdd'] | [
2
] |
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice).Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls Mishka makes.Mishka doesn't really care about the number of rolls, so he just wants to know any number of rolls he can make to be able to get exactly x points for them. Mishka is very lucky, so if the probability to get x points with chosen number of rolls is non-zero, he will be able to roll the dice in such a way. Your task is to print this number. It is guaranteed that at least one answer exists.Mishka is also very curious about different number of points to score so you have to answer t independent queries. | Input: ['4', '2', '13', '37', '100', ''] Output:['1', '3', '8', '27'] | [
3
] |
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.If there are multiple correct answers, print any of them. | Input: ['4 2', '1 2', '2 3', ''] Output:['2', '4 2', ''] | [
2
] |
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.Vova can only use 2 * 1 bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)? | Input: ['5', '2 1 1 2 5', ''] Output:['YES', ''] | [
2,
3
] |
Integer factorisation is hard. The RSA Factoring Challenge offered 100\,000 for factoring RSA-1024, a 1024-bit long product of two prime numbers. To this date, nobody was able to claim the prize. We want you to factorise a 1024-bit number.Since your programming language of choice might not offer facilities for handling large integers, we will provide you with a very simple calculator. To use this calculator, you can print queries on the standard output and retrieve the results from the standard input. The operations are as follows: + x y where x and y are integers between 0 and n-1. Returns (x+y) \bmod n. - x y where x and y are integers between 0 and n-1. Returns (x-y) \bmod n. * x y where x and y are integers between 0 and n-1. Returns (x \cdot y) \bmod n. / x y where x and y are integers between 0 and n-1 and y is coprime with n. Returns (x \cdot y^{-1}) \bmod n where y^{-1} is multiplicative inverse of y modulo n. If y is not coprime with n, then -1 is returned instead. sqrt x where x is integer between 0 and n-1 coprime with n. Returns y such that y^2 \bmod n = x. If there are multiple such integers, only one of them is returned. If there are none, -1 is returned instead. ^ x y where x and y are integers between 0 and n-1. Returns {x^y \bmod n}. Find the factorisation of n that is a product of between 2 and 10 distinct prime numbers, all of form 4x + 3 for some integer x.Because of technical issues, we restrict number of requests to 100. | Input: ['21717151711-115'] Output:['+ 12 16- 6 10* 8 15/ 5 4sqrt 16sqrt 5^ 6 12! 2 3 7'] | [
3
] |
Bob is a duck. He wants to get to Alice's nest, so that those two can duck! Duck is the ultimate animal! (Image courtesy of See Bang) The journey can be represented as a straight line, consisting of n segments. Bob is located to the left of the first segment, while Alice's nest is on the right of the last segment. Each segment has a length in meters, and also terrain type: grass, water or lava. Bob has three movement types: swimming, walking and flying. He can switch between them or change his direction at any point in time (even when he is located at a non-integer coordinate), and doing so doesn't require any extra time. Bob can swim only on the water, walk only on the grass and fly over any terrain. Flying one meter takes 1 second, swimming one meter takes 3 seconds, and finally walking one meter takes 5 seconds.Bob has a finite amount of energy, called stamina. Swimming and walking is relaxing for him, so he gains 1 stamina for every meter he walks or swims. On the other hand, flying is quite tiring, and he spends 1 stamina for every meter flown. Staying in place does not influence his stamina at all. Of course, his stamina can never become negative. Initially, his stamina is zero.What is the shortest possible time in which he can reach Alice's nest? | Input: ['1', '10', 'G', ''] Output:['30', ''] | [
2
] |
Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends.This morning, somebody anonymously sent Bob the following link: graph realization problem and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them. | Input: ['33 3 3'] Output:['3 '] | [
2,
3,
4
] |
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence p. For example, if n = 3, then p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence will be n \cdot n!.Let 1 <=q i <=q j <=q n \cdot n! be a pair of indices. We call the sequence (p_i, p_{i+1}, ..., p_{j-1}, p_j) a subarray of p. Its length is defined as the number of its elements, i.e., j - i + 1. Its sum is the sum of all its elements, i.e., \sum_{k=i}^j p_k. You are given n. Find the number of subarrays of p of length n having sum \frac{n(n+1)}{2}. Since this number may be large, output it modulo 998244353 (a prime number). | Input: ['3', ''] Output:['9', ''] | [
3
] |
There are n people sitting in a circle, numbered from 1 to n in the order in which they are seated. That is, for all i from 1 to n-1, the people with id i and i+1 are adjacent. People with id n and 1 are adjacent as well.The person with id 1 initially has a ball. He picks a positive integer k at most n, and passes the ball to his k-th neighbour in the direction of increasing ids, that person passes the ball to his k-th neighbour in the same direction, and so on until the person with the id 1 gets the ball back. When he gets it back, people do not pass the ball any more.For instance, if n = 6 and k = 4, the ball is passed in order [1, 5, 3, 1]. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be 1 + 5 + 3 = 9.Find and report the set of possible fun values for all choices of positive integer k. It can be shown that under the constraints of the problem, the ball always gets back to the 1-st player after finitely many steps, and there are no more than 10^5 possible fun values for given n. | Input: ['6', ''] Output:['1 5 9 21', ''] | [
3
] |
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point T, which coordinates to be found out.Bob travelled around the world and collected clues of the treasure location at n obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?As everyone knows, the world is a two-dimensional plane. The i-th obelisk is at integer coordinates (x_i, y_i). The j-th clue consists of 2 integers (a_j, b_j) and belongs to the obelisk p_j, where p is some (unknown) permutation on n elements. It means that the treasure is located at T=(x_{p_j} + a_j, y_{p_j} + b_j). This point T is the same for all clues.In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.Note that you don't need to find the permutation. Permutations are used only in order to explain the problem. | Input: ['2', '2 5', '-6 4', '7 -2', '-1 -3', ''] Output:['1 2', ''] | [
0,
2
] |
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments.In Bob's opinion, a Christmas Tree will be beautiful if: the number of blue ornaments used is greater by exactly 1 than the number of yellow ornaments, and the number of red ornaments used is greater by exactly 1 than the number of blue ornaments. That is, if they have 8 yellow ornaments, 13 blue ornaments and 9 red ornaments, we can choose 4 yellow, 5 blue and 6 red ornaments (5=4+1 and 6=5+1).Alice wants to choose as many ornaments as possible, but she also wants the Christmas Tree to be beautiful according to Bob's opinion.In the example two paragraphs above, we would choose 7 yellow, 8 blue and 9 red ornaments. If we do it, we will use 7+8+9=24 ornaments. That is the maximum number.Since Alice and Bob are busy with preparing food to the New Year's Eve, they are asking you to find out the maximum number of ornaments that can be used in their beautiful Christmas Tree! It is guaranteed that it is possible to choose at least 6 (1+2+3=6) ornaments. | Input: ['8 13 9', ''] Output:['24'] | [
0,
3
] |
A conglomerate consists of n companies. To make managing easier, their owners have decided to merge all companies into one. By law, it is only possible to merge two companies, so the owners plan to select two companies, merge them into one, and continue doing so until there is only one company left.But anti-monopoly service forbids to merge companies if they suspect unfriendly absorption. The criterion they use is the difference in maximum salaries between two companies. Merging is allowed only if the maximum salaries are equal.To fulfill the anti-monopoly requirements, the owners can change salaries in their companies before merging. But the labor union insists on two conditions: it is only allowed to increase salaries, moreover all the employees in one company must get the same increase.Sure enough, the owners want to minimize the total increase of all salaries in all companies. Help them find the minimal possible increase that will allow them to merge companies into one. | Input: ['3', '2 4 3', '2 2 1', '3 1 1 1', ''] Output:['13', ''] | [
2
] |
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings. Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below: A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process. A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive. A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('' code 36). A word does not start with a digit. Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.During the minification process words are renamed in a systematic fashion using the following algorithm: Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on. The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules. | Input: ['16', 'fun while return var { } ( ) , ; > = + ++ - --', '9', 'fun fib(num) { # compute fibs', ' var return_value = 1, prev = 0, temp;', ' while (num > 0) {', ' temp = return_value; return_value = return_value + prev;', ' prev = temp;', ' num--;', ' }', ' return return_value;', '}', ''] Output:['fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}', ''] | [
2
] |
Berland State University invites people from all over the world as guest students. You can come to the capital of Berland and study with the best teachers in the country.Berland State University works every day of the week, but classes for guest students are held on the following schedule. You know the sequence of seven integers a_1, a_2, ..., a_7 (a_i = 0 or a_i = 1): a_1=1 if and only if there are classes for guest students on Sundays; a_2=1 if and only if there are classes for guest students on Mondays; ... a_7=1 if and only if there are classes for guest students on Saturdays. The classes for guest students are held in at least one day of a week.You want to visit the capital of Berland and spend the minimum number of days in it to study k days as a guest student in Berland State University. Write a program to find the length of the shortest continuous period of days to stay in the capital to study exactly k days as a guest student. | Input: ['3', '2', '0 1 0 0 0 0 0', '100000000', '1 0 0 0 1 0 1', '1', '1 0 0 0 0 0 0', ''] Output:['8', '233333332', '1', ''] | [
3
] |
You are given a positive integer n.Find a sequence of fractions \frac{a_i}{b_i}, i = 1 ... k (where a_i and b_i are positive integers) for some k such that: \begin{cases} \text{b_i divides n, 1 < b_i < n for i = 1 ... k} \\ \text{1 <= a_i < b_i for i = 1 ... k} \\ \text{\sum\limits_{i=1}^k \frac{a_i}{b_i} = 1 - \frac{1}{n}} \end{cases} | Input: ['2', ''] Output:['NO', ''] | [
3
] |
You're given a tree consisting of n nodes. Every node u has a weight a_u. You want to choose an integer k (1 <= k <= n) and then choose k connected components of nodes that don't overlap (i.e every node is in at most 1 component). Let the set of nodes you chose be s. You want to maximize:\frac{\sum\limits_{u \in s} a_u}{k}In other words, you want to maximize the sum of weights of nodes in s divided by the number of connected components you chose. Also, if there are several solutions, you want to maximize k.Note that adjacent nodes can belong to different components. Refer to the third sample. | Input: ['3', '1 2 3', '1 2', '1 3', ''] Output:['6 1'] | [
2,
3
] |
You're given an array a of length n. You can perform the following operations on it: choose an index i (1 <= i <= n), an integer x (0 <= x <= 10^6), and replace a_j with a_j+x for all (1 <= j <= i), which means add x to all the elements in the prefix ending at i. choose an index i (1 <= i <= n), an integer x (1 <= x <= 10^6), and replace a_j with a_j \% x for all (1 <= j <= i), which means replace every element in the prefix ending at i with the remainder after dividing it by x. Can you make the array strictly increasing in no more than n+1 operations? | Input: ['31 2 3'] Output:['0'] | [
2,
3
] |
Given an integer x, find 2 integers a and b such that: 1 <= a,b <= x b divides a (a is divisible by b). a \cdot b>x. \frac{a}{b}<x. | Input: ['10'] Output:['6 3'] | [
0
] |
Berland forest was planted several decades ago in a formation of an infinite grid with a single tree in every cell. Now the trees are grown up and they form a pretty dense structure.So dense, actually, that the fire became a real danger for the forest. This season had been abnormally hot in Berland and some trees got caught on fire! The second fire started is considered the second 0. Every second fire lit up all intact neightbouring trees to every currently burning tree. The tree is neighbouring if it occupies adjacent by side or by corner cell. Luckily, after t seconds Berland fire department finally reached the location of fire and instantaneously extinguished it all.Now they want to calculate the destructive power of the fire. Let val_{x, y} be the second the tree in cell (x, y) got caught on fire. The destructive power is the sum of val_{x, y} over all (x, y) of burnt trees.Clearly, all the workers of fire department are firefighters, not programmers, thus they asked you to help them calculate the destructive power of the fire.The result can be rather big, so print it modulo 998244353. | Input: ['1 2', '10 11', ''] Output:['40'] | [
3
] |
Vasya owns three strings s , a and b, each of them consists only of first k Latin letters.Let a template be such a string of length k that each of the first k Latin letters appears in it exactly once (thus there are k! distinct templates). Application of template p to the string s is the replacement of each character in string s with p_i, i is the index of this letter in the alphabet. For example, applying template "bdca" to a string "aabccd" yields string "bbdcca".Vasya wants to know if there exists such a template which yields a string lexicographically greater than or equal to string a and lexicographically less than or equal to string b after applying it to s.If there exist multiple suitable templates, print any of them.String a is lexicographically less than string b if there is some i (1 <= i <= n) that a_i < b_i and for any j (1 <= j < i) a_j = b_j.You are required to answer t testcases independently. | Input: ['24bbcbaadaaada3abcbbbbbb'] Output:['YESbadcNO'] | [
2
] |
The Squareland national forest is divided into equal 1 * 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner.Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C in the forest. Initially, all plots in the forest (including the plots A, B, C) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots A, B, C from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side. For example, A=(0,0), B=(1,1), C=(2,2). The minimal number of plots to be cleared is 5. One of the ways to do it is shown with the gray color. Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees. | Input: ['0 0', '1 1', '2 2', ''] Output:['5', '0 0', '1 0', '1 1', '1 2', '2 2', ''] | [
3
] |
Vasya likes to solve equations. Today he wants to solve (x~\mathrm{div}~k) \cdot (x \bmod k) = n, where \mathrm{div} and \mathrm{mod} stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, k and n are positive integer parameters, and x is a positive integer unknown. If there are several solutions, Vasya wants to find the smallest possible x. Can you help him? | Input: ['6 3', ''] Output:['11', ''] | [
3
] |
The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. | Input: ['3 34 3 5'] Output:['3'] | [
2
] |
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening. It was decided that elevator, when it is not used, will stay on the x-th floor, but x hasn't been chosen yet. When a person needs to get from floor a to floor b, elevator follows the simple algorithm: Moves from the x-th floor (initially it stays on the x-th floor) to the a-th and takes the passenger. Moves from the a-th floor to the b-th floor and lets out the passenger (if a equals b, elevator just opens and closes the doors, but still comes to the floor from the x-th floor). Moves from the b-th floor back to the x-th. The elevator never transposes more than one person and always goes back to the floor x before transposing a next passenger. The elevator spends one unit of electricity to move between neighboring floors. So moving from the a-th floor to the b-th floor requires |a - b| units of electricity.Your task is to help Nut to find the minimum number of electricity units, that it would be enough for one day, by choosing an optimal the x-th floor. Don't forget than elevator initially stays on the x-th floor. | Input: ['30 2 1'] Output:['16'] | [
0
] |
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a!=b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. | Input: ['2 4', 'aa', 'bb', ''] Output:['6', ''] | [
2
] |
You are given array a of length n. You can choose one segment [l, r] (1 <= l <= r <= n) and integer value k (positive, negative or even zero) and change a_l, a_{l + 1}, ..., a_r by k each (i.e. a_i := a_i + k for each l <= i <= r).What is the maximum possible number of elements with value c that can be obtained after one such operation? | Input: ['6 9', '9 9 9 9 9 9', ''] Output:['6', ''] | [
2,
4
] |
A multi-subject competition is coming! The competition has m different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students. He has n candidates. For the i-th person he knows subject s_i the candidate specializes in and r_i — a skill level in his specialization (this level can be negative!). The rules of the competition require each delegation to choose some subset of subjects they will participate in. The only restriction is that the number of students from the team participating in each of the chosen subjects should be the same.Alex decided that each candidate would participate only in the subject he specializes in. Now Alex wonders whom he has to choose to maximize the total sum of skill levels of all delegates, or just skip the competition this year if every valid non-empty delegation has negative sum.(Of course, Alex doesn't have any spare money so each delegate he chooses must participate in the competition). | Input: ['6 3', '2 6', '3 6', '2 5', '3 5', '1 9', '3 1', ''] Output:['22', ''] | [
2
] |
Vova has won n trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap. | Input: ['10', 'GGGSGGGSGG', ''] Output:['7', ''] | [
2
] |
Vasya is reading a e-book. The file of the book consists of n pages, numbered from 1 to n. The screen is currently displaying the contents of page x, and Vasya wants to read the page y. There are two buttons on the book which allow Vasya to scroll d pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of 10 pages, and d = 3, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.Help Vasya to calculate the minimum number of times he needs to press a button to move to page y. | Input: ['3', '10 4 5 2', '5 1 3 4', '20 4 19 3', ''] Output:['4', '-1', '5', ''] | [
3
] |
Chouti thought about his very first days in competitive programming. When he had just learned to write merge sort, he thought that the merge sort is too slow, so he restricted the maximum depth of recursion and modified the merge sort to the following: Chouti found his idea dumb since obviously, this "merge sort" sometimes cannot sort the array correctly. However, Chouti is now starting to think of how good this "merge sort" is. Particularly, Chouti wants to know for a random permutation a of 1, 2, ..., n the expected number of inversions after calling MergeSort(a, 1, n, k).It can be proved that the expected number is rational. For the given prime q, suppose the answer can be denoted by \frac{u}{d} where gcd(u,d)=1, you need to output an integer r satisfying 0 <= r<q and rd \equiv u \pmod q. It can be proved that such r exists and is unique. | Input: ['3 1 998244353'] Output:['499122178'] | [
3
] |
Chouti is working on a strange math problem.There was a sequence of n positive integers x_1, x_2, ..., x_n, where n is even. The sequence was very special, namely for every integer t from 1 to n, x_1+x_2+...+x_t is a square of some integer number (that is, a perfect square).Somehow, the numbers with odd indexes turned to be missing, so he is only aware of numbers on even positions, i.e. x_2, x_4, x_6, ..., x_n. The task for him is to restore the original sequence. Again, it's your turn to help him.The problem setter might make mistakes, so there can be no possible sequence at all. If there are several possible sequences, you can output any. | Input: ['65 11 44'] Output:['Yes4 5 16 11 64 44'] | [
2,
3,
4
] |
On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard.There are n bricks lined in a row on the ground. Chouti has got m paint buckets of different colors at hand, so he painted each brick in one of those m colors.Having finished painting all bricks, Chouti was satisfied. He stood back and decided to find something fun with these bricks. After some counting, he found there are k bricks with a color different from the color of the brick on its left (the first brick is not counted, for sure).So as usual, he needs your help in counting how many ways could he paint the bricks. Two ways of painting bricks are different if there is at least one brick painted in different colors in these two ways. Because the answer might be quite big, you only need to output the number of ways modulo 998\,244\,353. | Input: ['3 3 0', ''] Output:['3', ''] | [
3
] |
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games.He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operation as many times as the player want (possibly zero): choose a positive integer x that x<n and x is not a divisor of n, then subtract x from n. The goal of the player is to minimize the value of n in the end.Soon, Chouti found the game trivial. Can you also beat the game? | Input: ['8', ''] Output:['1', ''] | [
3
] |
Recently, Olya received a magical square with the size of 2^n* 2^n.It seems to her sister that one square is boring. Therefore, she asked Olya to perform exactly k splitting operations.A Splitting operation is an operation during which Olya takes a square with side a and cuts it into 4 equal squares with side \dfrac{a}{2}. If the side of the square is equal to 1, then it is impossible to apply a splitting operation to it (see examples for better understanding).Olya is happy to fulfill her sister's request, but she also wants the condition of Olya's happiness to be satisfied after all operations.The condition of Olya's happiness will be satisfied if the following statement is fulfilled:Let the length of the side of the lower left square be equal to a, then the length of the side of the right upper square should also be equal to a. There should also be a path between them that consists only of squares with the side of length a. All consecutive squares on a path should have a common side.Obviously, as long as we have one square, these conditions are met. So Olya is ready to fulfill her sister's request only under the condition that she is satisfied too. Tell her: is it possible to perform exactly k splitting operations in a certain order so that the condition of Olya's happiness is satisfied? If it is possible, tell also the size of the side of squares of which the path from the lower left square to the upper right one will consist. | Input: ['3', '1 1', '2 2', '2 12', ''] Output:['YES 0', 'YES 1', 'NO', ''] | [
3
] |
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.Recently, she was presented with an array a of the size of 10^9 elements that is filled as follows: a_1 = -1 a_2 = 2 a_3 = -3 a_4 = 4 a_5 = -5 And so on ... That is, the value of the i-th element of the array a is calculated using the formula a_i = i \cdot (-1)^i.She immediately came up with q queries on this array. Each query is described with two numbers: l and r. The answer to a query is the sum of all the elements of the array at positions from l to r inclusive.Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.Help her find the answers! | Input: ['5', '1 3', '2 5', '5 5', '4 4', '2 3', ''] Output:['-2', '-2', '-5', '4', '-1', ''] | [
3
] |
Petya is having a party soon, and he has decided to invite his n friends.He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends. | Input: ['3 5', ''] Output:['10', ''] | [
3
] |
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that: number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems; the total number of problems in all the contests should be maximized. Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests. | Input: ['18', '2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10', ''] Output:['14', ''] | [
2
] |
You are given an array s consisting of n integers.You have to find any array t of length k such that you can cut out maximum number of copies of array t from array s.Cutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find such element in s, then you cannot cut out one more copy of t. The both arrays can contain duplicate elements.For example, if s = [1, 2, 3, 2, 4, 3, 1] and k = 3 then one of the possible answers is t = [1, 2, 3]. This array t can be cut out 2 times. To cut out the first copy of t you can use the elements [1, \underline{\textbf{2}}, 3, 2, 4, \underline{\textbf{3}}, \underline{\textbf{1}}] (use the highlighted elements). After cutting out the first copy of t the array s can look like [1, 3, 2, 4]. To cut out the second copy of t you can use the elements [\underline{\textbf{1}}, \underline{\textbf{3}}, \underline{\textbf{2}}, 4]. After cutting out the second copy of t the array s will be [4]. Your task is to find such array t that you can cut out the copy of t from s maximum number of times. If there are multiple answers, you may choose any of them. | Input: ['7 3', '1 2 3 2 4 3 1', ''] Output:['1 2 3 ', ''] | [
4
] |
There is a house with n flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of n integer numbers a_1, a_2, ..., a_n, where a_i = 1 if in the i-th flat the light is on and a_i = 0 otherwise.Vova thinks that people in the i-th flats are disturbed and cannot sleep if and only if 1 < i < n and a_{i - 1} = a_{i + 1} = 1 and a_i = 0.Vova is concerned by the following question: what is the minimum number k such that if people from exactly k pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number k. | Input: ['10', '1 1 0 1 1 0 1 0 1 0', ''] Output:['2', ''] | [
2
] |
A frog is currently at the point 0 on a coordinate axis Ox. It jumps by the following algorithm: the first jump is a units to the right, the second jump is b units to the left, the third jump is a units to the right, the fourth jump is b units to the left, and so on.Formally: if the frog has jumped an even number of times (before the current jump), it jumps from its current position x to position x+a; otherwise it jumps from its current position x to position x-b. Your task is to calculate the position of the frog after k jumps.But... One more thing. You are watching t different frogs so you have to answer t independent queries. | Input: ['6', '5 2 3', '100 1 4', '1 10 5', '1000000000 1 6', '1 1 1000000000', '1 1 999999999', ''] Output:['8', '198', '-17', '2999999997', '0', '1', ''] | [
3
] |
Vova has taken his summer practice this year and now he should write a report on how it went.Vova has already drawn all the tables and wrote down all the formulas. Moreover, he has already decided that the report will consist of exactly n pages and the i-th page will include x_i tables and y_i formulas. The pages are numbered from 1 to n.Vova fills the pages one after another, he can't go filling page i + 1 before finishing page i and he can't skip pages. However, if he draws strictly more than k tables in a row or writes strictly more than k formulas in a row then he will get bored. Vova wants to rearrange tables and formulas in each page in such a way that he doesn't get bored in the process. Vova can't move some table or some formula to another page.Note that the count doesn't reset on the start of the new page. For example, if the page ends with 3 tables and the next page starts with 5 tables, then it's counted as 8 tables in a row.Help Vova to determine if he can rearrange tables and formulas on each page in such a way that there is no more than k tables in a row and no more than k formulas in a row. | Input: ['2 2', '5 5', '2 2', ''] Output:['YES', ''] | [
2
] |
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i. You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.Your goal is to erase the edges in such a way that the number of good vertices is maximized. | Input: ['3 3 2', '1 2 1', '3 2 1', '1 3 3', ''] Output:['2', '1 2 '] | [
2
] |
Try guessing the statement from this picture: You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a \cdot b = d. | Input: ['7', '69', '0', '1', '4', '5', '999', '1000', ''] Output:['Y 67.985071301 1.014928699', 'Y 0.000000000 0.000000000', 'N', 'Y 2.000000000 2.000000000', 'Y 3.618033989 1.381966011', 'Y 997.998996990 1.001003010', 'Y 998.998997995 1.001002005', ''] | [
3,
4
] |
You are given an integer number n. The following algorithm is applied to it: if n = 0, then end algorithm; find the smallest prime divisor d of n; subtract d from n and go to step 1. Determine the number of subtrations the algorithm will make. | Input: ['5', ''] Output:['1', ''] | [
3
] |
You are given a string s consisting of n lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String s = s_1 s_2 ... s_n is lexicographically smaller than string t = t_1 t_2 ... t_m if n < m and s_1 = t_1, s_2 = t_2, ..., s_n = t_n or there exists a number p such that p <= min(n, m) and s_1 = t_1, s_2 = t_2, ..., s_{p-1} = t_{p-1} and s_p < t_p.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | Input: ['3', 'aaa', ''] Output:['aa', ''] | [
2
] |
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)...Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time.The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win.Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited.Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. | Input: ['42 3'] Output:['White'] | [
3
] |
You are given an undirected unweighted tree consisting of n vertices.An undirected tree is a connected undirected graph with n - 1 edges.Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1).It is guaranteed that it is possible to choose such pairs for the given tree.Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths.It is guaranteed that the answer with at least two common vertices exists for the given tree.The length of the path is the number of edges in it.The simple path is the path that visits each vertex at most once. | Input: ['71 41 51 62 32 44 7'] Output:['3 67 5'] | [
2
] |
You are given two integers l and r (l <= r). Your task is to calculate the sum of numbers from l to r (including l and r) such that each number contains at most k different digits, and print this sum modulo 998244353.For example, if k = 1 then you have to calculate all numbers from l to r such that each number is formed using only one digit. For l = 10, r = 50 the answer is 11 + 22 + 33 + 44 = 110. | Input: ['10 50 2'] Output:['1230'] | [
3
] |
XXI Berland Annual Fair is coming really soon! Traditionally fair consists of n booths, arranged in a circle. The booths are numbered 1 through n clockwise with n being adjacent to 1. The i-th booths sells some candies for the price of a_i burles per item. Each booth has an unlimited supply of candies.Polycarp has decided to spend at most T burles at the fair. However, he has some plan in mind for his path across the booths: at first, he visits booth number 1; if he has enough burles to buy exactly one candy from the current booth, then he buys it immediately; then he proceeds to the next booth in the clockwise order (regardless of if he bought a candy or not). Polycarp's money is finite, thus the process will end once he can no longer buy candy at any booth.Calculate the number of candies Polycarp will buy. | Input: ['3 385 2 5'] Output:['10'] | [
0,
2,
4
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.