question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
You are given an array of n integers a_1, a_2, ..., a_n. The integers are either 1 or -1. You have to perform the following operation exactly once on the array a: Choose an index i (1 <=q i < n) and flip the signs of a_i and a_{i+1}. Here, flipping the sign means -1 will be 1 and 1 will be -1. What is the maximum possible value of a_1 + a_2 + ... + a_n after applying the above operation? | Input: ['45-1 1 1 -1 -151 1 -1 -1 -121 141 -1 -1 1'] Output:['3', '3', '-2', '4', ''] | [
2
] |
You will be given a weighted directed graph of n nodes and m directed edges, where the i-th edge has a weight of w_i (1 <= i <= m).You need to reverse some edges of this graph so that there is at least one node in the graph from which every other node is reachable. The cost of these reversals is equal to the maximum weight of all reversed edges. If no edge reversal is required, assume the cost to be 0.It is guaranteed that no self-loop or duplicate edge exists.Find the minimum cost required for completing the task. If there is no solution, print a single integer -1. | Input: ['42 11 2 35 41 2 102 3 103 1 104 5 104 51 2 100002 3 200001 3 300004 2 5004 3 204 51 2 100002 3 200001 3 300004 2 54 3 20'] Output:['0', '-1', '20', '5', ''] | [
4
] |
You are given a tree of n nodes, rooted at 1. Every node has a value of either 0 or 1 at time t=0.At any integer time t>0, the value of a node becomes the bitwise XOR of the values of its children at time t - 1; the values of leaves become 0 since they don't have any children.Let S(t) denote the sum of values of all nodes at time t. Let F(A) denote the sum of S(t) across all values of t such that 0 <= t <= 10^{100}, where A is the initial assignment of 0s and 1s in the tree.The task is to find the sum of F(A) for all 2^n initial configurations of 0s and 1s in the tree. Print the sum modulo 10^9+7. | Input: ['161 21 33 43 53 6'] Output:['288', ''] | [
3
] |
A school has to decide on its team for an international quiz. There are n students in the school. We can describe the students using an array a where a_i is the smartness of the i-th (1 <= i <= n) student. There are m topics 1, 2, 3, ..., m from which the quiz questions will be formed. The i-th student is considered proficient in a topic T if (a_i \bmod T) = 0. Otherwise, he is a rookie in that topic. We say that a team of students is collectively proficient in all the topics if for every topic there is a member of the team proficient in this topic.Find a team that is collectively proficient in all the topics such that the maximum difference between the smartness of any two students in that team is minimized. Output this difference. | Input: ['32 43 74 23 7 2 95 76 4 3 5 7'] Output:['-1', '0', '3', ''] | [
3,
4
] |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). There are n! = n \cdot (n-1) \cdot (n - 2) \cdot ... \cdot 1 different permutations of length n.Given a permutation p of n numbers, we create an array a consisting of 2n numbers, which is equal to p concatenated with its reverse. We then define the beauty of p as the number of inversions in a.The number of inversions in the array a is the number of pairs of indices i, j such that i < j and a_i > a_j.For example, for permutation p = [1, 2], a would be [1, 2, 2, 1]. The inversions in a are (2, 4) and (3, 4) (assuming 1-based indexing). Hence, the beauty of p is 2.Your task is to find the sum of beauties of all n! permutations of size n. Print the remainder we get when dividing this value by 1\,000\,000\,007 (10^9 + 7). | Input: ['312100'] Output:['0', '4', '389456655', ''] | [
2,
3
] |
An array a is good if for all pairs of adjacent elements, a_i and a_{i+1} (1<= i \lt n) are of different parity. Note that an array of size 1 is trivially good.You are given an array of size n. In one operation you can select any pair of adjacent elements in which both elements are of the same parity, delete them, and insert their product in the same position.Find the minimum number of operations to form a good array. | Input: ['351 7 11 2 1341 2 3 461 1 1 2 2 3'] Output:['2', '0', '3', ''] | [
2,
3
] |
You are given a string s with length n-1 whose characters are either \texttt{<} or \texttt{>}.Count the permutations p_1, \, p_2, \, ..., \, p_n of 1, \, 2, \, ..., \, n such that, for all i = 1, \, 2, \, ..., \, n - 1, if s_i is \texttt{<} then p_i < p_{i+1} and if s_i is \texttt{>} then p_i > p_{i+1}.Since this number can be very large, compute its logarithm in base 2. | Input: ['2', '<', ''] Output:['0.0000000000', ''] | [
3
] |
The "Parmigiana di melanzane" is a typical Italian dish. Alessandro and Bianca have very different tastes when it comes to it: Alessandro loves to eat Parmigiana with seafood, but Bianca thinks it is an atrocity! To decide which ingredients to include in the dish they prepare, they play the following game.There are n possible ingredients, labeled from 1 to n. The higher the label, the closer the ingredient is to being seafood. The ingredients are connected by n - 1 edges, in such a way as to form a tree. Alessandro and Bianca take turns, with Alessandro going first. They alternately choose a terminal ingredient x, that is an ingredient currently connected to at most one other ingredient, and remove it from the tree. If the terminal ingredient x was chosen by Alessandro, it goes in the recipe; if it was chosen by Bianca, it is discarded.The taste of the Parmigiana is measured as the maximum label of an ingredient in the recipe. Alessandro wants to maximize the taste, while Bianca wants to minimize the taste. If both play optimally, what is the taste of the Parmigiana? | Input: ['4', '1 2', '1 3', '1 4', ''] Output:['4', ''] | [
2,
4
] |
You are at your grandparents' house and you are playing an old video game on a strange console. Your controller has only two buttons and each button has a number written on it.Initially, your score is 0. The game is composed of n rounds. For each 1<= i<= n, the i-th round works as follows.On the screen, a symbol s_i appears, which is either \texttt{+} (plus) or \texttt{-} (minus). Then you must press one of the two buttons on the controller once. Suppose you press a button with the number x written on it: your score will increase by x if the symbol was \texttt{+} and will decrease by x if the symbol was \texttt{-}. After you press the button, the round ends. After you have played all n rounds, you win if your score is 0.Over the years, your grandparents bought many different controllers, so you have q of them. The two buttons on the j-th controller have the numbers a_j and b_j written on them. For each controller, you must compute whether you can win the game playing with that controller. | Input: ['8', '+-+---+-', '5', '2 1', '10 3', '7 9', '10 10', '5 3', ''] Output:['YES', 'NO', 'NO', 'NO', 'YES', ''] | [
3,
4
] |
In a parallel universe there are n chemical elements, numbered from 1 to n. The element number n has not been discovered so far, and its discovery would be a pinnacle of research and would bring the person who does it eternal fame and the so-called SWERC prize.There are m independent researchers, numbered from 1 to m, that are trying to discover it. Currently, the i-th researcher has a sample of the element s_i. Every year, each researcher independently does one fusion experiment. In a fusion experiment, if the researcher currently has a sample of element a, they produce a sample of an element b that is chosen uniformly at random between a+1 and n, and they lose the sample of element a. The elements discovered by different researchers or in different years are completely independent.The first researcher to discover element n will get the SWERC prize. If several researchers discover the element in the same year, they all get the prize. For each i = 1, \, 2, \, ..., \, m, you need to compute the probability that the i-th researcher wins the prize. | Input: ['2 3', '1 1 1', ''] Output:['1.0 1.0 1.0', ''] | [
3
] |
The two siblings Alberto and Beatrice have to eat a spinach pizza together. However, none of them likes spinach, so they both want to eat as little as possible.The pizza has the shape of a strictly convex polygon with n vertices located at integer coordinates (x_1, y_1), \, (x_2, y_2), \, ..., \, (x_n, y_n) of the plane.The siblings have decided to eat the pizza in the following way: taking turns, starting with Alberto, each sibling chooses a vertex of the remaining part of the pizza and eats out the triangle determined by its two neighboring edges. In this way, after each of the first n - 3 turns the pizza will have one less vertex. The game ends after the (n - 2)-th turn, when all the pizza has been eaten.Assuming that Alberto and Beatrice choose the slices to eat optimally, which of the siblings manages to eat at most half of the pizza? You should identify a sibling that has a strategy to do so and help them choose the slices appropriately. Note that it is possible that both Alberto and Beatrice end up eating exactly half of the area if they choose their slices optimally. | Input: ['4', '0 0', '6 1', '5 3', '1 4', ''] Output:['-'] | [
2
] |
After the first successful edition, Gabriella has been asked to organize a second wine tasting event. There will be 2n - 1 bottles of wine arranged in a row, each of which is either red wine or white wine.This time, Gabriella has already chosen the type and order of all the bottles. The types of the wines are represented by a string s of length 2n - 1. For each 1 <= i <= 2n - 1, it holds that s_i = \texttt{R} if the i-th bottle is red wine, and s_i = \texttt{W} if the i-th bottle is white wine.Exactly n critics have been invited to attend. The critics are numbered from 1 to n. Just like last year, each critic j wants to taste an interval of wines, that is, the bottles at positions a_j, \, a_j + 1, \, ..., \, b_j for some 1 <= a_j <= b_j <= 2n - 1. Moreover, they have the following additional requirements: each of them wants to taste at least n wines, that is, it must hold that b_j - a_j + 1 >= n; no two critics must taste exactly the same wines, that is, if j!=k it must hold that a_j!=a_k or b_j!=b_k. Gabriella knows that, since the event is held in a coastal region of Italy, critics are especially interested in the white wines, and don't care much about the red ones. (Indeed, white wine is perfect to accompany seafood.) Thus, to ensure fairness, she would like that all critics taste the same number of white wines.Help Gabriella find an integer x (with 0 <= x <= 2n - 1) such that there exists a valid assignment of intervals to critics where each critic tastes exactly x white wines. It can be proved that at least one such x always exists. | Input: ['5', 'RWWRRRWWW', ''] Output:['2', ''] | [
3
] |
There are n big cities in Italy, and there are m train routes between pairs of cities. Each route connects two different cities bidirectionally. Moreover, using the trains one can reach every city starting from any other city.Right now, all the routes are operated by the government-owned Italian Carriage Passenger Company, but the government wants to privatize the routes. The government does not want to give too much power to a single company, but it also does not want to make people buy a lot of different subscriptions. Also, it would like to give a fair chance to all companies. In order to formalize all these wishes, the following model was proposed.There will be k >= 2 private companies indexed by 1, \, 2, \, ..., \, k. Each train route will be operated by exactly one of the k companies. Then: For any company, there should exist two cities such that it is impossible to reach one from the other using only routes operated by that company. On the other hand, for any two companies, it should be possible to reach every city from any other city using only routes operated by these two companies. Find a plan satisfying all these criteria. It can be shown that a viable plan always exists. Please note that you can choose the number k and you do not have to minimize or maximize it. | Input: ['25 91 21 31 41 52 32 42 53 43 53 31 23 12 3'] Output:['4', '1 2 3 1 4 2 2 4 3', '3', '2 3 1', ''] | [
2
] |
As soon as SWERC starts, your experienced 3-person team immediately realizes that the contest features a easy problems, b medium problems, and c hard problems. Solving a problem will take any of you 2, 3, or 4 time units, depending on whether the problem is easy, medium, or hard. Regardless of the difficulty of the problem, the last time unit spent to solve it has to be spent using your shared computer.You organize your efforts so that each of you starts (and ends) solving problems at integer time units. Any given problem can be solved by only one contestant; it requires a contiguous amount of time (which depends on the difficulty of the problem). None of the 3 of you can solve more than one problem at a time, but you can start solving a new problem immediately after finishing one. Similarly, the shared computer cannot be used by more than one of you at a time, but any of you can start using the computer (to complete the problem currently being solved) immediately after someone else stops using it.Given that the contest lasts l time units, find the maximum number of problems that your team can solve. Additionally, find one way to solve the maximum number of problems. | Input: ['2 1 1 3', ''] Output:['2', '1 0 2', '2 0 3', ''] | [
2,
3
] |
Alessia and Bernardo are discovering the world of competitive programming through the books of their university library.The library consists of m sections numbered from 1 to m. Each section contains only books dedicated to a particular subject and different sections correspond to different subjects. In order to prevent the students from wandering in the library, the university has established a system of passes. Each pass has a length y associated to it and allows access to an interval of y consecutive sections in the library. During a visit, the student must choose exactly one book from one of these sections and leave the library. Each pass can be used only once.At the moment Alessia and Bernardo have n passes of lengths x_1, \, x_2, \, ..., \, x_n. They have different opinions on the best way to improve: Alessia thinks that it is important to study many different topics, while Bernardo believes that it is important to study deeply at least one topic. So, Alessia wants to use the n passes to get n books on distinct topics, while Bernardo would like to get at least two books on the same topic.They have reached the following agreement: for each of the following n days, Alessia will choose a pass of length y among those which are still available and an interval of y sections in the library, and Bernardo will go into the library and will take exactly one book from one of those sections.Can Bernardo manage to get at least two books on the same subject, or will Alessia be able to avoid it?You should decide whether you want to be Alessia or Bernardo, and you have to fulfill the goal of your chosen character. The judge will impersonate the other character. Note that, even if at some moment Bernardo has already taken two books on the same subject, the interaction should go on until the end of the n days. | Input: ['5 14', '3 7 2 3 10', ''] Output:['-'] | [
2
] |
One of the SWERC judges has a dog named Boy. Besides being a good competitive programmer, Boy loves fresh air, so she wants to be walked at least twice a day. Walking Boy requires 120 consecutive minutes. Two walks cannot overlap, but one can start as soon as the previous one has finished. Boy before and after getting ACCEPTED on this problem. Today, the judge sent n messages to the SWERC Discord server. The i-th message was sent a_i minutes after midnight. You know that, when walking Boy, the judge does not send any messages, but he can send a message right before or right after a walk. Is it possible that the judge walked Boy at least twice today?Note that a day has 1440 minutes, and a walk is considered to happen today if it starts at a minute s >= 0 and ends right before a minute e <= 1440. In that case, it must hold that e - s = 120 and, for every i = 1, \, 2 \, ..., \, n, either a_i <= s or a_i >= e. | Input: ['614100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 140012100 200 300 400 600 700 800 900 1100 1200 1300 140013100 200 300 400 500 600 700 800 900 1100 1200 1300 140013101 189 272 356 463 563 659 739 979 1071 1170 1274 135814250 1 2 3 4'] Output:['NO', 'YES', 'NO', 'YES', 'YES', 'YES', ''] | [
2
] |
As you know, Martian scientists are actively engaged in space research. One of the highest priorities is Pluto. In order to study this planet in more detail, it was decided to build a laboratory on Pluto.It is known that the lab will be built of n square blocks of equal size. For convenience, we will assume that Pluto's surface is a plane divided by vertical and horizontal lines into unit squares. Each square is either occupied by a lab block or not, and only n squares are occupied.Since each block is square, it has four walls. If a wall is adjacent to another block, it is considered inside, otherwise — outside.Pluto is famous for its extremely cold temperatures, so the outside walls of the lab must be insulated. One unit of insulation per exterior wall would be required. Thus, the greater the total length of the outside walls of the lab (i. e., its perimeter), the more insulation will be needed.Consider the lab layout in the figure below. It shows that the lab consists of n = 33 blocks, and all the blocks have a total of 24 outside walls, i. e. 24 units of insulation will be needed.You should build the lab optimally, i. e., minimize the amount of insulation. On the other hand, there may be many optimal options, so scientists may be interested in the number of ways to build the lab using the minimum amount of insulation, modulo a prime number m.Two ways are considered the same if they are the same when overlapping without turning. Thus, if a lab plan is rotated by 90^{\circ}, such a new plan can be considered a separate way.To help scientists explore Pluto, you need to write a program that solves these difficult problems. | Input: ['3 1127'] Output:['1 1', '#', '1 2', '##', '2 4', '.###', '####', ''] | [
2,
3
] |
Petya and his friend, the robot Petya++, went to BFDMONCON, where the costume contest is taking place today. While walking through the festival, they came across a scientific stand named after Professor Oak and Golfball, where they were asked to solve an interesting problem.Given a sequence of numbers a_1, a_2, ..., a_n you can perform several operations on this sequence.Each operation should look as follows. You choose some subsequence^. Then you call all the numbers at odd positions in this subsequence northern, and all the numbers at even positions in this subsequence southern. In this case, only the position of the number in the subsequence is taken into account, not in the original sequence.For example, consider the sequence 1, 4, 2, 8, 5, 7, 3, 6, 9 and its subsequence (shown in bold) 1, \mathbf{4}, \mathbf{2}, 8, \mathbf{5}, 7, 3, \mathbf{6}, 9. Then the numbers 4 and 5 are northern, and the numbers 2 and 6 are southern.After that, you can do one of the following: add 1 to all northern numbers and subtract 1 from all south numbers; or add 1 to all southern numbers and subtract 1 from all northern numbers. Thus, from the sequence 1, \mathbf{4}, \mathbf{2}, 8, \mathbf{5}, 7, 3, \mathbf{6}, 9, if you choose the subsequence shown in bold, you can get either 1, \mathbf{5}, \mathbf{1}, 8, \mathbf{6}, 7, 3, \mathbf{5}, 9 or 1, \mathbf{3}, \mathbf{3}, 8, \mathbf{4}, 7, 3, \mathbf{7}, 9.Then the operation ends. Note also that all operations are independent, i. e. the numbers are no longer called northern or southern when one operation ends.It is necessary to turn all the numbers of the sequence into zeros using the operations described above. Since there is very little time left before the costume contest, the friends want to know, what is the minimum number of operations required for this.The friends were unable to solve this problem, so can you help them?^ A sequence c is a subsequence of a sequence d if c can be obtained from d by the deletion of several (possibly, zero or all) elements. | Input: ['531 2 -351 0 0 -1 -162 -4 3 -5 4 151 -1 1 -1 170 0 0 0 0 0 0'] Output:['3', '2', '6', '1', '0', ''] | [
2
] |
Mars is home to an unusual species of spiders — Binary spiders.Right now, Martian scientists are observing a colony of n spiders, the i-th of which has a_i legs.Some of the spiders are friends with each other. Namely, the i-th and j-th spiders are friends if \gcd(a_i, a_j)!=1, i. e., there is some integer k >= 2 such that a_i and a_j are simultaneously divided by k without a remainder. Here \gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.Scientists have discovered that spiders can send messages. If two spiders are friends, then they can transmit a message directly in one second. Otherwise, the spider must pass the message to his friend, who in turn must pass the message to his friend, and so on until the message reaches the recipient.Let's look at an example.Suppose a spider with eight legs wants to send a message to a spider with 15 legs. He can't do it directly, because \gcd(8, 15) = 1. But he can send a message through the spider with six legs because \gcd(8, 6) = 2 and \gcd(6, 15) = 3. Thus, the message will arrive in two seconds.Right now, scientists are observing how the s-th spider wants to send a message to the t-th spider. The researchers have a hypothesis that spiders always transmit messages optimally. For this reason, scientists would need a program that could calculate the minimum time to send a message and also deduce one of the optimal routes. | Input: ['7', '2 14 9 6 8 15 11', '5 6', ''] Output:['3', '5 4 6 '] | [
3
] |
Petya and his friend, robot Petya++, like to solve exciting math problems.One day Petya++ came up with the numbers n and x and wrote the following equality on the board: n\ \&\ (n+1)\ \&\ ...\ \&\ m = x, where \& denotes the bitwise AND operation. Then he suggested his friend Petya find such a minimal m (m >= n) that the equality on the board holds.Unfortunately, Petya couldn't solve this problem in his head and decided to ask for computer help. He quickly wrote a program and found the answer.Can you solve this difficult problem? | Input: ['510 810 1010 4220 161000000000000000000 0'] Output:['12', '10', '-1', '24', '1152921504606846976', ''] | [
3
] |
This is an hard version of the problem. The difference between the versions is that the string can be longer than in the easy version. You can only do hacks if both versions of the problem are passed.Kazimir Kazimirovich is a Martian gardener. He has a huge orchard of binary balanced apple trees.Recently Casimir decided to get himself three capybaras. The gardener even came up with their names and wrote them down on a piece of paper. The name of each capybara is a non-empty line consisting of letters "a" and "b".Denote the names of the capybaras by the lines a, b, and c. Then Casimir wrote the nonempty lines a, b, and c in a row without spaces. For example, if the capybara's name was "aba", "ab", and "bb", then the string the gardener wrote down would look like "abaabbb".The gardener remembered an interesting property: either the string b is lexicographically not smaller than the strings a and c at the same time, or the string b is lexicographically not greater than the strings a and c at the same time. In other words, either a <= b and c <= b are satisfied, or b <= a and b <= c are satisfied (or possibly both conditions simultaneously). Here <= denotes the lexicographic "less than or equal to" for strings. Thus, a <= b means that the strings must either be equal, or the string a must stand earlier in the dictionary than the string b. For a more detailed explanation of this operation, see "Notes" section.Today the gardener looked at his notes and realized that he cannot recover the names because they are written without spaces. He is no longer sure if he can recover the original strings a, b, and c, so he wants to find any triplet of names that satisfy the above property. | Input: ['5bbbaabaaaaabbaabbb'] Output:['b bb a', 'a b a', 'a a a', 'ab b a', 'a bb b'] | [
2
] |
This is an easy version of the problem. The difference between the versions is that the string can be longer than in the easy version. You can only do hacks if both versions of the problem are passed.Kazimir Kazimirovich is a Martian gardener. He has a huge orchard of binary balanced apple trees.Recently Casimir decided to get himself three capybaras. The gardener even came up with their names and wrote them down on a piece of paper. The name of each capybara is a non-empty line consisting of letters "a" and "b".Denote the names of the capybaras by the lines a, b, and c. Then Casimir wrote the nonempty lines a, b, and c in a row without spaces. For example, if the capybara's name was "aba", "ab", and "bb", then the string the gardener wrote down would look like "abaabbb".The gardener remembered an interesting property: either the string b is lexicographically not smaller than the strings a and c at the same time, or the string b is lexicographically not greater than the strings a and c at the same time. In other words, either a <= b and c <= b are satisfied, or b <= a and b <= c are satisfied (or possibly both conditions simultaneously). Here <= denotes the lexicographic "less than or equal to" for strings. Thus, a <= b means that the strings must either be equal, or the string a must stand earlier in the dictionary than the string b. For a more detailed explanation of this operation, see "Notes" section.Today the gardener looked at his notes and realized that he cannot recover the names because they are written without spaces. He is no longer sure if he can recover the original strings a, b, and c, so he wants to find any triplet of names that satisfy the above property. | Input: ['5bbbaabaaaaabbaabbb'] Output:['b bb a', 'a b a', 'a a a', 'ab b a', 'a bb b'] | [
0
] |
ChthollyNotaSeniorious gives DataStructures a number axis with m distinct segments on it. Let f(l,r) be the number of ways to choose an even number of segments such that the union of them is exactly [l,r], and g(l,r) be the number of ways to choose an odd number of segments such that the union of them is exactly [l,r].ChthollyNotaSeniorious asked DataStructures q questions. In each query, ChthollyNotaSeniorious will give DataStructures two numbers l, r, and now he wishes that you can help him find the value f(l,r)-g(l,r) modulo 998\,244\,353 so that he wouldn't let her down. | Input: ['4 2', '1 3', '4 6', '2 4', '3 5', '1 4', '1 5', ''] Output:['1', '0', ''] | [
0
] |
This is the hard version of the problem. The only difference between the two versions is the constraint on n and x. You can make hacks only if both versions of the problem are solved.Little09 has been interested in magic for a long time, and it's so lucky that he meets a magician! The magician will perform n operations, each of them is one of the following three: 1\ x: Create a pig with x Health Points. 2\ x: Reduce the Health Point of all living pigs by x. 3: Repeat all previous operations. Formally, assuming that this is the i-th operation in the operation sequence, perform the first i-1 operations (including "Repeat" operations involved) in turn.A pig will die when its Health Point is less than or equal to 0. Little09 wants to know how many living pigs there are after all the operations. Please, print the answer modulo 998\,244\,353. | Input: ['4', '1 8', '2 3', '3', '3', ''] Output:['2'] | [
0,
4
] |
This is the easy version of the problem. The only difference between the two versions is the constraint on n and x. You can make hacks only if both versions of the problem are solved.Little09 has been interested in magic for a long time, and it's so lucky that he meets a magician! The magician will perform n operations, each of them is one of the following three: 1\ x: Create a pig with x Health Points. 2\ x: Reduce the Health Point of all living pigs by x. 3: Repeat all previous operations. Formally, assuming that this is the i-th operation in the operation sequence, perform the first i-1 operations (including "Repeat" operations involved) in turn.A pig will die when its Health Point is less than or equal to 0. Little09 wants to know how many living pigs there are after all the operations. Please, print the answer modulo 998\,244\,353. | Input: ['4', '1 8', '2 3', '3', '3', ''] Output:['2', ''] | [
0
] |
Cirno_9baka has a tree with n nodes. He is willing to share it with you, which means you can operate on it.Initially, there are two chess pieces on the node 1 of the tree. In one step, you can choose any piece, and move it to the neighboring node. You are also given an integer d. You need to ensure that the distance between the two pieces doesn't ever exceed d.Each of these two pieces has a sequence of nodes which they need to pass in any order, and eventually, they have to return to the root. As a curious boy, he wants to know the minimum steps you need to take. | Input: ['4 2', '1 2', '1 3', '2 4', '1 3', '1 4', ''] Output:['6'] | [
2
] |
ChthollyNotaSeniorious received a special gift from AquaMoon: n binary arrays of length m. AquaMoon tells him that in one operation, he can choose any two arrays and any position pos from 1 to m, and swap the elements at positions pos in these arrays.He is fascinated with this game, and he wants to find the minimum number of operations needed to make the numbers of 1s in all arrays the same. He has invited you to participate in this interesting game, so please try to find it!If it is possible, please output specific exchange steps in the format described in the output section. Otherwise, please output -1. | Input: ['33 41 1 1 00 0 1 01 0 0 14 31 0 00 1 10 0 10 0 02 20 00 1'] Output:['1', '2 1 1', '1', '4 2 2', '-1', ''] | [
0,
2
] |
Little09 and his friends are playing a game. There are n players, and the temperature value of the player i is i. The types of environment are expressed as 0 or 1. When two players fight in a specific environment, if its type is 0, the player with a lower temperature value in this environment always wins; if it is 1, the player with a higher temperature value in this environment always wins. The types of the n-1 environments form a binary string s with a length of n-1.If there are x players participating in the game, there will be a total of x-1 battles, and the types of the x-1 environments will be the first x-1 characters of s. While there is more than one player left in the tournament, choose any two remaining players to fight. The player who loses will be eliminated from the tournament. The type of the environment of battle i is s_i.For each x from 2 to n, answer the following question: if all players whose temperature value does not exceed x participate in the game, how many players have a chance to win? | Input: ['240014101'] Output:['1 1 3 ', '1 2 3 ', ''] | [
2
] |
Cirno_9baka has a paper tape with n cells in a row on it. As he thinks that the blank paper tape is too dull, he wants to paint these cells with m kinds of colors. For some aesthetic reasons, he thinks that the i-th color must be used exactly a_i times, and for every k consecutive cells, their colors have to be distinct. Help Cirno_9baka to figure out if there is such a way to paint the cells. | Input: ['212 6 21 1 1 1 1 712 6 22 2 2 2 2 2'] Output:['NO', 'YES', ''] | [
2,
3
] |
AquaMoon has a string a consisting of only 0 and 1. She wants to add + and - between all pairs of consecutive positions to make the absolute value of the resulting expression as small as possible. Can you help her? | Input: ['3211501101510001'] Output:['-', '+-++', '+++-', ''] | [
3
] |
You are given an undirected connected graph with n vertices and m edges. Each edge has an associated counter, initially equal to 0. In one operation, you can choose an arbitrary spanning tree and add any value v to all edges of this spanning tree. Determine if it's possible to make every counter equal to its target value x_i modulo prime p, and provide a sequence of operations that achieves it. | Input: ['3 3 101', '1 2 30', '2 3 40', '3 1 50', ''] Output:['3', '10 1 2', '20 1 3', '30 2 3'] | [
3
] |
Oh no, this wicked jury hides something from you again, and you need to guess it interactively. This time, you need to find an integer n. To do that, you can make at most 10 queries of the form "What is the k-th decimal digit of the product of all integers from 1 to n (also known as factorial and denoted as n!)?". | Input: ['2', '', '1', '', 'YES', '', '0', '', '2', '', 'YES', ''] Output:['', '? 0', '', '! 1', '', '? 0', '', '? 19997', '', '! 5982'] | [
0
] |
This is an interactive problem.After emigrating to another country, little Hanna came across the fact that playing "Hot and cold" became more difficult: she does not understand the hint phrases! You are to write a helping program for her.The playground where the game happens is a rectangle, and the treasure is hidden in some point with integer coordinates between 0 and 10^6, inclusive. Hanna visits several points with valid coordinates. If the visited point contains the hidden treasure, she receives the phrase "Found!" in the local language. Fortunately, the intonations allow her to recognize this phrase — in this problem it will be denoted by an exclamation mark.Otherwise, for each visited point except for the first one, Hanna receives a phrase in the local language stating whether she is now "Closer", "Further", or "At the same distance" from the treasure, compared to the previous point. The distances are measured in Euclidean metric. After the first visited point, in case of no treasure there, Hanna receives the phrase "Not found" in the local language.Your program must help Hanna find the treasure by visiting at most 64 points. | Input: ['', 'Tabilmadi', '', 'Daha yakin', '', 'Daha yakin', '', 'Sama distanco', '', 'Dalej', '', 'Znaydeno!'] Output:['500 200', '', '560 230', '', '566 240', '', '566 238', '', '30 239', '', '566 239'] | [
4
] |
Genie is taking part in an intellectual game. The game consists of n questions, and there are m participants numbered from 1 to m. Genie is the participant number 1.For each question i and participant j, it is known whether the participant will answer the question correctly or not.The goal of the game is to be the last participant staying in the game.The game is conducted as follows. First, all n questions get shuffled uniformly at random (all n! permutations are equally likely). Then, the questions are asked one by one. Each participant answers the question. If all participants still in the game answer the question correctly, or if all of them answer the question incorrectly, nothing happens. Otherwise, those participants who answer the question incorrectly lose and leave the game.After all n questions are asked, all participants who are still in the game are declared to be the winners.What is the probability that Genie will win the game? | Input: ['1 5', '11010', ''] Output:['1.0000000000000000', ''] | [
3
] |
Emma loves playing with blocks. She has several cubic blocks of the same size that are numbered with distinct integers written on them. She assembles towers from those blocks by stacking them vertically. A configuration of her game is a set of towers that she has assembled from the blocks. Emma can perform two kinds of operations on a configuration of towers: Split any tower with more than one block in it by taking any number of blocks from the top of the tower and moving them to a new tower keeping their order, so that the top block of the old tower becomes the top block of the new tower. As a result of this operation, the number of towers increases by one. Combine any two towers by moving blocks from one tower on top of the other tower in the same order. As a result of this operation, the number of towers decreases by one.Emma wants to stack all the blocks into a single tower so that all blocks come in order sorted by the numbers — from the block with the minimal number at the top to the block with the maximal number at the bottom. Emma wants to do as little of splitting and combining operations as possible. Your task is to find the minimal number of operations she has to make and output how many splits and combines are needed. | Input: ['2', '3 3 5 8', '2 9 2', ''] Output:['1 2', ''] | [
2
] |
Dora likes to play with dominoes. She takes n * m table, marks some cells as occupied, and then tries to fill all unoccupied cells with 2 * 1 dominoes. Her little brother Dani loves to play pranks on his older sister. So when she is away, he marks two more unoccupied cells as occupied. He wants to do it in such a way that it will be impossible to fill all unoccupied cells with dominoes.Help Dani to count the number of ways he can select these two cells. Since Dani can only count to one million, if this number of ways is x, output \min(x, 10^6). | Input: ['3 6', '...#..', '......', '#...##', ''] Output:['52', ''] | [
2
] |
There are n employees in the BinCoin company numbered from 1 to n. The subordination structure in this company is a rooted tree. In other words: There is one CEO in the company — the main boss. Each other employee has exactly one direct superior. There are no cycles in the subordination structure. Moreover, due to the inexplicable love of the CEO of BinCoin for all the binary stuff, the subordination structure in the company is a binary rooted tree. That means each employee is directly superior to exactly zero or two other employees.In the CEO's opinion, working in this company is almost as dangerous as in mines. So, employees should sign the waiver of claims sometimes. This process happens in the following way. Initially, CEO takes the journal, then recursively the following procedure is performed: If an employee that holds the journal does not have any subordinates, they sign the waiver in the journal and give it back to their superior. The procedure stops if that was the CEO, who has no superior. Otherwise they choose one of two of their direct subordinates uniformly at random and give the journal to one of them; when they get the journal back, they sign it; and then they give it to another direct subordinate; when they get it back again, they give it back to their superior. The procedure stops if that was the CEO, who has no superior. All random choices are independent.One day, the CEO realized that they could not remember the subordination tree. Fortunately, they have the journal with k records. Each record is a sequence of employees in the order they've signed in a journal.Help CEO restore the subordination tree. | Input: ['3 50', '1 2 3 1 2 3 3 2 1 1 2 3', '3 2 1 1 2 3 1 2 3 1 2 3', '1 2 3 3 2 1 1 2 3 3 2 1', '1 2 3 3 2 1 1 2 3 3 2 1', '1 2 3 1 2 3 3 2 1 1 2 3', '3 2 1 1 2 3 3 2 1 1 2 3', '1 2 3 3 2 1 1 2 3 1 2 3', '1 2 3 1 2 3 3 2 1 1 2 3', '3 2 1 3 2 1 1 2 3 3 2 1', '1 2 3 3 2 1 3 2 1 1 2 3', '1 2 3 3 2 1 1 2 3 3 2 1', '3 2 1 3 2 1 1 2 3 1 2 3', '3 2 1 3 2 1 '] Output:['2 -1 2 ', ''] | [
4
] |
Alice is a magician and she creates a new trick. She has n cards with different numbers from 1 to n written on them. First, she asks an audience member to shuffle the deck and put cards in a row. Let's say the i-th card from the left has the number a_i on it. Then Alice picks two permutations p and q. There is a restriction on p and q — permutations can't have fixed points. Which means \forall i: p_i!=i\ and\ q_i!=i.After permutations are chosen, Alice shuffles the cards according to them. Now the i-th card from the left is the card a[p[q[i]]. The trick is considered successful if i-th card from the left has the number i on it after the shuffles.Help Alice pick the permutations p and q or say it is not possible for the specific starting permutation a. | Input: ['422 131 2 342 1 4 355 1 4 2 3'] Output:['Impossible', 'Possible', '3 1 2', '2 3 1', 'Possible', '3 4 2 1', '3 4 2 1', 'Possible', '4 1 2 5 3', '3 1 4 5 2', ''] | [
3
] |
Monocarp is playing chess on one popular website. He has n opponents he can play with. The i-th opponent has rating equal to a_i. Monocarp's initial rating is x. Monocarp wants to raise his rating to the value y (y > x).When Monocarp is playing against one of the opponents, he will win if his current rating is bigger or equal to the opponent's rating. If Monocarp wins, his rating is increased by 1, otherwise it is decreased by 1. The rating of his opponent does not change.Monocarp wants to gain rating y playing as few games as possible. But he can't just grind it, playing against weak opponents. The website has a rule that you should play against all opponents as evenly as possible. Speaking formally, if Monocarp wants to play against an opponent i, there should be no other opponent j such that Monocarp has played more games against i than against j.Calculate the minimum possible number of games Monocarp needs to gain rating y or say it's impossible. Note that ratings of Monocarp's opponents don't change, while Monocarp's rating does change. | Input: ['37 2 103 1 9 2 5 20 87 1 103 1 9 2 5 20 85 10 12100 1 200 11 300'] Output:['20', '-1', '2', ''] | [
2,
3,
4
] |
You are given an array a consisting of n integers. The array is sorted if a_1 <= a_2 <= ... <= a_n.You want to make the array a sorted by applying the following operation exactly once: choose an integer x, then for every i \in [1, n], replace a_i by |a_i - x|. Find any value of x that will make the array sorted, or report that there is no such value. | Input: ['855 3 3 3 545 3 4 581 2 3 4 5 6 7 8610 5 4 3 2 133 3 1342 43 422100000000 99999999629613295 52036613 75100585 78027446 81409090 73215'] Output:['4', '-1', '0', '42', '2', '-1', '100000000', '40741153', ''] | [
3
] |
An array a consisting of k integers is strictly increasing if a_1 < a_2 < ... < a_k. For example, the arrays [1, 3, 5], [1, 2, 3, 4], [3, 5, 6] are strictly increasing; the arrays [2, 2], [3, 7, 5], [7, 4, 3], [1, 2, 2, 3] are not.For a strictly increasing array a of k elements, let's denote the characteristic as the number of different elements in the array [a_2 - a_1, a_3 - a_2, ..., a_k - a_{k-1}]. For example, the characteristic of the array [1, 3, 4, 7, 8] is 3 since the array [2, 1, 3, 1] contains 3 different elements: 2, 1 and 3.You are given two integers k and n (k <= n). Construct an increasing array of k integers from 1 to n with maximum possible characteristic. | Input: ['75 94 123 33 44 44 68 11'] Output:['1 3 4 7 8', '2 4 7 12', '1 2 3', '1 3 4', '1 2 3 4', '2 4 5 6', '1 2 3 5 6 7 8 11', ''] | [
2,
3
] |
You have a matrix 2 * 2 filled with distinct integers. You want your matrix to become beautiful. The matrix is beautiful if the following two conditions are satisfied: in each row, the first element is smaller than the second element; in each column, the first element is smaller than the second element. You can perform the following operation on the matrix any number of times: rotate it clockwise by 90 degrees, so the top left element shifts to the top right cell, the top right element shifts to the bottom right cell, and so on: Determine if it is possible to make the matrix beautiful by applying zero or more operations. | Input: ['61 35 78 103 48 104 36 19 27 54 21 24 3'] Output:['YES', 'YES', 'NO', 'YES', 'YES', 'NO', ''] | [
0
] |
Hossam gives you a sequence of integers a_1, \, a_2, \, ..., \, a_n of length n. Moreover, he will give you q queries of type (l, \, r). For each query, consider the elements a_l, \, a_{l + 1}, \, ..., \, a_r. Hossam wants to know the smallest number in this sequence, such that it occurs in this sequence an odd number of times.You need to compute the answer for each query before process the next query. | Input: ['5', '1 2 1 2 2', '6', '1 2', '0 2', '0 6', '0 5', '2 2', '3 7', ''] Output:['1', '2', '1', '0', '2', '2', ''] | [
4
] |
Hossam bought a new piece of ground with length n and width m, he divided it into an n \cdot m grid, each cell being of size 1*1.Since Hossam's name starts with the letter 'H', he decided to draw the capital letter 'H' by building walls of size 1*1 on some squares of the ground. Each square 1*1 on the ground is assigned a quality degree: perfect, medium, or bad.The process of building walls to form up letter 'H' has the following constraints: The letter must consist of one horizontal and two vertical lines. The vertical lines must not be in the same or neighboring columns. The vertical lines must start in the same row and end in the same row (and thus have the same length). The horizontal line should connect the vertical lines, but must not cross them. The horizontal line can be in any row between the vertical lines (not only in the middle), except the top and the bottom one. (With the horizontal line in the top row the letter looks like 'n', and in the bottom row like 'U'.) It is forbidden to build walls in cells of bad quality. You can use at most one square of medium quality. You can use any number of squares of perfect quality. Find the maximum number of walls that can be used to draw the letter 'H'.Check the note for more clarification. | Input: ['2 3', '#m.', '.#.', ''] Output:['0', ''] | [
0
] |
Hossam has an unweighted tree G with letters in vertices.Hossam defines s(v, \, u) as a string that is obtained by writing down all the letters on the unique simple path from the vertex v to the vertex u in the tree G.A string a is a subsequence of a string s if a can be obtained from s by deletion of several (possibly, zero) letters. For example, "dores", "cf", and "for" are subsequences of "codeforces", while "decor" and "fork" are not.A palindrome is a string that reads the same from left to right and from right to left. For example, "abacaba" is a palindrome, but "abac" is not.Hossam defines a sub-palindrome of a string s as a subsequence of s, that is a palindrome. For example, "k", "abba" and "abhba" are sub-palindromes of the string "abhbka", but "abka" and "cat" are not.Hossam defines a maximal sub-palindrome of a string s as a sub-palindrome of s, which has the maximal length among all sub-palindromes of s. For example, "abhbka" has only one maximal sub-palindrome — "abhba". But it may also be that the string has several maximum sub-palindromes: the string "abcd" has 4 maximum sub-palindromes.Help Hossam find the length of the longest maximal sub-palindrome among all s(v, \, u) in the tree G.Note that the sub-palindrome is a subsequence, not a substring. | Input: ['25abaca1 21 33 44 59caabadedb1 22 32 41 55 65 75 88 9'] Output:['3', '5', ''] | [
0
] |
Hossam has n trainees. He assigned a number a_i for the i-th trainee. A pair of the i-th and j-th (i \neq j) trainees is called successful if there is an integer x (x >=q 2), such that x divides a_i, and x divides a_j.Hossam wants to know if there is a successful pair of trainees.Hossam is very tired now, so he asks you for your help! | Input: ['2332 48 7314 5 9'] Output:['YES', 'NO', ''] | [
2,
3
] |
Hossam makes a big party, and he will invite his friends to the party.He has n friends numbered from 1 to n. They will be arranged in a queue as follows: 1, 2, 3, ..., n.Hossam has a list of m pairs of his friends that don't know each other. Any pair not present in this list are friends.A subsegment of the queue starting from the friend a and ending at the friend b is [a, a + 1, a + 2, ..., b]. A subsegment of the queue is called good when all pairs of that segment are friends.Hossam wants to know how many pairs (a, b) there are (1 <= a <= b <= n), such that the subsegment starting from the friend a and ending at the friend b is good. | Input: ['23 21 32 34 21 22 3'] Output:['4', '5', ''] | [
4
] |
Hossam woke up bored, so he decided to create an interesting array with his friend Hazem.Now, they have an array a of n positive integers, Hossam will choose a number a_i and Hazem will choose a number a_j.Count the number of interesting pairs (a_i, a_j) that meet all the following conditions: 1 <= i, j <= n; i \neq j; The absolute difference |a_i - a_j| must be equal to the maximum absolute difference over all the pairs in the array. More formally, |a_i - a_j| = \max_{1 <= p, q <= n} |a_p - a_q|. | Input: ['256 2 3 8 167 2 8 3 2 10'] Output:['2', '4', ''] | [
3
] |
Chiyuu has a bracket sequence^ s of length n. Let k be the minimum number of characters that Chiyuu has to remove from s to make s balanced^\ddagger.Now, Koxia wants you to count the number of ways to remove k characters from s so that s becomes balanced, modulo 998\,244\,353.Note that two ways of removing characters are considered distinct if and only if the set of indices removed is different.^ A bracket sequence is a string containing only the characters "(" and ")".^\ddagger A bracket sequence is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), (()(())) and the empty string are balanced, while )(, ((), and (()))( are not. | Input: ['())(()', ''] Output:['4', ''] | [
3
] |
Mari has three integers n, x, and y.Call an array a of n non-negative integers good if it satisfies the following conditions: a_1+a_2+...+a_n=x, and a_1 \, | \, a_2 \, | \, ... \, | \, a_n=y, where | denotes the bitwise OR operation. The score of a good array is the value of a_1 \oplus a_2 \oplus ... \oplus a_n, where \oplus denotes the bitwise XOR operation.Koxia wants you to find the total bitwise XOR of the scores of all good arrays. If there are no good arrays, output 0 instead. | Input: ['3 5 3', ''] Output:['2', ''] | [
3
] |
Imi has an undirected tree with n vertices where edges are numbered from 1 to n-1. The i-th edge connects vertices u_i and v_i. There are also k butterflies on the tree. Initially, the i-th butterfly is on vertex a_i. All values of a are pairwise distinct.Koxia plays a game as follows: For i = 1, 2, ..., n - 1, Koxia set the direction of the i-th edge as u_i \rightarrow v_i or v_i \rightarrow u_i with equal probability. For i = 1, 2, ..., n - 1, if a butterfly is on the initial vertex of i-th edge and there is no butterfly on the terminal vertex, then this butterfly flies to the terminal vertex. Note that operations are sequentially in order of 1, 2, ..., n - 1 instead of simultaneously. Koxia chooses two butterflies from the k butterflies with equal probability from all possible \frac{k(k-1)}{2} ways to select two butterflies, then she takes the distance^ between the two chosen vertices as her score. Now, Koxia wants you to find the expected value of her score, modulo 998\,244\,353^\ddagger.^ The distance between two vertices on a tree is the number of edges on the (unique) simple path between them.^\ddagger Formally, let M = 998\,244\,353. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 <= x < M and x \cdot q \equiv p \pmod{M}. | Input: ['3 2', '1 3', '1 2', '2 3', ''] Output:['748683266'] | [
3
] |
Joi has an array a of n positive integers. Koxia wants you to determine whether there exists a positive integer x > 0 such that \gcd(a_i+x,a_j+x)=1 for all 1 <=q i < j <=q n.Here \gcd(y, z) denotes the greatest common divisor (GCD) of integers y and z. | Input: ['235 7 1033 3 4'] Output:['YES', 'NO', ''] | [
0,
3
] |
Kiyora has n whiteboards numbered from 1 to n. Initially, the i-th whiteboard has the integer a_i written on it.Koxia performs m operations. The j-th operation is to choose one of the whiteboards and change the integer written on it to b_j.Find the maximum possible sum of integers written on the whiteboards after performing all m operations. | Input: ['43 21 2 34 52 31 23 4 51 110015 31 1 1 1 11000000000 1000000000 1000000000'] Output:['12', '9', '1', '3000000002', ''] | [
0,
2
] |
В этой версии задачи нужно найти 26 раскладов с различными значениями важности первого хода.Алиса и Боб решили сыграть в карточную игру «Девятка». Пожалуйста, внимательно прочитайте условие задачи, поскольку правила могут отличаться от известных вам.Для игры нужна стандартная колода из 36 карт — по девять карт (от шестёрки до туза) каждой из четырёх мастей (трефы, бубны, пики и черви). Карты по достоинству от младшей к старшей идут следующим образом: шестёрка, семёрка, восьмёрка, девятка, десятка, валет, дама, король, туз.Перед игрой колода перемешивается, и каждому игроку раздаётся по 18 карт. Карты нужно выкладывать из руки на стол по определённым правилам. Выигрывает игрок, который первым выложит все карты из своей руки.Игроки ходят по очереди. Ход игрока имеет один из следующих видов: выложить на стол из своей руки девятку любой масти; выложить на стол шестёрку, семёрку или восьмёрку любой масти, если на столе уже лежит карта той же масти достоинством на единицу выше; выложить на стол десятку, валета, даму, короля или туза любой масти, если на столе уже лежит карта той же масти достоинством на единицу ниже. Например, девятку пик можно выложить на стол в любой момент, для выкладывания семёрки треф необходимо наличие на столе восьмёрки треф, а для выкладывания туза червей необходимо наличие на столе короля червей.Если игрок не может выложить на стол ни одну карту из своей руки, то ход переходит к сопернику. Обратите внимание: нельзя пропустить ход просто так — всегда необходимо выложить карту на стол корректным образом, если это возможно.Помимо того, что каждый игрок стремится избавиться от карт в своей руке, Алиса и Боб также хотят, чтобы в конце игры в руке у их соперника карт осталось как можно больше, а в их руке — как можно меньше. Напомним, что игра заканчивается, как только один из игроков выкладывает на стол последнюю карту из своей руки.Результатом игры назовём совокупность из информации о том, кто из двух игроков выиграет при оптимальной игре, а также о том, сколько карт останется в руке у проигравшего.Пусть Алиса и Боб уже взяли в руки свои 18 карт каждый, но ещё не решили, кто из них будет ходить первым. Величиной важности первого хода для данного расклада назовём абсолютную разность между результатами игры в случае, если первой будет ходить Алиса, и в случае, если первым будет ходить Боб.Например, если в обоих случаях выиграет Боб, но в одном случае у Алисы останется 6 карт в руке в конце игры, а во втором — всего 2, то величина важности первого хода равна 4. Если же в одном случае выиграет Алиса и у Боба останется 5 карт в руке, а во втором случае выиграет Боб и у Алисы останется 3 карты в руке, то величина важности первого хода равна 8.Ребята хотят узнать, насколько разной бывает величина важности первого хода для разных раскладов. По заданному числу k <= 26 помогите им найти такие k раскладов, что величины важности первого хода для всех них — различные целые числа. | Input: ['2', ''] Output:['KS QD 8D QC 8S 8C JD 9H AC TH 9S 9D QH 7H 8H TS 7S 9C', '6D JS 7D KH QS TC AD AS KC 6C 7C TD AH KD 6S JC JH 6H', '', 'JC JS 8S TD JD KH 7D 9C KC TH QD 8D 7H TC KD 9H 8C 6D', '7S AC QH AD 8H TS 6H JH 6C AH 7C 6S 9D QC AS QS KS 9S', ''] | [
0
] |
В этой версии задачи игроки начинают играть не только на победу, но и на оптимизацию результата игры для них. Вводится понятие величины важности первого хода, и нужно найти 13 раскладов с различными значениями этой величины.Алиса и Боб решили сыграть в карточную игру «Девятка». Пожалуйста, внимательно прочитайте условие задачи, поскольку правила могут отличаться от известных вам.Для игры нужна стандартная колода из 36 карт — по девять карт (от шестёрки до туза) каждой из четырёх мастей (трефы, бубны, пики и черви). Карты по достоинству от младшей к старшей идут следующим образом: шестёрка, семёрка, восьмёрка, девятка, десятка, валет, дама, король, туз.Перед игрой колода перемешивается, и каждому игроку раздаётся по 18 карт. Карты нужно выкладывать из руки на стол по определённым правилам. Выигрывает игрок, который первым выложит все карты из своей руки.Игроки ходят по очереди. Ход игрока имеет один из следующих видов: выложить на стол из своей руки девятку любой масти; выложить на стол шестёрку, семёрку или восьмёрку любой масти, если на столе уже лежит карта той же масти достоинством на единицу выше; выложить на стол десятку, валета, даму, короля или туза любой масти, если на столе уже лежит карта той же масти достоинством на единицу ниже. Например, девятку пик можно выложить на стол в любой момент, для выкладывания семёрки треф необходимо наличие на столе восьмёрки треф, а для выкладывания туза червей необходимо наличие на столе короля червей.Если игрок не может выложить на стол ни одну карту из своей руки, то ход переходит к сопернику. Обратите внимание: нельзя пропустить ход просто так — всегда необходимо выложить карту на стол корректным образом, если это возможно.Помимо того, что каждый игрок стремится избавиться от карт в своей руке, Алиса и Боб также хотят, чтобы в конце игры в руке у их соперника карт осталось как можно больше, а в их руке — как можно меньше. Напомним, что игра заканчивается, как только один из игроков выкладывает на стол последнюю карту из своей руки.Результатом игры назовём совокупность из информации о том, кто из двух игроков выиграет при оптимальной игре, а также о том, сколько карт останется в руке у проигравшего.Пусть Алиса и Боб уже взяли в руки свои 18 карт каждый, но ещё не решили, кто из них будет ходить первым. Величиной важности первого хода для данного расклада назовём абсолютную разность между результатами игры в случае, если первой будет ходить Алиса, и в случае, если первым будет ходить Боб.Например, если в обоих случаях выиграет Боб, но в одном случае у Алисы останется 6 карт в руке в конце игры, а во втором — всего 2, то величина важности первого хода равна 4. Если же в одном случае выиграет Алиса и у Боба останется 5 карт в руке, а во втором случае выиграет Боб и у Алисы останется 3 карты в руке, то величина важности первого хода равна 8.Ребята хотят узнать, насколько разной бывает величина важности первого хода для разных раскладов. По заданному числу k <= 13 помогите им найти такие k раскладов, что величины важности первого хода для всех них — различные целые числа. | Input: ['2', ''] Output:['KS QD 8D QC 8S 8C JD 9H AC TH 9S 9D QH 7H 8H TS 7S 9C', '6D JS 7D KH QS TC AD AS KC 6C 7C TD AH KD 6S JC JH 6H', '', 'JC JS 8S TD JD KH 7D 9C KC TH QD 8D 7H TC KD 9H 8C 6D', '7S AC QH AD 8H TS 6H JH 6C AH 7C 6S 9D QC AS QS KS 9S', ''] | [
0
] |
В этой версии задачи нужно определить, кто выиграет в карточной игре для двух игроков в заданном раскладе при оптимальной игре обоих соперников.Алиса и Боб решили сыграть в карточную игру «Девятка». Пожалуйста, внимательно прочитайте условие задачи, поскольку правила могут отличаться от известных вам.Для игры нужна стандартная колода из 36 карт — по девять карт (от шестёрки до туза) каждой из четырёх мастей (трефы, бубны, пики и черви). Карты по достоинству от младшей к старшей идут следующим образом: шестёрка, семёрка, восьмёрка, девятка, десятка, валет, дама, король, туз.Перед игрой колода перемешивается, и каждому игроку раздаётся по 18 карт. Карты нужно выкладывать из руки на стол по определённым правилам. Выигрывает игрок, который первым выложит все карты из своей руки.Игроки ходят по очереди. Ход игрока имеет один из следующих видов: выложить на стол из своей руки девятку любой масти; выложить на стол шестёрку, семёрку или восьмёрку любой масти, если на столе уже лежит карта той же масти достоинством на единицу выше; выложить на стол десятку, валета, даму, короля или туза любой масти, если на столе уже лежит карта той же масти достоинством на единицу ниже. Например, девятку пик можно выложить на стол в любой момент, для выкладывания семёрки треф необходимо наличие на столе восьмёрки треф, а для выкладывания туза червей необходимо наличие на столе короля червей.Если игрок не может выложить на стол ни одну карту из своей руки, то ход переходит к сопернику. Обратите внимание: нельзя пропустить ход просто так — всегда необходимо выложить карту на стол корректным образом, если это возможно.Вам дан расклад карт в начале игры. Алиса будет ходить первой. Определите, кто первым избавится от всех своих карт и выиграет, если оба игрока будут пытаться победить и играть оптимально. | Input: ['JD 7S 9S JS 8S 9D 6D 8C 8D TH KS QD QH TD 6C AD KD AC', 'KH QC 9H 6H KC 9C JC TS 6S QS TC JH 7D 7H AS AH 7C 8H', ''] Output:['Alice', ''] | [
0
] |
В этой версии задачи n <= 50 и a_i <= 100.Вика за время работы в компании VK уже сделала n коммитов в системе контроля версий. i-й коммит был сделан в a_i-й день работы Вики в компании. В некоторые дни Вика могла сделать несколько коммитов, а в другие — не сделать ни одного.Вику интересуют такие отрезки подряд идущих дней, что в каждый из этих дней у неё есть хотя бы один коммит. Чем длиннее будет самый длинный такой отрезок, тем более продуктивным сотрудником она будет себя ощущать.Недавно Вика нашла способ подкрутить время любого коммита вперёд, но не более чем на сутки. Таким образом, i-й коммит теперь может быть «сделан» либо в a_i-й, либо в (a_i + 1)-й день. Время каждого коммита можно подкрутить независимо от других — в частности, можно как оставить всем коммитам исходное время, так и перенести все коммиты ровно на день вперёд.Найдите длину самого длинного возможного отрезка подряд идущих дней, в каждый из которых у Вики в профиле будет отображаться хотя бы один коммит, после возможной подкрутки времени некоторых коммитов. | Input: ['391 1 3 4 6 6 6 8 1061 2 3 4 5 6510 10 10 10 10'] Output:['5', '6', '2', ''] | [
0,
2
] |
В этой версии задачи размеры копируемых файлов не превышают 10^{10} байт.Вы копируете с одного сервера на другой n файлов размером a_1, a_2, ..., a_n байт. Файлы копируются последовательно в заданном порядке.При копировании вы видите два прогресс-бара: первый показывает процент скопированных данных в текущем файле, а второй — общий процент скопированных данных по всем n файлам. Оба процента отображаются округлёнными вниз до целого числа. Значения на прогресс-барах обновляются после копирования каждого байта.Формально, после копирования байта номер x из файла номер i первый прогресс-бар показывает \lfloor \frac{100 \cdot x}{a_i} \rfloor процентов, а второй — \lfloor \frac{100 \cdot (a_1 + a_2 + ... + a_{i - 1} + x)}{a_1 + a_2 + ... + a_n} \rfloor процентов. В самом начале копирования оба прогресс-бара показывают 0 процентов.Найдите все такие целые числа от 0 до 100 включительно, что существует момент времени, в который оба прогресс-бара одновременно показывают это число. Выведите эти числа в порядке возрастания. | Input: ['1', '6', ''] Output:['0', '16', '33', '50', '66', '83', '100', ''] | [
0,
3,
4
] |
В этой версии задачи размеры копируемых файлов не превышают 1000 байт.Вы копируете с одного сервера на другой n файлов размером a_1, a_2, ..., a_n байт. Файлы копируются последовательно в заданном порядке.При копировании вы видите два прогресс-бара: первый показывает процент скопированных данных в текущем файле, а второй — общий процент скопированных данных по всем n файлам. Оба процента отображаются округлёнными вниз до целого числа. Значения на прогресс-барах обновляются после копирования каждого байта.Формально, после копирования байта номер x из файла номер i первый прогресс-бар показывает \lfloor \frac{100 \cdot x}{a_i} \rfloor процентов, а второй — \lfloor \frac{100 \cdot (a_1 + a_2 + ... + a_{i - 1} + x)}{a_1 + a_2 + ... + a_n} \rfloor процентов. В самом начале копирования оба прогресс-бара показывают 0 процентов.Найдите все такие целые числа от 0 до 100 включительно, что существует момент времени, в который оба прогресс-бара одновременно показывают это число. Выведите эти числа в порядке возрастания. | Input: ['1', '6', ''] Output:['0', '16', '33', '50', '66', '83', '100', ''] | [
0,
3
] |
Колонна из n самокатов едет по узкой односторонней дороге в пункт Б. Самокаты пронумерованы от 1 до n. Для каждого самоката i известно, что текущее расстояние от него до пункта Б равно a_i метров. При этом a_1 < a_2 < ... < a_n, в частности, самокат 1 находится ближе всего к пункту Б, а самокат n — дальше всего.Самокат с номером i движется в сторону пункта Б со скоростью i метров в секунду (то есть чем ближе самокат в колонне к пункту Б, тем медленнее он едет). Так как дорога узкая, самокаты не могут обгонять друг друга. Более того, соседние самокаты в колонне должны соблюдать дистанцию хотя бы в 1 метр. Поэтому когда более быстрый самокат догоняет более медленный, более быстрому приходится дальше ехать со скоростью более медленного, причём на расстоянии в 1 метр от него.Определите, на каком расстоянии до пункта Б будет каждый самокат ровно через одну секунду. | Input: ['4', '20', '30', '50', '100', ''] Output:['19', '28', '47', '96', ''] | [
3
] |
You are given an array of positive integers a_1,a_2,...,a_n of length n. In one operation you can jump from index i to index j (1 <= i <= j <= n) by paying \min(a_i, a_{i + 1}, ..., a_j) \cdot (j - i)^2 eris.For all k from 1 to n, find the minimum number of eris needed to get from index 1 to index k. | Input: ['3', '2 1 3', ''] Output:['0 1 2 ', ''] | [
2
] |
Consider a permutation^ p of length 3n. Each time you can do one of the following operations: Sort the first 2n elements in increasing order. Sort the last 2n elements in increasing order. We can show that every permutation can be made sorted in increasing order using only these operations. Let's call f(p) the minimum number of these operations needed to make the permutation p sorted in increasing order.Given n, find the sum of f(p) over all (3n)! permutations p of size 3n.Since the answer could be very large, output it modulo a prime M.^ A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). | Input: ['1 100009067', ''] Output:['9', ''] | [
3
] |
You are given a permutation^ p of length n.In one operation, you can choose two indices 1 <= i < j <= n and swap p_i with p_j.Find the minimum number of operations needed to have exactly one inversion^\ddagger in the permutation.^ A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).^\ddagger The number of inversions of a permutation p is the number of pairs of indices (i, j) such that 1 <= i < j <= n and p_i > p_j. | Input: ['422 121 243 4 1 242 4 3 1'] Output:['0', '1', '3', '1', ''] | [
2
] |
You are given an array a of n integers.Find two permutations^ p and q of length n such that \max(p_i,q_i)=a_i for all 1 <=q i <=q n or report that such p and q do not exist.^ A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). | Input: ['31155 3 4 2 521 1'] Output:['YES', '1 ', '1 ', 'YES', '1 3 4 2 5 ', '5 2 3 1 4 ', 'NO', ''] | [
2
] |
You are given a permutation^ p of length n and a positive integer k <= n.In one operation, you: Choose k distinct elements p_{i_1}, p_{i_2}, ..., p_{i_k}. Remove them and then add them sorted in increasing order to the end of the permutation. For example, if p = [2,5,1,3,4] and k = 2 and you choose 5 and 3 as the elements for the operation, then [2, \color{red}{5}, 1, \color{red}{3}, 4] \rightarrow [2, 1, 4, \color{red}{3},\color{red}{5}].Find the minimum number of operations needed to sort the permutation in increasing order. It can be proven that it is always possible to do so.^ A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). | Input: ['43 21 2 33 13 1 24 21 3 2 44 22 3 1 4'] Output:['0', '1', '1', '2', ''] | [
2,
3
] |
You are given an integer k. Find the largest integer x, where 1 <= x < k, such that x! + (x - 1)!^ is a multiple of ^\ddagger k, or determine that no such x exists.^ y! denotes the factorial of y, which is defined recursively as y! = y \cdot (y-1)! for y >=q 1 with the base case of 0! = 1. For example, 5! = 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 \cdot 0! = 120.^\ddagger If a and b are integers, then a is a multiple of b if there exists an integer c such that a = b \cdot c. For example, 10 is a multiple of 5 but 9 is not a multiple of 6. | Input: ['436810'] Output:['2', '5', '7', '9', ''] | [
2,
3
] |
Algebra Flash 2.2 has just been released!Changelog: New gamemode! Thank you for the continued support of the game! Huh, is that it? Slightly disappointed, you boot up the game and click on the new gamemode. It says "Colored platforms".There are n platforms, numbered from 1 to n, placed one after another. There are m colors available in the game, numbered from 1 to m. The i-th platform is colored c_i.You start on the platform 1 and want to reach platform n. In one move, you can jump from some platform i to platforms i + 1 or i + 2.All platforms are initially deactivated (including platforms 1 and n). For each color j, you can pay x_j coins to activate all platforms of that color.You want to activate some platforms so that you could start on an activated platform 1, jump through some activated platforms and reach an activated platform n.What's the smallest amount of coins you can spend to achieve that? | Input: ['5 3', '1 3 2 3 1', '1 10 100', ''] Output:['11', ''] | [
0,
3
] |
2^n teams participate in a playoff tournament. The tournament consists of 2^n - 1 games. They are held as follows: in the first phase of the tournament, the teams are split into pairs: team 1 plays against team 2, team 3 plays against team 4, and so on (so, 2^{n-1} games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only 2^{n-1} teams remain. If only one team remains, it is declared the champion; otherwise, the second phase begins, where 2^{n-2} games are played: in the first one of them, the winner of the game "1 vs 2" plays against the winner of the game "3 vs 4", then the winner of the game "5 vs 6" plays against the winner of the game "7 vs 8", and so on. This process repeats until only one team remains. The skill level of the i-th team is p_i, where p is a permutation of integers 1, 2, ..., 2^n (a permutation is an array where each element from 1 to 2^n occurs exactly once).You are given a string s which consists of n characters. These characters denote the results of games in each phase of the tournament as follows: if s_i is equal to 0, then during the i-th phase (the phase with 2^{n-i} games), in each match, the team with the lower skill level wins; if s_i is equal to 1, then during the i-th phase (the phase with 2^{n-i} games), in each match, the team with the higher skill level wins. Let's say that an integer x is winning if it is possible to find a permutation p such that the team with skill x wins the tournament. Find all winning integers. | Input: ['3', '101', ''] Output:['4 5 6 7 '] | [
2,
3
] |
There are n block towers, numbered from 1 to n. The i-th tower consists of a_i blocks.In one move, you can move one block from tower i to tower j, but only if a_i > a_j. That move increases a_j by 1 and decreases a_i by 1. You can perform as many moves as you would like (possibly, zero).What's the largest amount of blocks you can have on the tower 1 after the moves? | Input: ['431 2 331 2 221 1000000000103 8 6 7 4 1 2 4 10 1'] Output:['3', '2', '500000001', '9', ''] | [
2
] |
For a sequence of integers [x_1, x_2, ..., x_k], let's define its decomposition as follows:Process the sequence from the first element to the last one, maintaining the list of its subsequences. When you process the element x_i, append it to the end of the first subsequence in the list such that the bitwise AND of its last element and x_i is greater than 0. If there is no such subsequence in the list, create a new subsequence with only one element x_i and append it to the end of the list of subsequences.For example, let's analyze the decomposition of the sequence [1, 3, 2, 0, 1, 3, 2, 1]: processing element 1, the list of subsequences is empty. There is no subsequence to append 1 to, so we create a new subsequence [1]; processing element 3, the list of subsequences is [[1]]. Since the bitwise AND of 3 and 1 is 1, the element is appended to the first subsequence; processing element 2, the list of subsequences is [[1, 3]]. Since the bitwise AND of 2 and 3 is 2, the element is appended to the first subsequence; processing element 0, the list of subsequences is [[1, 3, 2]]. There is no subsequence to append 0 to, so we create a new subsequence [0]; processing element 1, the list of subsequences is [[1, 3, 2], [0]]. There is no subsequence to append 1 to, so we create a new subsequence [1]; processing element 3, the list of subsequences is [[1, 3, 2], [0], [1]]. Since the bitwise AND of 3 and 2 is 2, the element is appended to the first subsequence; processing element 2, the list of subsequences is [[1, 3, 2, 3], [0], [1]]. Since the bitwise AND of 2 and 3 is 2, the element is appended to the first subsequence; processing element 1, the list of subsequences is [[1, 3, 2, 3, 2], [0], [1]]. The element 1 cannot be appended to any of the first two subsequences, but can be appended to the third one. The resulting list of subsequences is [[1, 3, 2, 3, 2], [0], [1, 1]].Let f([x_1, x_2, ..., x_k]) be the number of subsequences the sequence [x_1, x_2, ..., x_k] is decomposed into.Now, for the problem itself.You are given a sequence [a_1, a_2, ..., a_n], where each element is an integer from 0 to 3. Let a[i..j] be the sequence [a_i, a_{i+1}, ..., a_j]. You have to calculate \sum \limits_{i=1}^n \sum \limits_{j=i}^n f(a[i..j]). | Input: ['8', '1 3 2 0 1 3 2 1', ''] Output:['71', ''] | [
0,
4
] |
Let's name a pair of positive integers (x, y) lucky if the greatest common divisor of them is equal to 1 (\gcd(x, y) = 1).Let's define a chain induced by (x, y) as a sequence of pairs (x, y), (x + 1, y + 1), (x + 2, y + 2), ..., (x + k, y + k) for some integer k >= 0. The length of the chain is the number of pairs it consists of, or (k + 1).Let's name such chain lucky if all pairs in the chain are lucky.You are given n pairs (x_i, y_i). Calculate for each pair the length of the longest lucky chain induced by this pair. Note that if (x_i, y_i) is not lucky itself, the chain will have the length 0. | Input: ['4', '5 15', '13 37', '8 9', '10009 20000', ''] Output:['0', '1', '-1', '79', ''] | [
3
] |
Let's call a positive integer extremely round if it has only one non-zero digit. For example, 5000, 4, 1, 10, 200 are extremely round integers; 42, 13, 666, 77, 101 are not.You are given an integer n. You have to calculate the number of extremely round integers x such that 1 <= x <= n. | Input: ['594213100111'] Output:['9', '13', '10', '19', '19', ''] | [
0
] |
You are given a positive integer x.You can apply the following operation to the number: remove one occurrence of any digit in such a way that the resulting number does not contain any leading zeroes and is still a positive integer. For example, 10142 can be converted to 1142, 1042, 1012 or 1014 (note that 0142 is not a valid outcome); 10 can be converted to 1 (but not to 0 since it is not positive).Your task is to find the minimum positive integer that you can obtain from x if you can apply the aforementioned operation exactly k times. | Input: ['510000413370987654321666837494128578086523'] Output:['1', '1337', '321', '344128', '7052', ''] | [
2
] |
You are given an integer n.Your task is to find two positive (greater than 0) integers a and b such that a+b=n and the least common multiple (LCM) of a and b is the minimum among all possible values of a and b. If there are multiple answers, you can print any of them. | Input: ['429510'] Output:['1 1', '3 6', '1 4', '5 5', ''] | [
3
] |
There are n employees at Bersoft company, numbered from 1 to n. Each employee works on some days of the week and rests on the other days. You are given the lists of working days of the week for each employee.There are regular days and holidays. On regular days, only those employees work that have the current day of the week on their list. On holidays, no one works. You are provided with a list of days that are holidays. The days are numbered from 1 onwards, day 1 is Monday.The company receives k project offers they have to complete. The projects are numbered from 1 to k in the order of decreasing priority. Each project consists of multiple parts, where the i-th part must be completed by the a_i-th employee. The parts must be completed in order (i. e. the (i+1)-st part can only be started when the i-th part is completed). Each part takes the corresponding employee a day to complete.The projects can be worked on simultaneously. However, one employee can complete a part of only one project during a single day. If they have a choice of what project to complete a part on, they always go for the project with the highest priority (the lowest index).For each project, output the day that project will be completed on. | Input: ['3 5 4', '2 Saturday Sunday', '2 Tuesday Thursday', '4 Monday Wednesday Friday Saturday', '4 7 13 14 15', '5 1 1 3 3 2', '3 2 3 2', '5 3 3 3 1 1', '8 3 3 3 3 3 3 3 3', ''] Output:['25 9 27 27 ', ''] | [
0
] |
You are given a square grid with n rows and n columns, where each cell has a non-negative integer written in it. There is a chip initially placed at the top left cell (the cell with coordinates (1, 1)). You need to move the chip to the bottom right cell (the cell with coordinates (n, n)).In one step, you can move the chip to the neighboring cell, but: you can move only right or down. In other words, if the current cell is (x, y), you can move either to (x, y + 1) or to (x + 1, y). There are two special cases: if the chip is in the last column (cell (x, n)) and you're moving right, you'll teleport to the first column (to the cell (x, 1)); if the chip is in the last row (cell (n, y)) and you're moving down, you'll teleport to the first row (to the cell (1, y)). you cannot visit the same cell twice. The starting cell is counted visited from the beginning (so you cannot enter it again), and you can't leave the finishing cell once you visit it. Your total score is counted as the sum of numbers in all cells you have visited. What is the maximum possible score you can achieve? | Input: ['2', '1 2', '3 4', ''] Output:['8', ''] | [
2,
3
] |
There are no heroes in this problem. I guess we should have named it "To Zero".You are given two arrays a and b, each of these arrays contains n non-negative integers.Let c be a matrix of size n * n such that c_{i,j} = |a_i - b_j| for every i \in [1, n] and every j \in [1, n].Your goal is to transform the matrix c so that it becomes the zero matrix, i. e. a matrix where every element is exactly 0. In order to do so, you may perform the following operations any number of times, in any order: choose an integer i, then decrease c_{i,j} by 1 for every j \in [1, n] (i. e. decrease all elements in the i-th row by 1). In order to perform this operation, you pay 1 coin; choose an integer j, then decrease c_{i,j} by 1 for every i \in [1, n] (i. e. decrease all elements in the j-th column by 1). In order to perform this operation, you pay 1 coin; choose two integers i and j, then decrease c_{i,j} by 1. In order to perform this operation, you pay 1 coin; choose an integer i, then increase c_{i,j} by 1 for every j \in [1, n] (i. e. increase all elements in the i-th row by 1). When you perform this operation, you receive 1 coin; choose an integer j, then increase c_{i,j} by 1 for every i \in [1, n] (i. e. increase all elements in the j-th column by 1). When you perform this operation, you receive 1 coin. You have to calculate the minimum number of coins required to transform the matrix c into the zero matrix. Note that all elements of c should be equal to 0 simultaneously after the operations. | Input: ['3', '1 2 3', '2 2 2', ''] Output:['2', ''] | [
3
] |
There are n people (numbered from 1 to n) signed up for a doctor's appointment. The doctor has to choose in which order he will appoint these people. The i-th patient should be appointed among the first p_i people. There are also m restrictions of the following format: the i-th restriction is denoted by two integers (a_i, b_i) and means that the patient with the index a_i should be appointed earlier than the patient with the index b_i.For example, if n = 4, p = [2, 3, 2, 4], m = 1, a = [3] and b = [1], then the only order of appointment of patients that does not violate the restrictions is [3, 1, 2, 4]. For n =3, p = [3, 3, 3], m = 0, a = [] and b = [], any order of appointment is valid.For each patient, calculate the minimum position in the order that they can have among all possible orderings that don't violate the restrictions. | Input: ['4 1', '2 3 2 4', '3 1', ''] Output:['2 3 1 4 '] | [
2,
4
] |
Monocarp is playing a MMORPG. There are two commonly used types of currency in this MMORPG — gold coins and silver coins. Monocarp wants to buy a new weapon for his character, and that weapon costs n silver coins. Unfortunately, right now, Monocarp has no coins at all.Monocarp can earn gold coins by completing quests in the game. Each quest yields exactly one gold coin. Monocarp can also exchange coins via the in-game trading system. Monocarp has spent days analyzing the in-game economy; he came to the following conclusion: it is possible to sell one gold coin for a silver coins (i. e. Monocarp can lose one gold coin to gain a silver coins), or buy one gold coin for b silver coins (i. e. Monocarp can lose b silver coins to gain one gold coin).Now Monocarp wants to calculate the minimum number of quests that he has to complete in order to have at least n silver coins after some abuse of the in-game economy. Note that Monocarp can perform exchanges of both types (selling and buying gold coins for silver coins) any number of times. | Input: ['4100 25 309999997 25 5052 50 4849 50 1'] Output:['4', '400000', '1', '1', ''] | [
0,
3
] |
Monocarp wants to watch n videos. Each video is only one minute long, but its size may be arbitrary. The i-th video has the size a_i megabytes. All videos are published on the Internet. A video should be downloaded before it can be watched. Monocarp has poor Internet connection — it takes exactly 1 minute to download 1 megabyte of data, so it will require a_i minutes to download the i-th video.Monocarp's computer has a hard disk of m megabytes. The disk is used to store the downloaded videos. Once Monocarp starts the download of a video of size s, the s megabytes are immediately reserved on a hard disk. If there are less than s megabytes left, the download cannot be started until the required space is freed. Each single video can be stored on the hard disk, since a_i <= m for all i. Once the download is started, it cannot be interrupted. It is not allowed to run two or more downloads in parallel.Once a video is fully downloaded to the hard disk, Monocarp can watch it. Watching each video takes exactly 1 minute and does not occupy the Internet connection, so Monocarp can start downloading another video while watching the current one.When Monocarp finishes watching a video, he doesn't need it on the hard disk anymore, so he can delete the video, instantly freeing the space it occupied on a hard disk. Deleting a video takes negligible time.Monocarp wants to watch all n videos as quickly as possible. The order of watching does not matter, since Monocarp needs to watch all of them anyway. Please calculate the minimum possible time required for that. | Input: ['5 6', '1 2 3 4 5', ''] Output:['16', ''] | [
4
] |
Recently, Mishka started noticing that his keyboard malfunctions — maybe it's because he was playing rhythm games too much. Empirically, Mishka has found out that every other time he presses a key, it is registered as if the key was pressed twice. For example, if Mishka types text, the first time he presses a key, exactly one letter is printed; the second time he presses a key, two same letters are printed; the third time he presses a key, one letter is printed; the fourth time he presses a key, two same letters are printed, and so on. Note that the number of times a key was pressed is counted for the whole keyboard, not for each key separately. For example, if Mishka tries to type the word osu, it will be printed on the screen as ossu.You are given a word consisting of n lowercase Latin letters. You have to determine if it can be printed on Mishka's keyboard or not. You may assume that Mishka cannot delete letters from the word, and every time he presses a key, the new letter (or letters) is appended to the end of the word. | Input: ['44ossu2aa6addonn3qwe'] Output:['YES', 'NO', 'YES', 'NO', ''] | [
2
] |
The only difference between this problem and the other two versions is the maximum number of queries. In this version, you are allowed to ask at most \mathbf{20} queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem."Everybody! Doremy's Perfect Data Structure Class is about to start! Come and do your best if you want to have as much IQ as me!" In today's Data Structure class, Doremy is teaching everyone a powerful data structure — Doremy tree! Now she gives you a quiz to prove that you are paying attention in class.Given an array a of length m, Doremy tree supports the query Q(l,r,k), where 1 <=q l <=q r <=q m and 1 <=q k <=q m, which returns the number of distinct integers in the array <=ft[\lfloor\frac{a_l}{k} \rfloor, \lfloor\frac{a_{l+1}}{k} \rfloor, ..., \lfloor\frac{a_r}{k} \rfloor\right].Doremy has a secret permutation p of integers from 1 to n. You can make queries, in one query, you give 3 integers l,r,k (1 <=q l <=q r <=q n, 1 <=q k <=q n) and receive the value of Q(l,r,k) for the array p. Can you find the index y (1 <=q y <=q n) such that p_y=1 in at most \mathbf{20} queries?Note that the permutation p is fixed before any queries are made. | Input: ['5', '', '2', '', '2', '', '1', '', '3'] Output:['', '? 1 3 4', '', '? 3 5 3', '', '? 3 4 5', '', '? 3 5 2', '', '! 4'] | [
4
] |
The only difference between this problem and the other two versions is the maximum number of queries. In this version, you are allowed to ask at most \mathbf{25} queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem."Everybody! Doremy's Perfect Data Structure Class is about to start! Come and do your best if you want to have as much IQ as me!" In today's Data Structure class, Doremy is teaching everyone a powerful data structure — Doremy tree! Now she gives you a quiz to prove that you are paying attention in class.Given an array a of length m, Doremy tree supports the query Q(l,r,k), where 1 <=q l <=q r <=q m and 1 <=q k <=q m, which returns the number of distinct integers in the array <=ft[\lfloor\frac{a_l}{k} \rfloor, \lfloor\frac{a_{l+1}}{k} \rfloor, ..., \lfloor\frac{a_r}{k} \rfloor\right].Doremy has a secret permutation p of integers from 1 to n. You can make queries, in one query, you give 3 integers l,r,k (1 <=q l <=q r <=q n, 1 <=q k <=q n) and receive the value of Q(l,r,k) for the array p. Can you find the index y (1 <=q y <=q n) such that p_y=1 in at most \mathbf{25} queries?Note that the permutation p is fixed before any queries are made. | Input: ['5', '', '2', '', '2', '', '1', '', '3'] Output:['', '? 1 3 4', '', '? 3 5 3', '', '? 3 4 5', '', '? 3 5 2', '', '! 4'] | [
4
] |
The only difference between this problem and the other two versions is the maximum number of queries. In this version, you are allowed to ask at most \mathbf{30} queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem."Everybody! Doremy's Perfect Data Structure Class is about to start! Come and do your best if you want to have as much IQ as me!" In today's Data Structure class, Doremy is teaching everyone a powerful data structure — Doremy tree! Now she gives you a quiz to prove that you are paying attention in class.Given an array a of length m, Doremy tree supports the query Q(l,r,k), where 1 <=q l <=q r <=q m and 1 <=q k <=q m, which returns the number of distinct integers in the array <=ft[\lfloor\frac{a_l}{k} \rfloor, \lfloor\frac{a_{l+1}}{k} \rfloor, ..., \lfloor\frac{a_r}{k} \rfloor\right].Doremy has a secret permutation p of integers from 1 to n. You can make queries, in one query, you give 3 integers l,r,k (1 <=q l <=q r <=q n, 1 <=q k <=q n) and receive the value of Q(l,r,k) for the array p. Can you find the index y (1 <=q y <=q n) such that p_y=1 in at most \mathbf{30} queries?Note that the permutation p is fixed before any queries are made. | Input: ['5', '', '2', '', '2', '', '1', '', '3'] Output:['', '? 1 3 4', '', '? 3 5 3', '', '? 3 4 5', '', '? 3 5 2', '', '! 4'] | [
4
] |
Doremy has an edge-weighted tree with n vertices whose weights are integers between 1 and 10^9. She does \frac{n(n+1)}{2} experiments on it.In each experiment, Doremy chooses vertices i and j such that j <=q i and connects them directly with an edge with weight 1. Then, there is exactly one cycle (or self-loop when i=j) in the graph. Doremy defines f(i,j) as the sum of lengths of shortest paths from every vertex to the cycle.Formally, let \mathrm{dis}_{i,j}(x,y) be the length of the shortest path between vertex x and y when the edge (i,j) of weight 1 is added, and S_{i,j} be the set of vertices that are on the cycle when edge (i,j) is added. Then, f(i,j)=\sum_{x=1}^{n}<=ft(\min_{y\in S_{i,j}}\mathrm{dis}_{i,j}(x,y)\right). Doremy writes down all values of f(i,j) such that 1 <=q j <=q i <=q n, then goes to sleep. However, after waking up, she finds that the tree has gone missing. Fortunately, the values of f(i,j) are still in her notebook, and she knows which i and j they belong to. Given the values of f(i,j), can you help her restore the tree?It is guaranteed that at least one suitable tree exists. | Input: ['3', '7', '3 5', '0 2 8', ''] Output:['2 3 3', '1 2 2', ''] | [
0
] |
Doremy has two arrays a and b of n integers each, and an integer k.Initially, she has a number line where no integers are colored. She chooses a permutation p of [1,2,...,n] then performs n moves. On the i-th move she does the following: Pick an uncolored integer x on the number line such that either: x <=q a_{p_i}; or there exists a colored integer y such that y <=q a_{p_i} and x <=q y+b_{p_i}. Color integer x with color p_i. Determine if the integer k can be colored with color 1. | Input: ['64 165 38 1210 715 14 168 1210 715 15 34 1610 715 15 38 124 1615 15 38 1210 71 1000000000500000000 5000000002 10000000001 9999999991 1'] Output:['NO', 'YES', 'YES', 'YES', 'NO', 'YES', ''] | [
2
] |
Doremy has n+1 pegs. There are n red pegs arranged as vertices of a regular n-sided polygon, numbered from 1 to n in anti-clockwise order. There is also a blue peg of slightly smaller diameter in the middle of the polygon. A rubber band is stretched around the red pegs.Doremy is very bored today and has decided to play a game. Initially, she has an empty array a. While the rubber band does not touch the blue peg, she will: choose i (1 <=q i <=q n) such that the red peg i has not been removed; remove the red peg i; append i to the back of a. Doremy wonders how many possible different arrays a can be produced by the following process. Since the answer can be big, you are only required to output it modulo p. p is guaranteed to be a prime number. game with n=9 and a=[7,5,2,8,3,9,4] and another game with n=8 and a=[3,4,7,1,8,5,2] | Input: ['4 100000007', ''] Output:['16', ''] | [
3
] |
Doremy's new city is under construction! The city can be regarded as a simple undirected graph with n vertices. The i-th vertex has altitude a_i. Now Doremy is deciding which pairs of vertices should be connected with edges.Due to economic reasons, there should be no self-loops or multiple edges in the graph.Due to safety reasons, there should not be pairwise distinct vertices u, v, and w such that a_u <=q a_v <=q a_w and the edges (u,v) and (v,w) exist.Under these constraints, Doremy would like to know the maximum possible number of edges in the graph. Can you help her?Note that the constructed graph is allowed to be disconnected. | Input: ['442 2 3 165 2 3 1 5 2127 2 4 9 1 4 6 3 7 4 2 341000000 1000000 1000000 1000000'] Output:['3', '9', '35', '2', ''] | [
2
] |
"Everybody! Doremy's Perfect Math Class is about to start! Come and do your best if you want to have as much IQ as me!" In today's math class, Doremy is teaching everyone subtraction. Now she gives you a quiz to prove that you are paying attention in class.You are given a set S containing positive integers. You may perform the following operation some (possibly zero) number of times: choose two integers x and y from the set S such that x > y and x - y is not in the set S. add x-y into the set S. You need to tell Doremy the maximum possible number of integers in S if the operations are performed optimally. It can be proven that this number is finite. | Input: ['221 235 10 25'] Output:['2', '5', ''] | [
3
] |
Doremy has n buckets of paint which is represented by an array a of length n. Bucket i contains paint with color a_i. Let c(l,r) be the number of distinct elements in the subarray [a_l,a_{l+1},...,a_r]. Choose 2 integers l and r such that l <=q r and r-l-c(l,r) is maximized. | Input: ['751 3 2 2 451 2 3 4 542 1 2 132 3 322 21199 8 5 2 1 1 2 3 3'] Output:['2 4', '1 5', '1 4', '2 3', '1 2', '1 1', '3 9', ''] | [
2
] |
Let's call an ordered pair of nodes (u, v) in a directed graph unidirectional if u \neq v, there exists a path from u to v, and there are no paths from v to u.A directed graph is called p-reachable if it contains exactly p ordered pairs of nodes (u, v) such that u < v and u and v are reachable from each other. Find the minimum number of nodes required to create a p-reachable directed graph.Also, among all such p-reachable directed graphs with the minimum number of nodes, let G denote a graph which maximizes the number of unidirectional pairs of nodes. Find this number. | Input: ['3', ''] Output:['3 0', ''] | [
3
] |
You are given five integers n, i, j, x, and y. Find the number of bitonic permutations B, of the numbers 1 to n, such that B_i=x, and B_j=y. Since the answer can be large, compute it modulo 10^9+7.A bitonic permutation is a permutation of numbers, such that the elements of the permutation first increase till a certain index k, 2 <= k <= n-1, and then decrease till the end. Refer to notes for further clarification. | Input: ['73 1 3 2 33 2 3 3 24 3 4 3 15 2 5 2 45 3 4 5 49 3 7 8 620 6 15 8 17'] Output:['0', '1', '1', '1', '3', '0', '4788', ''] | [
3
] |
You are given an array a of n integers. You are allowed to perform the following operation on it as many times as you want (0 or more times): Choose 2 indices i,j where 1 <= i < j <= n and replace a_k for all i <=q k <=q j with |a_i - a_j| Print the maximum sum of all the elements of the final array that you can obtain in such a way. | Input: ['331 1 129 134 9 5'] Output:['3', '16', '18', ''] | [
0,
2
] |
To destroy humanity, The Monster Association sent n monsters to Earth's surface. The i-th monster has health h_i and power p_i.With his last resort attack, True Spiral Incineration Cannon, Genos can deal k damage to all monsters alive. In other words, Genos can reduce the health of all monsters by k (if k > 0) with a single attack. However, after every attack Genos makes, the monsters advance. With their combined efforts, they reduce Genos' attack damage by the power of the ^weakest monster ^\ddaggeralive. In other words, the minimum p_i among all currently living monsters is subtracted from the value of k after each attack.^The Weakest monster is the one with the least power.^\ddaggerA monster is alive if its health is strictly greater than 0.Will Genos be successful in killing all the monsters? | Input: ['36 718 5 13 9 10 12 7 2 1 2 63 45 5 54 4 43 22 1 31 1 1'] Output:['YES', 'NO', 'YES', ''] | [
0,
3,
4
] |
You are given an array a of length n. You can perform the following operation several (possibly, zero) times: Choose i, j, b: Swap the b-th digit in the binary representation of a_i and a_j. Find the maximum possible value of \max(a) - \min(a).In a binary representation, bits are numbered from right (least significant) to left (most significant). Consider that there are an infinite number of leading zero bits at the beginning of any binary representation.For example, swap the 0-th bit for 4=100_2 and 3=11_2 will result 101_2=5 and 10_2=2. Swap the 2-nd bit for 4=100_2 and 3=11_2 will result 000_2=0_2=0 and 111_2=7. Here, \max(a) denotes the maximum element of array a and \min(a) denotes the minimum element of array a.The binary representation of x is x written in base 2. For example, 9 and 6 written in base 2 are 1001 and 110, respectively. | Input: ['431 0 145 5 5 551 2 3 4 5720 85 100 41 76 49 36'] Output:['1', '0', '7', '125', ''] | [
2,
3
] |
You are given an array a consisting of n integers and an integer k.A pair (l,r) is good if there exists a sequence of indices i_1, i_2, ..., i_m such that i_1=l and i_m=r; i_j < i_{j+1} for all 1 <=q j < m; and |a_{i_j}-a_{i_{j+1}}| <=q k for all 1 <=q j < m. Find the number of pairs (l,r) (1 <=q l <=q r <=q n) that are good. | Input: ['43 01 1 14 24 8 6 86 47 2 5 8 3 820 23110 57 98 14 20 1 60 82 108 37 82 73 8 46 38 35 106 115 58 112'] Output:['6', '9', '18', '92', ''] | [
4
] |
Let us call an edge-weighted tree with n vertices numbered from 1 to n good if the weight of each edge is either 1 or -1 and for each vertex i, the product of the edge weights of all edges having i as one endpoint is -1.You are given a positive integer n. There are n^{n-2} \cdot 2^{n-1} distinct^ edge-weighted trees with n vertices numbered from 1 to n such that each edge is either 1 or -1. Your task is to find the sum of d(1,n)^\ddagger of all such trees that are good. Since the answer can be quite large, you only need to find it modulo 998\,244\,353.^ Two trees are considered to be distinct if either: there exists two vertices such that there is an edge between them in one of the trees, and not in the other. there exists two vertices such that there is an edge between them in both trees but the weight of the edge between them in one tree is different from the one in the other tree. Note that by Cayley's formula, the number of trees on n labeled vertices is n^{n-2}. Since we have n-1 edges, there are 2^{n-1} possible assignment of weights(weight can either be 1 or -1). That is why total number of distinct edge-weighted tree is n^{n-2} \cdot 2^{n-1}.^\ddagger d(u,v) denotes the sum of the weight of all edges on the unique simple path from u to v. | Input: ['2', ''] Output:['998244352', ''] | [
3
] |
A binary string^ b of odd length m is good if b_i is the median^\ddagger of b[1,i]^\S for all odd indices i (1 <=q i <=q m).For a binary string a of length k, a binary string b of length 2k-1 is an extension of a if b_{2i-1}=a_i for all i such that 1 <=q i <=q k. For example, 1001011 and 1101001 are extensions of the string 1001. String x=1011011 is not an extension of string y=1001 because x_3 \neq y_2. Note that there are 2^{k-1} different extensions of a.You are given a binary string s of length n. Find the sum of the number of good extensions over all prefixes of s. In other words, find \sum_{i=1}^{n} f(s[1,i]), where f(x) gives number of good extensions of string x. Since the answer can be quite large, you only need to find it modulo 998\,244\,353.^ A binary string is a string whose elements are either \mathtt{0} or \mathtt{1}.^\ddagger For a binary string a of length 2m-1, the median of a is the (unique) element that occurs at least m times in a.^\S a[l,r] denotes the string of length r-l+1 which is formed by the concatenation of a_l,a_{l+1},...,a_r in that order. | Input: ['6111021130109101101111371011011111011010000011011111111011111'] Output:['1', '1', '3', '3', '21', '365', ''] | [
3
] |
An array b is good if the sum of elements of b is even. You are given an array a consisting of n positive integers. In one operation, you can select an index i and change a_i := \lfloor \frac{a_i}{2} \rfloor. ^Find the minimum number of operations (possibly 0) needed to make a good. It can be proven that it is always possible to make a good.^ \lfloor x \rfloor denotes the floor function — the largest integer less than or equal to x. For example, \lfloor 2.7 \rfloor = 2, \lfloor \pi \rfloor = 3 and \lfloor 5 \rfloor =5. | Input: ['441 1 1 127 431 2 4115'] Output:['0', '2', '1', '4', ''] | [
2,
3
] |
This is the hard version of the problem. The only difference between the two versions is the constraint on n. You can make hacks only if all versions of the problem are solved.Let's call an array a of odd length 2m+1 (with m >= 1) bad, if element a_{m+1} is equal to the median of this array. In other words, the array is bad if, after sorting it, the element at m+1-st position remains the same.Let's call a permutation p of integers from 1 to n anti-median, if every its subarray of odd length >= 3 is not bad.You are already given values of some elements of the permutation. Find the number of ways to set unknown values to obtain an anti-median permutation. As this number can be very large, find it modulo 10^9+7. | Input: ['52-1 -13-1 -1 -141 2 3 46-1 -1 3 4 -1 -18-1 -1 -1 -1 -1 -1 -1 -1'] Output:['2', '4', '0', '1', '316', ''] | [
3
] |