question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
Ujan needs some rest from cleaning, so he started playing with infinite sequences. He has two integers n and k. He creates an infinite sequence s by repeating the following steps. Find k smallest distinct positive integers that are not in s. Let's call them u_{1}, u_{2}, ..., u_{k} from the smallest to the largest. Append u_{1}, u_{2}, ..., u_{k} and \sum_{i=1}^{k} u_{i} to s in this order. Go back to the first step. Ujan will stop procrastinating when he writes the number n in the sequence s. Help him find the index of n in s. In other words, find the integer x such that s_{x} = n. It's possible to prove that all positive integers are included in s only once.
Input: ['2', '10 2', '40 5', ''] Output:['11', '12', '']
[ 3 ]
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles with numbers i and j, such that |j - i| is a divisor of n greater than 1, they have the same color. Formally, the colors of two tiles with numbers i and j should be the same if |i-j| > 1 and n \bmod |i-j| = 0 (where x \bmod y is the remainder when dividing x by y).Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic?
Input: ['4', ''] Output:['2', '']
[ 3 ]
There are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 <=q i <=q n) will decide to go for boiled water at minute t_i.Tank with a boiled water is located to the left of the 1-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly p minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the i-th seat wants to go for a boiled water, he will first take a look on all seats from 1 to i - 1. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than i are busy, he will go to the tank.There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment.Your goal is to find for each passenger, when he will receive the boiled water for his noodles.
Input: ['5 314', '0 310 942 628 0', ''] Output:['314 628 1256 942 1570 ', '']
[ 2 ]
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input: ['2 3', ''] Output:['8', '']
[ 3 ]
Adilbek has to water his garden. He is going to do it with the help of a complex watering system: he only has to deliver water to it, and the mechanisms will do all the remaining job.The watering system consumes one liter of water per minute (if there is no water, it is not working). It can hold no more than c liters. Adilbek has already poured c_0 liters of water into the system. He is going to start watering the garden right now and water it for m minutes, and the watering system should contain at least one liter of water at the beginning of the i-th minute (for every i from 0 to m - 1).Now Adilbek wonders what he will do if the watering system runs out of water. He called n his friends and asked them if they are going to bring some water. The i-th friend answered that he can bring no more than a_i liters of water; he will arrive at the beginning of the t_i-th minute and pour all the water he has into the system (if the system cannot hold such amount of water, the excess water is poured out); and then he will ask Adilbek to pay b_i dollars for each liter of water he has brought. You may assume that if a friend arrives at the beginning of the t_i-th minute and the system runs out of water at the beginning of the same minute, the friend pours his water fast enough so that the system does not stop working.Of course, Adilbek does not want to pay his friends, but he has to water the garden. So he has to tell his friends how much water should they bring. Formally, Adilbek wants to choose n integers k_1, k_2, ..., k_n in such a way that: if each friend i brings exactly k_i liters of water, then the watering system works during the whole time required to water the garden; the sum \sum\limits_{i = 1}^{n} k_i b_i is minimum possible. Help Adilbek to determine the minimum amount he has to pay his friends or determine that Adilbek not able to water the garden for m minutes.You have to answer q independent queries.
Input: ['4', '1 5 4 2', '2 4 2', '0 4 5 4', '2 5 3 1', '1 2 4', '3 1 3', '2 3 5 1', '2 1 1', '1 4 3', ''] Output:['6', '0', '-1', '4', '']
[ 2 ]
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5); t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4); t = AAAAA (all letters belong to palindrome t_1 ... t_5); You are given a string s of length n, consisting of only letters A and B.You have to calculate the number of good substrings of string s.
Input: ['5', 'AABBB', ''] Output:['6', '']
[ 4 ]
You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height h, and there is a moving platform on each height x from 1 to h.Each platform is either hidden inside the cliff or moved out. At first, there are n moved out platforms on heights p_1, p_2, ..., p_n. The platform on height h is moved out (and the character is initially standing there).If you character is standing on some moved out platform on height x, then he can pull a special lever, which switches the state of two platforms: on height x and x - 1. In other words, the platform you are currently standing on will hide in the cliff and the platform one unit below will change it state: it will hide if it was moved out or move out if it was hidden. In the second case, you will safely land on it. Note that this is the only way to move from one platform to another.Your character is quite fragile, so it can safely fall from the height no more than 2. In other words falling from the platform x to platform x - 2 is okay, but falling from x to x - 3 (or lower) is certain death. Sometimes it's not possible to come down from the cliff, but you can always buy (for donate currency) several magic crystals. Each magic crystal can be used to change the state of any single platform (except platform on height h, which is unaffected by the crystals). After being used, the crystal disappears.What is the minimum number of magic crystal you need to buy to safely land on the 0 ground level?
Input: ['4', '3 2', '3 1', '8 6', '8 7 6 5 3 2', '9 6', '9 8 5 4 3 1', '1 1', '1', ''] Output:['0', '1', '2', '0', '']
[ 2, 3 ]
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point x = 0 is where these parts meet.The right part of the corridor is filled with n monsters β€” for each monster, its initial coordinate x_i is given (and since all monsters are in the right part, every x_i is positive).The left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes less than or equal to 0), it gets instantly killed by a trap.The main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point c. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be y, then: if c = y, then the monster is killed; if y < c, then the monster is pushed r units to the left, so its current coordinate becomes y - r; if y > c, then the monster is pushed r units to the right, so its current coordinate becomes y + r. Ivan is going to kill the monsters as follows: choose some integer point d and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on.What is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he chooses the impact point optimally.You have to answer q independent queries.
Input: ['2', '3 2', '1 3 5', '4 1', '5 2 3 5', ''] Output:['2', '2', '']
[ 2 ]
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y?Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime numbers starts with 2, 3, 5, 7, 11.Your program should solve t independent test cases.
Input: ['4', '100 98', '42 32', '1000000000000000000 1', '41 40', ''] Output:['YES', 'YES', 'YES', 'NO', '']
[ 3 ]
There are n friends living on a circular street. The friends and their houses are numbered clockwise from 0 to n-1.Initially person i has a_i stones. The friends want to make the distribution of stones among them perfectly balanced: everyone should possess the same number of stones.The only way to change the distribution of stones is by conducting meetings. During a meeting, people from exactly k consecutive houses (remember that the street is circular) gather at the same place and bring all their stones with them. All brought stones may be redistributed among people attending the meeting arbitrarily. The total number of stones they possess before the meeting and after the meeting must stay the same. After the meeting, everyone returns to their home.Find a way to make the distribution of stones perfectly balanced conducting as few meetings as possible.
Input: ['6 3', '2 6 1 10 3 2', ''] Output:['3', '2 7 3 4', '5 4 4 2', '1 4 4 4', '']
[ 2 ]
Recall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree.The depth of a vertex is the number of edges on the simple path from the vertex to the root. In particular, the depth of the root is 0.Let's call a binary search tree perfectly balanced if there doesn't exist a binary search tree with the same number of vertices that has a strictly smaller sum of depths of its vertices.Let's call a binary search tree with integer keys striped if both of the following conditions are satisfied for every vertex v: If v has a left subtree whose root is u, then the parity of the key of v is different from the parity of the key of u. If v has a right subtree whose root is w, then the parity of the key of v is the same as the parity of the key of w. You are given a single integer n. Find the number of perfectly balanced striped binary search trees with n vertices that have distinct integer keys between 1 and n, inclusive. Output this number modulo 998\,244\,353.
Input: ['4', ''] Output:['1', '']
[ 3 ]
Your favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of n tracks numbered from 1 to n. The playlist is automatic and cyclic: whenever track i finishes playing, track i+1 starts playing automatically; after track n goes track 1.For each track i, you have estimated its coolness a_i. The higher a_i is, the cooler track i is.Every morning, you choose a track. The playlist then starts playing from this track in its usual cyclic fashion. At any moment, you remember the maximum coolness x of already played tracks. Once you hear that a track with coolness strictly less than \frac{x}{2} (no rounding) starts playing, you turn off the music immediately to keep yourself in a good mood.For each track i, find out how many tracks you will listen to before turning off the music if you start your morning with track i, or determine that you will never turn the music off. Note that if you listen to the same track several times, every time must be counted.
Input: ['4', '11 5 2 7', ''] Output:['1 1 3 2', '']
[ 4 ]
This is a harder version of the problem. In this version, n <= 50\,000.There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.You'd like to remove all n points using a sequence of \frac{n}{2} snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if \min(x_a, x_b) <= x_c <= \max(x_a, x_b), \min(y_a, y_b) <= y_c <= \max(y_a, y_b), and \min(z_a, z_b) <= z_c <= \max(z_a, z_b). Note that the bounding box might be degenerate. Find a way to remove all points in \frac{n}{2} snaps.
Input: ['6', '3 1 0', '0 3 0', '2 2 0', '1 0 0', '1 3 0', '0 1 0', ''] Output:['3 6', '5 1', '2 4', '']
[ 2, 4 ]
This is an easier version of the problem. In this version, n <= 2000.There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.You'd like to remove all n points using a sequence of \frac{n}{2} snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if \min(x_a, x_b) <= x_c <= \max(x_a, x_b), \min(y_a, y_b) <= y_c <= \max(y_a, y_b), and \min(z_a, z_b) <= z_c <= \max(z_a, z_b). Note that the bounding box might be degenerate. Find a way to remove all points in \frac{n}{2} snaps.
Input: ['6', '3 1 0', '0 3 0', '2 2 0', '1 0 0', '1 3 0', '0 1 0', ''] Output:['3 6', '5 1', '2 4', '']
[ 2 ]
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced β€” their sum is equal to 0.Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.There are two conditions though: For each participant i, their modified rating change b_i must be integer, and as close to \frac{a_i}{2} as possible. It means that either b_i = \lfloor \frac{a_i}{2} \rfloor or b_i = \lceil \frac{a_i}{2} \rceil. In particular, if a_i is even, b_i = \frac{a_i}{2}. Here \lfloor x \rfloor denotes rounding down to the largest integer not greater than x, and \lceil x \rceil denotes rounding up to the smallest integer not smaller than x. The modified rating changes must be perfectly balanced β€” their sum must be equal to 0. Can you help with that?
Input: ['3', '10', '-5', '-5', ''] Output:['5', '-2', '-3', '']
[ 3 ]
Alice recently found some cactuses growing near her house! After several months, more and more cactuses appeared and soon they blocked the road. So Alice wants to clear them.A cactus is a connected undirected graph. No edge of this graph lies on more than one simple cycle. Let's call a sequence of different nodes of the graph x_1, x_2, ..., x_k a simple cycle, if k >=q 3 and all pairs of nodes x_1 and x_2, x_2 and x_3, ..., x_{k-1} and x_k, x_k and x_1 are connected with edges. Edges (x_1, x_2), (x_2, x_3), ..., (x_{k-1}, x_k), (x_k, x_1) lies on this simple cycle.There are so many cactuses, so it seems hard to destroy them. But Alice has magic. When she uses the magic, every node of the cactus will be removed independently with the probability \frac{1}{2}. When a node is removed, the edges connected to it are also removed.Now Alice wants to test her magic. She has picked a cactus with n nodes and m edges. Let X[S] (where S is a subset of the removed nodes) be the number of connected components in the remaining graph after removing nodes of set S. Before she uses magic, she wants to know the variance of random variable X, if all nodes of the graph have probability \frac{1}{2} to be removed and all n of these events are independent. By the definition the variance is equal to E[(X - E[X])^2], where E[X] is the expected value of X. Help her and calculate this value by modulo 10^9+7.Formally, let M = 10^9 + 7 (a prime number). It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, find such an integer x that 0 <= x < M and x \cdot q \equiv p \pmod{M}.
Input: ['3 3', '1 2', '2 3', '1 3', ''] Output:['984375007']
[ 3 ]
Alice is playing a game with her good friend, Marisa.There are n boxes arranged in a line, numbered with integers from 1 to n from left to right. Marisa will hide a doll in one of the boxes. Then Alice will have m chances to guess where the doll is. If Alice will correctly guess the number of box, where doll is now, she will win the game, otherwise, her friend will win the game.In order to win, Marisa will use some unfair tricks. After each time Alice guesses a box, she can move the doll to the neighboring box or just keep it at its place. Boxes i and i + 1 are neighboring for all 1 <=q i <=q n - 1. She can also use this trick once before the game starts.So, the game happens in this order: the game starts, Marisa makes the trick, Alice makes the first guess, Marisa makes the trick, Alice makes the second guess, Marisa makes the trick, ..., Alice makes m-th guess, Marisa makes the trick, the game ends.Alice has come up with a sequence a_1, a_2, ..., a_m. In the i-th guess, she will ask if the doll is in the box a_i. She wants to know the number of scenarios (x, y) (for all 1 <=q x, y <=q n), such that Marisa can win the game if she will put the doll at the x-th box at the beginning and at the end of the game, the doll will be at the y-th box. Help her and calculate this number.
Input: ['3 3', '2 2 2', ''] Output:['7']
[ 4 ]
Alice got a new doll these days. It can even walk!Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.More formally, there exist 4 directions, in which the doll can look: The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1); The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y); The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1); The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y). .Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 \to 2, 2 \to 3, 3 \to 4, 4 \to 1. Standing in one cell, the doll can make at most one turn right.Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input: ['3 3 2', '2 2', '2 1', ''] Output:['Yes']
[ 0, 2 ]
In order to do some research, n^2 labs are built on different heights of a mountain. Let's enumerate them with integers from 1 to n^2, such that the lab with the number 1 is at the lowest place, the lab with the number 2 is at the second-lowest place, ..., the lab with the number n^2 is at the highest place.To transport water between the labs, pipes are built between every pair of labs. A pipe can transport at most one unit of water at a time from the lab with the number u to the lab with the number v if u > v.Now the labs need to be divided into n groups, each group should contain exactly n labs. The labs from different groups can transport water to each other. The sum of units of water that can be sent from a group A to a group B is equal to the number of pairs of labs (u, v) such that the lab with the number u is from the group A, the lab with the number v is from the group B and u > v. Let's denote this value as f(A,B) (i.e. f(A,B) is the sum of units of water that can be sent from a group A to a group B).For example, if n=3 and there are 3 groups X, Y and Z: X = \{1, 5, 6\}, Y = \{2, 4, 9\} and Z = \{3, 7, 8\}. In this case, the values of f are equal to: f(X,Y)=4 because of 5 \rightarrow 2, 5 \rightarrow 4, 6 \rightarrow 2, 6 \rightarrow 4, f(X,Z)=2 because of 5 \rightarrow 3, 6 \rightarrow 3, f(Y,X)=5 because of 2 \rightarrow 1, 4 \rightarrow 1, 9 \rightarrow 1, 9 \rightarrow 5, 9 \rightarrow 6, f(Y,Z)=4 because of 4 \rightarrow 3, 9 \rightarrow 3, 9 \rightarrow 7, 9 \rightarrow 8, f(Z,X)=7 because of 3 \rightarrow 1, 7 \rightarrow 1, 7 \rightarrow 5, 7 \rightarrow 6, 8 \rightarrow 1, 8 \rightarrow 5, 8 \rightarrow 6, f(Z,Y)=5 because of 3 \rightarrow 2, 7 \rightarrow 2, 7 \rightarrow 4, 8 \rightarrow 2, 8 \rightarrow 4. Please, divide labs into n groups with size n, such that the value \min f(A,B) over all possible pairs of groups A and B (A \neq B) is maximal.In other words, divide labs into n groups with size n, such that minimum number of the sum of units of water that can be transported from a group A to a group B for every pair of different groups A and B (A \neq B) as big as possible.Note, that the example above doesn't demonstrate an optimal division, but it demonstrates how to calculate the values f for some division.If there are many optimal divisions, you can find any.
Input: ['3', ''] Output:['2 8 5', '9 3 4', '7 6 1', '']
[ 2 ]
Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.There are n kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind.Also, there are m boxes. All of them are for different people, so they are pairwise distinct (consider that the names of m friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box.Alice wants to pack presents with the following rules: She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of n kinds, empty boxes are allowed); For each kind at least one present should be packed into some box. Now Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo 10^9+7.See examples and their notes for clarification.
Input: ['1 3', ''] Output:['7']
[ 3 ]
Alice is playing with some stones.Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones.Each time she can do one of two operations: take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones); take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has 0 stones. Can you help her?
Input: ['3', '3 4 5', '1 0 5', '5 3 2', ''] Output:['9', '0', '6', '']
[ 0, 2, 3 ]
Let's define p_i(n) as the following permutation: [i, 1, 2, ..., i - 1, i + 1, ..., n]. This means that the i-th permutation is almost identity (i.e. which maps every element to itself) permutation but the element i is on the first position. Examples: p_1(4) = [1, 2, 3, 4]; p_2(4) = [2, 1, 3, 4]; p_3(4) = [3, 1, 2, 4]; p_4(4) = [4, 1, 2, 3]. You are given an array x_1, x_2, ..., x_m (1 <= x_i <= n).Let pos(p, val) be the position of the element val in p. So, pos(p_1(4), 3) = 3, pos(p_2(4), 2) = 1, pos(p_4(4), 4) = 1.Let's define a function f(p) = \sum\limits_{i=1}^{m - 1} |pos(p, x_i) - pos(p, x_{i + 1})|, where |val| is the absolute value of val. This function means the sum of distances between adjacent elements of x in p.Your task is to calculate f(p_1(n)), f(p_2(n)), ..., f(p_n(n)).
Input: ['4 4', '1 2 3 4', ''] Output:['3 4 6 5 ', '']
[ 3 ]
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all n goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.So you need to find the minimum possible equal price of all n goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.You have to answer q independent queries.
Input: ['3', '5', '1 2 3 4 5', '3', '1 2 2', '4', '1 1 1 1', ''] Output:['3', '2', '1', '']
[ 3 ]
The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out.You are given two strings s and t of the same length n. Their characters are numbered from 1 to n from left to right (i.e. from the beginning to the end).In a single move you can do the following sequence of actions: choose any valid index i (1 <= i <= n), move the i-th character of s from its position to the beginning of the string or move the i-th character of s from its position to the end of the string. Note, that the moves don't change the length of the string s. You can apply a move only to the string s.For example, if s="test" in one move you can obtain: if i=1 and you move to the beginning, then the result is "test" (the string doesn't change), if i=2 and you move to the beginning, then the result is "etst", if i=3 and you move to the beginning, then the result is "stet", if i=4 and you move to the beginning, then the result is "ttes", if i=1 and you move to the end, then the result is "estt", if i=2 and you move to the end, then the result is "tste", if i=3 and you move to the end, then the result is "tets", if i=4 and you move to the end, then the result is "test" (the string doesn't change). You want to make the string s equal to the string t. What is the minimum number of moves you need? If it is impossible to transform s to t, print -1.
Input: ['3', '9', 'iredppipe', 'piedpiper', '4', 'estt', 'test', '4', 'tste', 'test', ''] Output:['2', '1', '2', '']
[ 2 ]
In this problem, a n * m rectangular matrix a is called increasing if, for each row of i, when go from left to right, the values strictly increase (that is, a_{i,1}<a_{i,2}<...<a_{i,m}) and for each column j, when go from top to bottom, the values strictly increase (that is, a_{1,j}<a_{2,j}<...<a_{n,j}).In a given matrix of non-negative integers, it is necessary to replace each value of 0 with some positive integer so that the resulting matrix is increasing and the sum of its elements is maximum, or find that it is impossible.It is guaranteed that in a given value matrix all values of 0 are contained only in internal cells (that is, not in the first or last row and not in the first or last column).
Input: ['4 5', '1 3 5 6 7', '3 0 7 0 9', '5 0 0 0 10', '8 9 10 11 12', ''] Output:['144', '']
[ 2 ]
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input: ['5 3', '51528', ''] Output:['10028', '']
[ 2 ]
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?Note, that you can't keep bags for yourself or throw them away, each bag should be given to one of the friends.
Input: ['1 7 11 5', ''] Output:['YES', '']
[ 0 ]
You have n * n square grid and an integer k. Put an integer in each cell while satisfying the conditions below. All numbers in the grid should be between 1 and k inclusive. Minimum number of the i-th row is 1 (1 <= i <= n). Minimum number of the j-th column is 1 (1 <= j <= n). Find the number of ways to put integers in the grid. Since the answer can be very large, find the answer modulo (10^{9} + 7). These are the examples of valid and invalid grid when n=k=2.
Input: ['2 2', ''] Output:['7', '']
[ 3 ]
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.Let's make a definition.Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set v_1. There are no edges with both endpoints in vertex set v_2. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y. Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true. Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input: ['6 11', '1 2', '1 3', '1 4', '1 5', '1 6', '2 4', '2 5', '2 6', '3 4', '3 5', '3 6', ''] Output:['1 2 2 3 3 3 ']
[ 0 ]
Let's introduce some definitions that will be needed later.Let prime(x) be the set of prime divisors of x. For example, prime(140) = \{ 2, 5, 7 \}, prime(169) = \{ 13 \}.Let g(x, p) be the maximum possible integer p^k where k is an integer such that x is divisible by p^k. For example: g(45, 3) = 9 (45 is divisible by 3^2=9 but not divisible by 3^3=27), g(63, 7) = 7 (63 is divisible by 7^1=7 but not divisible by 7^2=49). Let f(x, y) be the product of g(y, p) for all p in prime(x). For example: f(30, 70) = g(70, 2) \cdot g(70, 3) \cdot g(70, 5) = 2^1 \cdot 3^0 \cdot 5^1 = 10, f(525, 63) = g(63, 3) \cdot g(63, 5) \cdot g(63, 7) = 3^2 \cdot 5^0 \cdot 7^1 = 63. You have integers x and n. Calculate f(x, 1) \cdot f(x, 2) \cdot ... \cdot f(x, n) \bmod{(10^{9} + 7)}.
Input: ['10 2', ''] Output:['2', '']
[ 3 ]
Suppose there is a h * w grid consisting of empty or full cells. Let's make some definitions: r_{i} is the number of consecutive full cells connected to the left side in the i-th row (1 <= i <= h). In particular, r_i=0 if the leftmost cell of the i-th row is empty. c_{j} is the number of consecutive full cells connected to the top end in the j-th column (1 <= j <= w). In particular, c_j=0 if the topmost cell of the j-th column is empty. In other words, the i-th row starts exactly with r_i full cells. Similarly, the j-th column starts exactly with c_j full cells. These are the r and c values of some 3 * 4 grid. Black cells are full and white cells are empty. You have values of r and c. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of r and c. Since the answer can be very large, find the answer modulo 1000000007\,(10^{9} + 7). In other words, find the remainder after division of the answer by 1000000007\,(10^{9} + 7).
Input: ['3 4', '0 3 1', '0 2 3 0', ''] Output:['2', '']
[ 3 ]
You have two integers l and r. Find an integer x which satisfies the conditions below: l <= x <= r. All digits of x are different. If there are multiple answers, print any of them.
Input: ['121 130', ''] Output:['123', '']
[ 0 ]
Your program fails again. This time it gets "Wrong answer on test 233".This is the harder version of the problem. In this version, 1 <= n <= 2\cdot10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.The problem is to finish n one-choice-questions. Each of the questions contains k options, and only one of them is correct. The answer to the i-th question is h_{i}, and if your answer of the question i is h_{i}, you earn 1 point, otherwise, you earn 0 points for this question. The values h_1, h_2, ..., h_n are known to you in this problem.However, you have a mistake in your program. It moves the answer clockwise! Consider all the n answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.Formally, the mistake moves the answer for the question i to the question i \bmod n + 1. So it moves the answer for the question 1 to question 2, the answer for the question 2 to the question 3, ..., the answer for the question n to the question 1.We call all the n answers together an answer suit. There are k^n possible answer suits in total.You're wondering, how many answer suits satisfy the following condition: after moving clockwise by 1, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo 998\,244\,353.For example, if n = 5, and your answer suit is a=[1,2,3,4,5], it will submitted as a'=[5,1,2,3,4] because of a mistake. If the correct answer suit is h=[5,2,2,3,4], the answer suit a earns 1 point and the answer suite a' earns 4 points. Since 4 > 1, the answer suit a=[1,2,3,4,5] should be counted.
Input: ['3 3', '1 3 1', ''] Output:['9', '']
[ 3 ]
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n * m rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as 0) some trees were set on fire. At the beginning of minute 0, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of 8 neighboring trees. At the beginning of minute T, the fire was extinguished.The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of T (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of T (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.Note that you'd like to maximize value T but the set of trees can be arbitrary.
Input: ['3 6', 'XXXXXX', 'XXXXXX', 'XXXXXX', ''] Output:['1', '......', '.X.XX.', '......', '']
[ 4 ]
This is the harder version of the problem. In this version, 1 <= n, m <= 2\cdot10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 <= k <= n) is given, then the subsequence is called optimal if: it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 <= t <= k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: [10, 20, 20] lexicographically less than [10, 21, 1], [7, 99, 99] is lexicographically less than [10, 21, 1], [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 <= k <= n, 1 <= pos_j <= k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
Input: ['3', '10 20 10', '6', '1 1', '2 1', '2 2', '3 1', '3 2', '3 3', ''] Output:['20', '10', '20', '10', '20', '10', '']
[ 2 ]
This is the easier version of the problem. In this version 1 <= n, m <= 100. You can hack this problem only if you solve and lock both problems.You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 <= k <= n) is given, then the subsequence is called optimal if: it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 <= t <= k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: [10, 20, 20] lexicographically less than [10, 21, 1], [7, 99, 99] is lexicographically less than [10, 21, 1], [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 <= k <= n, 1 <= pos_j <= k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
Input: ['3', '10 20 10', '6', '1 1', '2 1', '2 2', '3 1', '3 2', '3 3', ''] Output:['20', '10', '20', '10', '20', '10', '']
[ 2 ]
Your math teacher gave you the following problem:There are n segments on the x-axis, [l_1; r_1], [l_2; r_2], ..., [l_n; r_n]. The segment [l; r] includes the bounds, i.e. it is a set of such x that l <= x <= r. The length of the segment [l; r] is equal to r - l.Two segments [a; b] and [c; d] have a common point (intersect) if there exists x that a <=q x <=q b and c <=q x <=q d. For example, [2; 5] and [3; 10] have a common point, but [5; 6] and [1; 4] don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given n segments.In other words, you need to find a segment [a; b], such that [a; b] and every [l_i; r_i] have a common point for each i, and b-a is minimal.
Input: ['4', '3', '4 5', '5 9', '7 7', '5', '11 19', '4 17', '16 16', '3 12', '14 17', '1', '1 10', '1', '1 1', ''] Output:['2', '4', '0', '0', '']
[ 3 ]
There are n positive integers written on the blackboard. Also, a positive number k >=q 2 is chosen, and none of the numbers on the blackboard are divisible by k. In one operation, you can choose any two integers x and y, erase them and write one extra number f(x + y), where f(x) is equal to x if x is not divisible by k, otherwise f(x) = f(x / k).In the end, there will be a single number of the blackboard. Is it possible to make the final number equal to 1? If so, restore any sequence of operations to do so.
Input: ['2 2', '1 1', ''] Output:['YES', '1 1', '']
[ 2 ]
Bytelandian Tree Factory produces trees for all kinds of industrial applications. You have been tasked with optimizing the production of a certain type of tree for an especially large and important order.The tree in question is a rooted tree with n vertices labelled with distinct integers from 0 to n - 1. The vertex labelled 0 is the root of the tree, and for any non-root vertex v the label of its parent p(v) is less than the label of v.All trees at the factory are made from bamboo blanks. A bamboo is a rooted tree such that each vertex has exactly one child, except for a single leaf vertex with no children. The vertices of a bamboo blank can be labelled arbitrarily before its processing is started.To process a bamboo into another tree a single type of operation can be made: choose an arbitrary non-root vertex v such that its parent p(v) is not a root either. The operation consists of changing the parent of v to its parent's parent p(p(v)). Note that parents of all other vertices remain unchanged, in particular, the subtree of v does not change.Efficiency is crucial, hence you have to minimize the number of operations to make the desired tree from a bamboo blank. Construct any optimal sequence of operations to produce the desired tree.Note that the labelling of the resulting tree has to coincide with the labelling of the desired tree. Formally, the labels of the roots have to be equal, and for non-root vertices with the same label the labels of their parents should be the same.It is guaranteed that for any test present in this problem an answer exists, and further, an optimal sequence contains at most 10^6 operations. Note that any hack that does not meet these conditions will be invalid.
Input: ['5', '0 0 1 1', ''] Output:['0 2 1 4 3', '2', '1 3', '']
[ 2 ]
You are at the top left cell (1, 1) of an n * m labyrinth. Your goal is to get to the bottom right cell (n, m). You can only move right or down, one cell per step. Moving right from a cell (x, y) takes you to the cell (x, y + 1), while moving down takes you to the cell (x + 1, y).Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on.The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal.Count the number of different legal paths you can take from the start to the goal modulo 10^9 + 7. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other.
Input: ['1 1', '.', ''] Output:['1', '']
[ 4 ]
You are given n positive integers a_1, ..., a_n, and an integer k >=q 2. Count the number of pairs i, j such that 1 <=q i < j <=q n, and there exists an integer x such that a_i \cdot a_j = x^k.
Input: ['6 3', '1 3 9 8 24 1', ''] Output:['5', '']
[ 3 ]
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer.For example, some -9-binary ("minus nine" binary) numbers are: -8 (minus eight), 7 and 1015 (-8=2^0-9, 7=2^4-9, 1015=2^{10}-9).The boys now use p-binary numbers to represent everything. They now face a problem: given a positive integer n, what's the smallest number of p-binary numbers (not necessarily distinct) they need to represent n as their sum? It may be possible that representation is impossible altogether. Help them solve this problem.For example, if p=0 we can represent 7 as 2^0 + 2^1 + 2^2.And if p=-9 we can represent 7 as one number (2^4-9).Note that negative p-binary numbers are allowed to be in the sum (see the Notes section for an example).
Input: ['24 0', ''] Output:['2', '']
[ 0, 3 ]
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b.Can you reconstruct any equation a + 1 = b that satisfies this property? It may be possible that Kolya misremembers the digits, and there is no suitable equation, in which case report so.
Input: ['1 2', ''] Output:['199 200', '']
[ 3 ]
Suppose you are stuck on a desert island. The only way to save yourself is to craft a wooden raft and go to the sea. Fortunately, you have a hand-made saw and a forest nearby. Moreover, you've already cut several trees and prepared it to the point that now you have n logs and the i-th log has length a_i.The wooden raft you'd like to build has the following structure: 2 logs of length x and x logs of length y. Such raft would have the area equal to x \cdot y. Both x and y must be integers since it's the only way you can measure the lengths while being on a desert island. And both x and y must be at least 2 since the raft that is one log wide is unstable.You can cut logs in pieces but you can't merge two logs in one. What is the maximum area of the raft you can craft?
Input: ['1', '9', ''] Output:['4', '']
[ 3, 4 ]
You are given a sequence a_1, a_2, ..., a_n, consisting of integers.You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation.For example, if a = [2, 1, 3, 1, 1, 3, 2], you can get the following sequences in one operation (for convenience, denote elements equal to x as x-elements): [1, 1, 1, 2, 3, 3, 2] if you move all 1-elements to the beginning; [2, 3, 3, 2, 1, 1, 1] if you move all 1-elements to the end; [2, 2, 1, 3, 1, 1, 3] if you move all 2-elements to the beginning; [1, 3, 1, 1, 3, 2, 2] if you move all 2-elements to the end; [3, 3, 2, 1, 1, 1, 2] if you move all 3-elements to the beginning; [2, 1, 1, 1, 2, 3, 3] if you move all 3-elements to the end; You have to determine the minimum number of such operations so that the sequence a becomes sorted in non-descending order. Non-descending order means that for all i from 2 to n, the condition a_{i-1} <= a_i is satisfied.Note that you have to answer q independent queries.
Input: ['3', '7', '3 1 6 6 3 1 1', '8', '1 1 4 4 4 7 8 8', '7', '4 2 5 2 6 2 7', ''] Output:['2', '0', '1', '']
[ 2 ]
You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose: The x\% of the price of each the a-th sold ticket (a-th, 2a-th, 3a-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources. The y\% of the price of each the b-th sold ticket (b-th, 2b-th, 3b-th and so on) in the order you chose is aimed for pollution abatement. If the ticket is in both programs then the (x + y) \% are used for environmental activities. Also, it's known that all prices are multiples of 100, so there is no need in any rounding.For example, if you'd like to sell tickets with prices [400, 100, 300, 200] and the cinema pays 10\% of each 2-nd sold ticket and 20\% of each 3-rd sold ticket, then arranging them in order [100, 200, 300, 400] will lead to contribution equal to 100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120. But arranging them in order [100, 300, 400, 200] will lead to 100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130.Nature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least k in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least k.
Input: ['4', '1', '100', '50 1', '49 1', '100', '8', '100 200 100 200 100 200 100 100', '10 2', '15 3', '107', '3', '1000000000 1000000000 1000000000', '50 1', '50 1', '3000000000', '5', '200 100 100 100 100', '69 5', '31 2', '90', ''] Output:['-1', '6', '3', '4', '']
[ 2, 4 ]
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||. Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer q independent queries.
Input: ['4', '2', '5', '8', '11', ''] Output:['2', '1', '0', '1', '']
[ 3 ]
You are given an undirected graph with n vertices and m edges. You have to write a number on each vertex of this graph, each number should be either 0 or 1. After that, you write a number on each edge equal to the sum of numbers on vertices incident to that edge.You have to choose the numbers you will write on the vertices so that there is at least one edge with 0 written on it, at least one edge with 1 and at least one edge with 2. How many ways are there to do it? Two ways to choose numbers are different if there exists at least one vertex which has different numbers written on it in these two ways.
Input: ['6 5', '1 2', '2 3', '3 4', '4 5', '5 1', ''] Output:['20', '']
[ 0 ]
Petya recently found a game "Choose a Square". In this game, there are n points numbered from 1 to n on an infinite field. The i-th point has coordinates (x_i, y_i) and cost c_i.You have to choose a square such that its sides are parallel to coordinate axes, the lower left and upper right corners belong to the line y = x, and all corners have integer coordinates.The score you get is the sum of costs of the points covered by the selected square minus the length of the side of the square. Note that the length of the side can be zero.Petya asks you to calculate the maximum possible score in the game that can be achieved by placing exactly one square.
Input: ['6', '0 0 2', '1 0 -5', '1 1 3', '2 3 4', '1 4 -4', '3 1 -1', ''] Output:['4', '1 1 3 3', '']
[ 4 ]
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that c of your students are coders, m are mathematicians and x have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer q independent queries.
Input: ['6', '1 1 1', '3 6 0', '0 0 0', '0 1 1', '10 1 10', '4 4 1', ''] Output:['1', '3', '0', '0', '1', '3', '']
[ 3, 4 ]
You are given a chess board with n rows and n columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.A knight is a chess piece that can attack a piece in cell (x_2, y_2) from the cell (x_1, y_1) if one of the following conditions is met: |x_1 - x_2| = 2 and |y_1 - y_2| = 1, or |x_1 - x_2| = 1 and |y_1 - y_2| = 2. Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them). A duel of knights is a pair of knights of different colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.
Input: ['3', ''] Output:['WBW', 'BBB', 'WBW', '']
[ 2 ]
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from s, remove them from s and insert the number equal to their sum into s.For example, if s = \{1, 2, 1, 1, 4, 2, 2\} and you choose integers 2 and 2, then the multiset becomes \{1, 1, 1, 4, 4, 2\}.You win if the number 2048 belongs to your multiset. For example, if s = \{1024, 512, 512, 4\} you can win as follows: choose 512 and 512, your multiset turns into \{1024, 1024, 4\}. Then choose 1024 and 1024, your multiset turns into \{2048, 4\} and you win.You have to determine if you can win this game.You have to answer q independent queries.
Input: ['6', '4', '1024 512 64 512', '1', '2048', '3', '64 512 2', '2', '4096 4', '7', '2048 2 2048 2048 2048 2048 2048', '2', '2048 4096', ''] Output:['YES', 'YES', 'NO', 'NO', 'YES', 'YES', '']
[ 0, 2, 3 ]
Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on n vertices. Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from 1 to n which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?We remind that cyclic shift of permutation a_1, a_2, ..., a_k, ..., a_n for k elements to the left is the permutation a_{k + 1}, a_{k + 2}, ..., a_n, a_1, a_2, ..., a_k.
Input: ['4', '1 2 3 4', ''] Output:['3 2', '']
[ 4 ]
Alex decided to go on a touristic trip over the country.For simplicity let's assume that the country has n cities and m bidirectional roads connecting them. Alex lives in city s and initially located in it. To compare different cities Alex assigned each city a score w_i which is as high as interesting city seems to Alex.Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city v from city u, he may choose as the next city in the trip any city connected with v by the road, except for the city u.Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.
Input: ['5 7', '2 2 8 6 9', '1 2', '1 3', '2 4', '3 2', '4 5', '2 5', '1 5', '2', ''] Output:['27', '']
[ 2 ]
Boy Dima gave Julian a birthday present β€” set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input: ['3', '1 2 3', ''] Output:['1', '2 ']
[ 3 ]
Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string s and a number k (0 <= k < |s|).At the beginning of the game, players are given a substring of s with left border l and right border r, both equal to k (i.e. initially l=r=k). Then players start to make moves one by one, according to the following rules: A player chooses l^{\prime} and r^{\prime} so that l^{\prime} <= l, r^{\prime} >= r and s[l^{\prime}, r^{\prime}] is lexicographically less than s[l, r]. Then the player changes l and r in this way: l := l^{\prime}, r := r^{\prime}. Ann moves first. The player, that can't make a move loses.Recall that a substring s[l, r] (l <= r) of a string s is a continuous segment of letters from s that starts at position l and ends at position r. For example, "ehn" is a substring (s[3, 5]) of "aaaehnsvz" and "ahz" is not.Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only s and k.Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes s and determines the winner for all possible k.
Input: ['abba', ''] Output:['Mike', 'Ann', 'Ann', 'Mike', '']
[ 2 ]
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i \cdot a_j where a_1, ..., a_n is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array!
Input: ['5', '0 4 6 2 4', '4 0 6 2 4', '6 6 0 3 6', '2 2 3 0 2', '4 4 6 2 0', ''] Output:['2 2 3 1 2 ']
[ 3 ]
For her birthday Alice received an interesting gift from her friends – The Light Square. The Light Square game is played on an N * N lightbulbs square board with a magical lightbulb bar of size N * 1 that has magical properties. At the start of the game some lights on the square board and magical bar are turned on. The goal of the game is to transform the starting light square board pattern into some other pattern using the magical bar without rotating the square board. The magical bar works as follows: It can be placed on any row or column The orientation of the magical lightbulb must be left to right or top to bottom for it to keep its magical properties The entire bar needs to be fully placed on a board The lights of the magical bar never change If the light on the magical bar is the same as the light of the square it is placed on it will switch the light on the square board off, otherwise it will switch the light on The magical bar can be used an infinite number of times Alice has a hard time transforming her square board into the pattern Bob gave her. Can you help her transform the board or let her know it is impossible? If there are multiple solutions print any.
Input: ['2', '11', '11', '00', '01', '11', ''] Output:['-1', '']
[ 2 ]
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input: ['5 10000', '10000 30000 30000 40000 20000', '20000', '5 2 8 3 6', ''] Output:['5', '']
[ 2 ]
Let's define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that holds for every position, then the multiset is balanced. Otherwise it's unbalanced.For example, multiset \{20, 300, 10001\} is balanced and multiset \{20, 310, 10001\} is unbalanced: The red digits mark the elements and the positions for which these elements have the same digit as the sum. The sum of the first multiset is 10321, every position has the digit required. The sum of the second multiset is 10331 and the second-to-last digit doesn't appear in any number, thus making the multiset unbalanced.You are given an array a_1, a_2, ..., a_n, consisting of n integers.You are asked to perform some queries on it. The queries can be of two types: 1~i~x β€” replace a_i with the value x; 2~l~r β€” find the unbalanced subset of the multiset of the numbers a_l, a_{l + 1}, ..., a_r with the minimum sum, or report that no unbalanced subset exists. Note that the empty multiset is balanced.For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
Input: ['4 5', '300 10001 20 20', '2 1 3', '1 1 310', '2 1 3', '2 3 3', '2 3 4', ''] Output:['-1', '330', '-1', '40', '']
[ 2, 3 ]
You are given a binary string s (recall that a string is binary if each character is either 0 or 1).Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4.The substring s_{l}, s_{l+1}, ... , s_{r} is good if r - l + 1 = f(s_l ... s_r).For example string s = 1011 has 5 good substrings: s_1 ... s_1 = 1, s_3 ... s_3 = 1, s_4 ... s_4 = 1, s_1 ... s_2 = 10 and s_2 ... s_4 = 011. Your task is to calculate the number of good substrings of string s.You have to answer t independent queries.
Input: ['4', '0110', '0101', '00001000', '0001000', ''] Output:['4', '3', '4', '3', '']
[ 0, 4 ]
You are fighting with Zmei Gorynich β€” a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! Initially Zmei Gorynich has x heads. You can deal n types of blows. If you deal a blow of the i-th type, you decrease the number of Gorynich's heads by min(d_i, curX), there curX is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows h_i new heads. If curX = 0 then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if curX = 10, d = 7, h = 10 then the number of heads changes to 13 (you cut 7 heads off, but then Zmei grows 10 new ones), but if curX = 10, d = 11, h = 100 then number of heads changes to 0 and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer t independent queries.
Input: ['3', '3 10', '6 3', '8 2', '1 4', '4 10', '4 1', '3 2', '2 6', '1 100', '2 15', '10 11', '14 100', ''] Output:['2', '3', '-1', '']
[ 2, 3 ]
You play your favourite game yet another time. You chose the character you didn't play before. It has str points of strength and int points of intelligence. Also, at start, the character has exp free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by 1 or raise intelligence by 1).Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.
Input: ['4', '5 3 4', '2 1 0', '3 5 5', '4 10 6', ''] Output:['3', '1', '2', '0', '']
[ 3, 4 ]
You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n.You have to connect all n rooms to the Internet.You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers. Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have.
Input: ['5 2', '00100', ''] Output:['3', '']
[ 2 ]
The only difference between the easy and the hard versions is the maximum value of k.You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input: ['5', '1', '3', '20', '38', '56', ''] Output:['1', '2', '5', '2', '0', '']
[ 3, 4 ]
The only difference between the easy and the hard versions is the maximum value of k.You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input: ['5', '1', '3', '20', '38', '56', ''] Output:['1', '2', '5', '2', '0', '']
[ 0, 3, 4 ]
There were n types of swords in the theater basement which had been used during the plays. Moreover there were exactly x swords of each type. y people have broken into the theater basement and each of them has taken exactly z swords of some single type. Note that different people might have taken different types of swords. Note that the values x, y and z are unknown for you.The next morning the director of the theater discovers the loss. He counts all swords β€” exactly a_i swords of the i-th type are left untouched.The director has no clue about the initial number of swords of each type in the basement, the number of people who have broken into the basement and how many swords each of them have taken.For example, if n=3, a = [3, 12, 6] then one of the possible situations is x=12, y=5 and z=3. Then the first three people took swords of the first type and the other two people took swords of the third type. Note that you don't know values x, y and z beforehand but know values of n and a.Thus he seeks for your help. Determine the minimum number of people y, which could have broken into the theater basement, and the number of swords z each of them has taken.
Input: ['3', '3 12 6', ''] Output:['5 3', '']
[ 3 ]
There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates (0, 0), and coordinate axes are left and bottom sides of the table, then the bottom left corner of the white sheet has coordinates (x_1, y_1), and the top right β€” (x_2, y_2).After that two black sheets of paper are placed on the table. Sides of both black sheets are also parallel to the sides of the table. Coordinates of the bottom left corner of the first black sheet are (x_3, y_3), and the top right β€” (x_4, y_4). Coordinates of the bottom left corner of the second black sheet are (x_5, y_5), and the top right β€” (x_6, y_6). Example of three rectangles. Determine if some part of the white sheet can be seen from the above after the two black sheets are placed. The part of the white sheet can be seen if there is at least one point lying not strictly inside the white sheet and strictly outside of both black sheets.
Input: ['2 2 4 4', '1 1 3 5', '3 1 5 5', ''] Output:['NO', '']
[ 3 ]
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i \cdot x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down.Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible.
Input: ['3', '20 10 20', ''] Output:['43', '1 3 2 ', '']
[ 2 ]
Monocarp and Bicarp live in Berland, where every bus ticket consists of n digits (n is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first \frac{n}{2} digits of this ticket is equal to the sum of the last \frac{n}{2} digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from 0 to 9. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.
Input: ['4', '0523', ''] Output:['Bicarp', '']
[ 2, 3 ]
Monocarp has got two strings s and t having equal length. Both strings consist of lowercase Latin letters "a" and "b". Monocarp wants to make these two strings s and t equal to each other. He can do the following operation any number of times: choose an index pos_1 in the string s, choose an index pos_2 in the string t, and swap s_{pos_1} with t_{pos_2}.You have to determine the minimum number of operations Monocarp has to perform to make s and t equal, and print any optimal sequence of operations β€” or say that it is impossible to make these strings equal.
Input: ['4', 'abab', 'aabb', ''] Output:['2', '3 3', '3 2', '']
[ 2 ]
The final match of the Berland Football Cup has been held recently. The referee has shown n yellow cards throughout the match. At the beginning of the match there were a_1 players in the first team and a_2 players in the second team.The rules of sending players off the game are a bit different in Berland football. If a player from the first team receives k_1 yellow cards throughout the match, he can no longer participate in the match β€” he's sent off. And if a player from the second team receives k_2 yellow cards, he's sent off. After a player leaves the match, he can no longer receive any yellow cards. Each of n yellow cards was shown to exactly one player. Even if all players from one team (or even from both teams) leave the match, the game still continues.The referee has lost his records on who has received each yellow card. Help him to determine the minimum and the maximum number of players that could have been thrown out of the game.
Input: ['2', '3', '5', '1', '8', ''] Output:['0 4', '']
[ 2, 3 ]
Two large companies "Cecsi" and "Poca Pola" are fighting against each other for a long time. In order to overcome their competitor, "Poca Pola" started a super secret project, for which it has total n vacancies in all of their offices. After many tests and interviews n candidates were selected and the only thing left was their employment.Because all candidates have the same skills, it doesn't matter where each of them will work. That is why the company decided to distribute candidates between workplaces so that the total distance between home and workplace over all candidates is minimal.It is well known that Earth is round, so it can be described as a circle, and all m cities on Earth can be described as points on this circle. All cities are enumerated from 1 to m so that for each i (1 <= i <= m - 1) cities with indexes i and i + 1 are neighbors and cities with indexes 1 and m are neighbors as well. People can move only along the circle. The distance between any two cities equals to minimal number of transitions between neighboring cities you have to perform to get from one city to another. In particular, the distance between the city and itself equals 0.The "Poca Pola" vacancies are located at offices in cities a_1, a_2, ..., a_n. The candidates live in cities b_1, b_2, ..., b_n. It is possible that some vacancies are located in the same cities and some candidates live in the same cities. The "Poca Pola" managers are too busy with super secret project, so you were asked to help "Poca Pola" to distribute candidates between workplaces, so that the sum of the distance between home and workplace over all candidates is minimum possible.
Input: ['10 3', '1 5 5', '10 4 6', ''] Output:['3', '1 2 3 ']
[ 2 ]
It's Petya's birthday party and his friends have presented him a brand new "Electrician-n" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.Construction set "Electrician-n" consists of 2n - 1 wires and 2n light bulbs. Each bulb has its own unique index that is an integer from 1 to 2n, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed 2i and 2i - 1 turn on if the chain connecting them consists of exactly d_i wires. Moreover, the following important condition holds: the value of d_i is never greater than n.Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.
Input: ['3', '2 2 2', ''] Output:['1 6', '2 6', '3 5', '3 6', '4 5', '']
[ 3 ]
Petya's friends made him a birthday present β€” a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence s is called correct if: s is empty; s is equal to "(t)", where t is correct bracket sequence; s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.
Input: ['2', ')(', ''] Output:['Yes', '']
[ 2 ]
There are b boys and g girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and n participants have accepted the invitation. The organizers do not know how many boys and girls are among them.Organizers are preparing red badges for girls and blue ones for boys.Vasya prepared n+1 decks of badges. The i-th (where i is from 0 to n, inclusive) deck contains i blue badges and n-i red ones. The total number of badges in any deck is exactly n.Determine the minimum number of decks among these n+1 that Vasya should take, so that there will be a suitable deck no matter how many girls and boys there will be among the participants of the tournament.
Input: ['5', '6', '3', ''] Output:['4', '']
[ 0, 3 ]
Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has n rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is d rubles, and one euro costs e rubles.Recall that there exist the following dollar bills: 1, 2, 5, 10, 20, 50, 100, and the following euro bills β€” 5, 10, 20, 50, 100, 200 (note that, in this problem we do not consider the 500 euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help him β€” write a program that given integers n, e and d, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.
Input: ['100', '60', '70', ''] Output:['40', '']
[ 0, 3 ]
Authors have come up with the string s consisting of n lowercase Latin letters.You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.For all i from 1 to n-1 the following properties hold: s[p_i] <= s[p_{i + 1}] and s[q_i] <= s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.
Input: ['3 2', '1 2 3', '1 3 2', ''] Output:['YES', 'abb', '']
[ 2 ]
You are given two strings s and t both of length 2 and both consisting only of characters 'a', 'b' and 'c'.Possible examples of strings s and t: "ab", "ca", "bb".You have to find a string res consisting of 3n characters, n characters should be 'a', n characters should be 'b' and n characters should be 'c' and s and t should not occur in res as substrings.A substring of a string is a contiguous subsequence of that string. So, the strings "ab", "ac" and "cc" are substrings of the string "abacc", but the strings "bc", "aa" and "cb" are not substrings of the string "abacc".If there are multiple answers, you can print any of them.
Input: ['2', 'ab', 'bc', ''] Output:['YES', 'acbbac', '']
[ 0 ]
The only difference between easy and hard versions is the number of elements in the array.You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := \lfloor\frac{a_i}{2}\rfloor).You can perform such an operation any (possibly, zero) number of times with any a_i.Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input: ['5 3', '1 2 2 4 5', ''] Output:['1', '']
[ 0, 3 ]
The only difference between easy and hard versions is the number of elements in the array.You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := \lfloor\frac{a_i}{2}\rfloor).You can perform such an operation any (possibly, zero) number of times with any a_i.Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input: ['5 3', '1 2 2 4 5', ''] Output:['1', '']
[ 0 ]
Polycarp is reading a book consisting of n pages numbered from 1 to n. Every time he finishes the page with the number divisible by m, he writes down the last digit of this page number. For example, if n=15 and m=5, pages divisible by m are 5, 10, 15. Their last digits are 5, 0, 5 correspondingly, their sum is 10.Your task is to calculate the sum of all digits Polycarp has written down.You have to answer q independent queries.
Input: ['7', '1 1', '10 1', '100 3', '1024 14', '998244353 1337', '123 144', '1234312817382646 13', ''] Output:['1', '45', '153', '294', '3359835', '0', '427262129093995', '']
[ 3 ]
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: Move the chip i by 2 to the left or 2 to the right for free (i.e. replace the current coordinate x_i with x_i - 2 or with x_i + 2); move the chip i by 1 to the left or 1 to the right and pay one coin for this move (i.e. replace the current coordinate x_i with x_i - 1 or with x_i + 1). Note that it's allowed to move chips to any integer coordinate, including negative and zero.Your task is to find the minimum total number of coins required to move all n chips to the same coordinate (i.e. all x_i should be equal after some sequence of moves).
Input: ['3', '1 2 3', ''] Output:['1', '']
[ 3 ]
There are n cities and n-1 two-way roads in Treeland. Each road connects a pair of different cities. From any city you can drive to any other, moving only along the roads. Cities are numbered from 1 to n. Yes, of course, you recognized an undirected tree in this description.The government plans to repair all the roads. Each road will be repaired by some private company. In total, the country has 10^6 private companies that are numbered from 1 to 10^6. It is possible that some companies will not repair roads at all, and some will repair many roads.To simplify the control over the work of private companies, the following restriction was introduced: for each city, we calculate the number of different companies that repair roads that have this city at one end. This number for each city should not exceed 2. In other words, for each city, there should be no more than two different companies that repair roads related to this city.The National Anti-Corruption Committee of Treeland raises concerns that all (or almost all) of the work will go to one private company. For this reason, the committee requires that roads be distributed among companies in such a way as to minimize the value of r. For each company, we calculate the number of roads assigned to it, the maximum among all companies is called the number r.Help the government find such a way to distribute all roads among companies in the required way.
Input: ['3', '3', '1 2', '2 3', '6', '1 2', '1 3', '1 4', '1 5', '1 6', '7', '3 1', '1 4', '4 6', '5 1', '2 4', '1 7', ''] Output:['1', '10 20', '3', '1 1 1 2 2 ', '2', '11 11 12 13 12 13', '']
[ 4 ]
There are n cities and n-1 two-way roads in Treeland. Each road connects a pair of different cities. From any city you can drive to any other, moving only along the roads. Cities are numbered from 1 to n. Yes, of course, you recognized an undirected tree in this description.There is exactly one flag in each city, in the i-th city the flag color is c_i. The colors of the flags in different cities may be the same.If the King travels along the route [u_1, u_2, u_3, ..., u_k], then this means that he starts in the city u_1, then moves to the city u_2 (u_2 is connected by road with u_1), then from u_2 to u_3 (u_3 is connected by road to u_2), and so on until he arrives in the city of u_k. It is possible that during this route the King will visit the same city more than once. In other words, the route [u_1, u_2, u_3, ..., u_k] does not necessarily consist of different cities. In terms of graph theory β€” the King moves from u_1 to u_k along some path [u_1, u_2, u_3, ..., u_k], which is not necessarily simple (for all j from 1 to k-1 of the city u_j and u_{j+1} are connected by road).When the King moves from one city to another, city heads exchange flags as a sign of their friendship. Example of moving the King along the route [1, 4, 2, 6]. The color of the vertex matches the color of the flag at that vertex. For aesthetic reasons, the King wants the flag color in the city i to be equal to d_i for all i from 1 to n. Determine whether the King can choose some route and drive along it so that for each city the flag color in it turns out to be equal to the desired color d_i. Note that the King can choose (and drive) exactly one route. If yes, find the shortest possible route for the King.If the initial colors of the flags already match the King's requirements (i.e. c_i=d_i for all i), then consider that the King makes a route of length k=0.
Input: ['1', '7', '2 3 2 7 1 1 3', '7 1 2 3 1 2 3', '1 7', '4 1', '2 6', '2 3', '2 4', '5 4', ''] Output:['Yes', '4', '1 4 2 6 ', '']
[ 3 ]
Polycarp recently became an employee of the company "Double Permutation Inc." Now he is a fan of permutations and is looking for them everywhere!A permutation in this problem is a sequence of integers p_1, p_2, ..., p_k such that every integer from 1 to k occurs exactly once in it. For example, the following sequences are permutations of [3, 1, 4, 2], [1] and [6, 1, 2, 3, 5, 4]. The following sequences are not permutations: [0, 1], [1, 2, 2], [1, 2, 4] and [2, 3].In the lobby of the company's headquarter statistics on visits to the company's website for the last n days are published β€” the sequence a_1, a_2, ..., a_n. Polycarp wants to color all the elements of this sequence in one of three colors (red, green or blue) so that: all red numbers, being written out of a_1, a_2, ..., a_n from left to right (that is, without changing their relative order), must form some permutation (let's call it P); all green numbers, being written out of a_1, a_2, ..., a_n from left to right (that is, without changing their relative order), must form the same permutation P; among blue numbers there should not be elements that are equal to some element of the permutation P. Help Polycarp to color all n numbers so that the total number of red and green elements is maximum.
Input: ['5', '1 2 3 2 1', ''] Output:['RBBBG', '']
[ 2, 4 ]
There are n table bowling players, the rating of the i-th player equals r_i. Compose a maximum number of teams in a such way that: each player belongs to at most one team; each team contains exactly a+b players; each team contains a group of a players with the same rating and a group of b players with another same rating, which must be k times larger than the rating of the players in the first group. For example, if n=12, r=[1, 1, 2, 2, 2, 2, 2, 3, 3, 4, 6, 6], a=1, b=2, k=2, you can compose two teams with ratings [1, 2, 2] and one team with ratings [3, 6, 6]. So, the maximum number of teams is 3.Find the maximum number of teams by given n, r_1 ... r_n, a, b and k to compose in respect to the given requirements.
Input: ['12 1 2 2', '1 1 2 2 2 2 2 3 3 4 6 6', ''] Output:['3', '']
[ 2, 3, 4 ]
Summer in Berland lasts n days, the price of one portion of ice cream on the i-th day is c_i. Over the summer, Tanya wants to eat exactly k portions of ice cream. At the same time, on the i-th day, she decided that she would eat at least a_i portions, but not more than b_i (a_i <= b_i) portions. In other words, let d_i be equal to the number of portions that she eats on the i-th day. Then d_1+d_2+...+d_n=k and a_i <= d_i <= b_i for each i.Given that portions of ice cream can only be eaten on the day of purchase, find the minimum amount of money that Tanya can spend on ice cream in the summer.
Input: ['3 7', '3 5 6', '0 3 4', '3 3 3', ''] Output:['31', '']
[ 2 ]
This is a harder version of the problem. In this version, n <= 7.Marek is working hard on creating strong test cases to his new algorithmic problem. Do you want to know what it is? Nah, we're not telling you. However, we can tell you how he generates test cases.Marek chooses an integer n and n^2 integers p_{ij} (1 <= i <= n, 1 <= j <= n). He then generates a random bipartite graph with 2n vertices. There are n vertices on the left side: \ell_1, \ell_2, ..., \ell_n, and n vertices on the right side: r_1, r_2, ..., r_n. For each i and j, he puts an edge between vertices \ell_i and r_j with probability p_{ij} percent.It turns out that the tests will be strong only if a perfect matching exists in the generated graph. What is the probability that this will occur?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}. Let Q^{-1} be an integer for which Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}. Print the value of P \cdot Q^{-1} modulo 10^9+7.
Input: ['2', '50 50', '50 50', ''] Output:['937500007', '']
[ 0 ]
This is an easier version of the problem. In this version, n <= 6.Marek is working hard on creating strong testcases to his new algorithmic problem. You want to know what it is? Nah, we're not telling you. However, we can tell you how he generates the testcases.Marek chooses an integer n and n^2 integers p_{ij} (1 <= i <= n, 1 <= j <= n). He then generates a random bipartite graph with 2n vertices. There are n vertices on the left side: \ell_1, \ell_2, ..., \ell_n, and n vertices on the right side: r_1, r_2, ..., r_n. For each i and j, he puts an edge between vertices \ell_i and r_j with probability p_{ij} percent.It turns out that the tests will be strong only if a perfect matching exists in the generated graph. What is the probability that this will occur?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}. Let Q^{-1} be an integer for which Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}. Print the value of P \cdot Q^{-1} modulo 10^9+7.
Input: ['2', '50 50', '50 50', ''] Output:['937500007', '']
[ 0 ]
Wojtek has just won a maths competition in Byteland! The prize is admirable β€” a great book called 'Card Tricks for Everyone.' 'Great!' he thought, 'I can finally use this old, dusted deck of cards that's always been lying unused on my desk!'The first chapter of the book is 'How to Shuffle k Cards in Any Order You Want.' It's basically a list of n intricate methods of shuffling the deck of k cards in a deterministic way. Specifically, the i-th recipe can be described as a permutation (P_{i,1}, P_{i,2}, ..., P_{i,k}) of integers from 1 to k. If we enumerate the cards in the deck from 1 to k from top to bottom, then P_{i,j} indicates the number of the j-th card from the top of the deck after the shuffle.The day is short and Wojtek wants to learn only some of the tricks today. He will pick two integers l, r (1 <= l <= r <= n), and he will memorize each trick from the l-th to the r-th, inclusive. He will then take a sorted deck of k cards and repeatedly apply random memorized tricks until he gets bored. He still likes maths, so he started wondering: how many different decks can he have after he stops shuffling it?Wojtek still didn't choose the integers l and r, but he is still curious. Therefore, he defined f(l, r) as the number of different decks he can get if he memorizes all the tricks between the l-th and the r-th, inclusive. What is the value of\sum_{l=1}^n \sum_{r=l}^n f(l, r)?
Input: ['3 3', '2 1 3', '3 1 2', '1 3 2', ''] Output:['25', '']
[ 3 ]
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?You're given a tree β€” a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.Each vertex v is assigned its beauty x_v β€” a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.Your task is to find the sum \sum_{u\text{ is an ancestor of }v} f(u, v). As the result might be too large, please output it modulo 10^9 + 7.Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input: ['5', '4 5 6 0 8', '1 2', '1 3', '1 4', '4 5', ''] Output:['42', '']
[ 3 ]
Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i and b_i; b_i is equal to the skill level of the i-th student (the higher, the better). Also, there are 60 known algorithms, which are numbered with integers from 0 to 59. If the i-th student knows the j-th algorithm, then the j-th bit (2^j) is set in the binary representation of a_i. Otherwise, this bit is not set.Student x thinks that he is better than student y if and only if x knows some algorithm which y doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
Input: ['4', '3 2 3 6', '2 8 5 10', ''] Output:['15', '']
[ 0, 2 ]
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 <=q a <=q b <=q 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.How many dominoes at most can Anadi place on the edges of his graph?
Input: ['4 4', '1 2', '2 3', '3 4', '4 1', ''] Output:['4', '']
[ 0 ]
Airports often use moving walkways to help you walking big distances faster. Each such walkway has some speed that effectively increases your speed. You can stand on such a walkway and let it move you, or you could also walk and then your effective speed is your walking speed plus walkway's speed.Limak wants to get from point 0 to point L on a straight line. There are n disjoint walkways in between. The i-th walkway is described by two integers x_i and y_i and a real value s_i. The i-th walkway starts at x_i, ends at y_i and has speed s_i. Every walkway is located inside the segment [0, L] and no two walkways have positive intersection. However, they can touch by endpoints.Limak needs to decide how to distribute his energy. For example, it might make more sense to stand somewhere (or to walk slowly) to then have a lot of energy to walk faster.Limak's initial energy is 0 and it must never drop below that value. At any moment, he can walk with any speed v in the interval [0, 2] and it will cost him v energy per second, but he continuously recovers energy with speed of 1 energy per second. So, when he walks with speed v, his energy increases by (1-v). Note that negative value would mean losing energy.In particular, he can walk with speed 1 and this won't change his energy at all, while walking with speed 0.77 effectively gives him 0.23 energy per second.Limak can choose his speed arbitrarily (any real value in interval [0, 2]) at every moment of time (including the moments when he is located on non-integer positions). Everything is continuous (non-discrete).What is the fastest time Limak can get from 0 to L?
Input: ['1 5', '0 2 2.0', ''] Output:['3.000000000000', '']
[ 2, 3 ]
This is an easier version of the next problem. In this version, q = 0.A sequence of integers is called nice if its elements are arranged in blocks like in [3, 3, 3, 4, 1, 1]. Formally, if two elements are equal, everything in between must also be equal.Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value x to value y, you must also change all other elements of value x into y as well. For example, for [3, 3, 1, 3, 2, 1, 2] it isn't allowed to change first 1 to 3 and second 1 to 2. You need to leave 1's untouched or change them to the same value.You are given a sequence of integers a_1, a_2, ..., a_n and q updates.Each update is of form "i x" β€” change a_i to x. Updates are not independent (the change stays for the future).Print the difficulty of the initial sequence and of the sequence after every update.
Input: ['5 0', '3 7 3 7 3', ''] Output:['2', '']
[ 2 ]
This is a harder version of the problem. The difference is only in constraints.You are given a rectangular n * m matrix a. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for i-th row it is equal r_i. What is the maximal possible value of r_1+r_2+...+r_n?
Input: ['3', '2 3', '2 5 7', '4 2 4', '3 6', '4 1 5 2 10 4', '8 6 6 4 9 10', '5 4 9 5 8 7', '3 3', '9 9 9', '1 1 1', '1 1 1', ''] Output:['12', '29', '27', '']
[ 2 ]
This is an easier version of the next problem. The difference is only in constraints.You are given a rectangular n * m matrix a. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for i-th row it is equal r_i. What is the maximal possible value of r_1+r_2+...+r_n?
Input: ['2', '2 3', '2 5 7', '4 2 4', '3 6', '4 1 5 2 10 4', '8 6 6 4 9 10', '5 4 9 5 8 7', ''] Output:['12', '29', '']
[ 0, 2 ]
You are given a sequence of n digits d_1d_2 ... d_{n}. You need to paint all the digits in two colors so that: each digit is painted either in the color 1 or in the color 2; if you write in a row from left to right all the digits painted in the color 1, and then after them all the digits painted in the color 2, then the resulting sequence of n digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence d=914 the only valid coloring is 211 (paint in the color 1 two last digits, paint in the color 2 the first digit). But 122 is not a valid coloring (9 concatenated with 14 is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.
Input: ['5', '12', '040425524644', '1', '0', '9', '123456789', '2', '98', '3', '987', ''] Output:['121212211211', '1', '222222222', '21', '-', '']
[ 2 ]
It is a holiday season, and Koala is decorating his house with cool lights! He owns n lights, all of which flash periodically.After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters a_i and b_i. Light with parameters a_i and b_i will toggle (on to off, or off to on) every a_i seconds starting from the b_i-th second. In other words, it will toggle at the moments b_i, b_i + a_i, b_i + 2 \cdot a_i and so on.You know for each light whether it's initially on or off and its corresponding parameters a_i and b_i. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out. Here is a graphic for the first example.
Input: ['3', '101', '3 3', '3 2', '3 1', ''] Output:['2', '']
[ 3 ]