question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: At least one of the chips at least once fell to the banned cell. At least once two chips were on the same cell. At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.
Input: ['3 12 2'] Output:['0']
[ 2 ]
Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.
Input: ['1'] Output:['1']
[ 2 ]
Let's assume that p and q are strings of positive length, called the container and the key correspondingly, string q only consists of characters 0 and 1. Let's take a look at a simple algorithm that extracts message s from the given container p:i = 0;j = 0;s = <>;while i is less than the length of the string p{ if q[j] == 1, then add to the right of string s character p[i]; increase variables i, j by one; if the value of the variable j equals the length of the string q, then j = 0; }In the given pseudocode i, j are integer variables, s is a string, '=' is an assignment operator, '==' is a comparison operation, '[]' is the operation of obtaining the string character with the preset index, '<>' is an empty string. We suppose that in all strings the characters are numbered starting from zero. We understand that implementing such algorithm is quite easy, so your task is going to be slightly different. You need to construct the lexicographically minimum key of length k, such that when it is used, the algorithm given above extracts message s from container p (otherwise find out that such key doesn't exist).
Input: ['abacabaaba6'] Output:['100001']
[ 2 ]
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
Input: ['6 1-1 -1 -1 8 -1-1 5 -1 -1-1 -1 3-1 -1-1'] Output:['5']
[ 3 ]
A student's life is fraught with complications. Some Berland University students know this only too well. Having studied for two years, they contracted strong antipathy towards the chairperson of some department. Indeed, the person in question wasn't the kindest of ladies to begin with: prone to reforming groups, banning automatic passes and other mean deeds. At last the students decided that she just can't get away with all this anymore...The students pulled some strings on the higher levels and learned that the next University directors' meeting is going to discuss n orders about the chairperson and accept exactly p of them. There are two values assigned to each order: ai is the number of the chairperson's hairs that turn grey if she obeys the order and bi β€” the displeasement of the directors if the order isn't obeyed. The students may make the directors pass any p orders chosen by them. The students know that the chairperson will obey exactly k out of these p orders. She will pick the orders to obey in the way that minimizes first, the directors' displeasement and second, the number of hairs on her head that turn grey.The students want to choose p orders in the way that maximizes the number of hairs on the chairperson's head that turn grey. If there are multiple ways to accept the orders, then the students are keen on maximizing the directors' displeasement with the chairperson's actions. Help them.
Input: ['5 3 25 65 81 34 34 11'] Output:['3 1 2 ']
[ 2 ]
β€” Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me? β€” Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai β€” some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart: The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible; the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same; and of course, the walk should be successful: there must be at least two trees in the woodland belt left. Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input: ['51 2 3 1 2'] Output:['8 11 ']
[ 0 ]
You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows: The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.Please output the maximum number of cake cells that the cakeminator can eat.
Input: ['3 4S.........S.'] Output:['8']
[ 0 ]
There are n cities on a two dimensional Cartesian plane. The distance between two cities is equal to the Manhattan distance between them (see the Notes for definition). A Hamiltonian cycle of the cities is defined as a permutation of all n cities. The length of this Hamiltonian cycle is defined as the sum of the distances between adjacent cities in the permutation plus the distance between the first and final city in the permutation. Please compute the longest possible length of a Hamiltonian cycle of the given cities.
Input: ['41 11 22 12 2'] Output:['6']
[ 3 ]
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n × n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.You would like to purify all n × n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.
Input: ['3.E.E.E.E.'] Output:['1 12 23 3']
[ 2 ]
Do you remember how Kai constructed the word "eternity" using pieces of ice as components?Little Sheldon plays with pieces of ice, each piece has exactly one digit between 0 and 9. He wants to construct his favourite number t. He realized that digits 6 and 9 are very similar, so he can rotate piece of ice with 6 to use as 9 (and vice versa). Similary, 2 and 5 work the same. There is no other pair of digits with similar effect. He called this effect "Digital Mimicry".Sheldon favourite number is t. He wants to have as many instances of t as possible. How many instances he can construct using the given sequence of ice pieces. He can use any piece at most once.
Input: ['4223454'] Output:['2']
[ 2 ]
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.Look at the input part of the statement, s is given in a special form.
Input: ['12561'] Output:['4']
[ 3 ]
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: Its elements are in increasing order. That is an inequality ai < aj holds for any two indices i, j (i < j). For any two indices i and j (i < j), aj must not be divisible by ai. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with n elements.
Input: ['3'] Output:['2 9 15']
[ 3 ]
Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≀ i ≀ j ≀ n) and flips all values ak for which their positions are in range [i, j] (that is i ≀ k ≀ j). Flip the value of x means to apply operation x = 1 - x.The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
Input: ['51 0 0 1 0'] Output:['4']
[ 0 ]
Piegirl found the red button. You have one last chance to change the inevitable end.The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2Β·i) modulo n or node (2Β·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once. Your task is to find any such order and print it. If there is no such order, print -1.
Input: ['2'] Output:['0 1 0']
[ 2 ]
Daniel is organizing a football tournament. He has come up with the following tournament format: In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers.
Input: ['3'] Output:['34']
[ 3, 4 ]
Fox Ciel has some flowers: r red flowers, g green flowers and b blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets: To make a "red bouquet", it needs 3 red flowers. To make a "green bouquet", it needs 3 green flowers. To make a "blue bouquet", it needs 3 blue flowers. To make a "mixing bouquet", it needs 1 red, 1 green and 1 blue flower. Help Fox Ciel to find the maximal number of bouquets she can make.
Input: ['3 6 9'] Output:['6']
[ 3 ]
Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule: either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before); or the girl in the dancing pair must dance for the first time. Help Fox Ciel to make a schedule that they can dance as many songs as possible.
Input: ['2 1'] Output:['21 12 1']
[ 2 ]
Fox Ciel has a board with n rows and n columns, there is one integer in each cell.It's known that n is an odd number, so let's introduce . Fox Ciel can do the following operation many times: she choose a sub-board with size x rows and x columns, then all numbers in it will be multiplied by -1.Return the maximal sum of numbers in the board that she can get by these operations.
Input: ['3-1 -1 1-1 1 -11 -1 -1'] Output:['9']
[ 2, 3 ]
Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has n cities connected by n - 1 undirected roads, and for any two cities there always exists a path between them.Fox Ciel needs to assign an officer to each city. Each officer has a rank β€” a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost.There are enough officers of each rank. But there is a special rule must obey: if x and y are two distinct cities and their officers have the same rank, then on the simple path between x and y there must be a city z that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer.Help Ciel to make a valid plan, and if it's impossible, output "Impossible!".
Input: ['41 21 31 4'] Output:['A B B B']
[ 2 ]
Fox Ciel is playing a card game with her friend Jiro.Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.Now is Ciel's battle phase, Ciel can do the following operation many times: Choose one of her cards X. This card mustn't be chosen before. If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then: If Y's position is Attack, then (X's strength)  β‰₯  (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength). If Y's position is Defense, then (X's strength)  >  (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage. Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.
Input: ['2 3ATK 2000DEF 1700250025002500'] Output:['3000']
[ 2 ]
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all: 'U': go up, (x, y)  →  (x, y+1); 'D': go down, (x, y)  →  (x, y-1); 'L': go left, (x, y)  →  (x-1, y); 'R': go right, (x, y)  →  (x+1, y). The robot will do the operations in s from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in (a, b).
Input: ['2 2RU'] Output:['Yes']
[ 3, 4 ]
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not.You're given a number. Determine if it is a magic number or not.
Input: ['114114'] Output:['YES']
[ 0, 2 ]
A substring of a string is a contiguous subsequence of that string. So, string bca is substring of string abcabc, but string cc is not.A repeating block is a string formed by concatenating some string with itself. So, string abcabc is a repeating block, but strings abcabd, ababab are not.You've got a sequence of Latin characters (string). At each step you find the shortest substring that is a repeating block, if there exists more than one you must choose the leftmost. As the substring is of form XX (X β€” some string) you replace this substring with X, in other words you delete one of the X substrings in the substring. You repeat this process until there remains no repeating block in the string. How would the final string looks like? Look at the sample explanation to understand the statement more precise.
Input: ['abccabc'] Output:['abc']
[ 2 ]
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2n members and coincidentally Natalia Fan Club also has 2n members. Each member of MDC is assigned a unique id i from 0 to 2n - 1. The same holds for each member of NFC.One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers (a, b) such that member a from MDC dances with member b from NFC.The complexity of a pairs' assignment is the number of pairs of dancing pairs (a, b) and (c, d) such that a < c and b > d.You are given a binary number of length n named x. We know that member i from MDC dances with member from NFC. Your task is to calculate the complexity of this assignment modulo 1000000007 (109 + 7).Expression denotes applying Β«XORΒ» to numbers x and y. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as Β«^Β», in Pascal β€” Β«xorΒ».
Input: ['11'] Output:['6']
[ 3 ]
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the following sequence of numbers: firstly all odd integers from 1 to n (in ascending order), then all even integers from 1 to n (also in ascending order). Help our hero to find out which number will stand at the position number k.
Input: ['10 3'] Output:['5']
[ 3 ]
It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) β€” one ant in each direction. No other ant movements will happen. Ants never interfere with each other.Scientists have put a colony of n ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.
Input: ['1 30 10 00 -1'] Output:['010']
[ 0 ]
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, (x + y).What is the minimum number of such operations one has to perform in order to make the given pair of integers m-perfect?
Input: ['1 2 5'] Output:['2']
[ 0 ]
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
Input: ['5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5'] Output:['1232850']
[ 3 ]
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
Input: ['5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5'] Output:['1232850']
[ 3 ]
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
Input: ['5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5'] Output:['1232850']
[ 0 ]
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for n = 5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.
Input: ['51 2 2 1 2'] Output:['120']
[ 3 ]
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for n = 5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.
Input: ['51 2 2 1 2'] Output:['120']
[ 0 ]
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input: ['6 12 0 4 0 6 0'] Output:['246']
[ 0 ]
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure: if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively); if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code; if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits. The length of the safe code coincides with the length of the hint. For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input: ['AJ'] Output:['81']
[ 3 ]
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure: if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively); if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code; if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits. The length of the safe code coincides with the length of the hint. For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input: ['AJ'] Output:['81']
[ 2 ]
Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.
Input: ['41 12 23 34 4'] Output:['4']
[ 0 ]
Sereja placed n points on a plane. Now Sereja wants to place on the plane two straight lines, intersecting at a right angle, so that one of the straight lines intersect the Ox axis at an angle of 45 degrees and the maximum distance from the points to the straight lines were minimum. In this problem we consider the distance between points (x1, y1) and (x2, y2) equal |x1 - x2| + |y1 - y2|. The distance between the point and the straight lines is the minimum distance from the point to some point belonging to one of the lines.Help Sereja, find the maximum distance from the points to the optimally located straight lines.
Input: ['40 02 00 22 2'] Output:['0.000000000000000']
[ 4 ]
Let's introduce the designation , where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc.We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, strings ab and aсba can be obtained from string xacbac, and strings bx and aaa cannot be obtained from it.Sereja has two strings, w = [a, b] and q = [c, d]. He wants to find such maximum integer p (p > 0), that [q, p] can be obtained from string w.
Input: ['10 3ababbab'] Output:['3']
[ 4 ]
Ilya has recently taken up archaeology. He's recently found two numbers, written in the m-based notation. Each of the found numbers consisted of exactly n digits. Ilya immediately started looking for information about those numbers. He learned that the numbers are part of a cyphered code and the one who can decypher it can get the greatest treasure.After considerable research Ilya understood that to decypher the code, he should do the following: Rearrange digits in the first number in some manner. Similarly, rearrange digits in the second number in some manner. As a result of this operation, the numbers can get leading zeroes. Add numbers, digit by digit, modulo m. In other words, we need to get the third number of length n, each digit of the number is the sum of the respective numbers of the found numbers. For example, suppose there are two numbers recorded in the ternary notation, 001210 and 012111, then if you add them to each other digit by digit modulo 3, you will get number 010021. The key to the code is the maximum possible number that can be obtained in the previous step. Help Ilya, find the key to the code.
Input: ['4 75 4 3 25 6 5 4'] Output:['6 4 2 1 ']
[ 2 ]
Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.He's got a square 2n × 2n-sized matrix and 4n integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that the beauty of the resulting matrix with numbers is maximum.The beauty of a 2n × 2n-sized matrix is an integer, obtained by the following algorithm: Find the maximum element in the matrix. Let's denote it as m. If n = 0, then the beauty of the matrix equals m. Otherwise, a matrix can be split into 4 non-intersecting 2n - 1 × 2n - 1-sized submatrices, then the beauty of the matrix equals the sum of number m and other four beauties of the described submatrices. As you can see, the algorithm is recursive.Help Ilya, solve the problem and print the resulting maximum beauty of the matrix.
Input: ['113'] Output:['13']
[ 2 ]
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
Input: ['1 2 1 2'] Output:['0.666666666667']
[ 3 ]
While learning Computational Geometry, Tiny is simultaneously learning a useful data structure called segment tree or interval tree. He has scarcely grasped it when comes out a strange problem:Given an integer sequence a1, a2, ..., an. You should run q queries of two types: Given two integers l and r (1 ≀ l ≀ r ≀ n), ask the sum of all elements in the sequence al, al + 1, ..., ar. Given two integers l and r (1 ≀ l ≀ r ≀ n), let each element x in the sequence al, al + 1, ..., ar becomes x3. In other words, apply an assignments al = al3, al + 1 = al + 13, ..., ar = ar3. For every query of type 1, output the answer to it.Tiny himself surely cannot work it out, so he asks you for help. In addition, Tiny is a prime lover. He tells you that because the answer may be too huge, you should only output it modulo 95542721 (this number is a prime number).
Input: ['81 2 3 4 5 6 7 851 2 52 2 51 2 52 3 61 4 7'] Output:['142242215492']
[ 3 ]
Rainbow built h cells in a row that are numbered from 1 to h from left to right. There are n cells with treasure. We call each of these n cells "Treasure Cell". The i-th "Treasure Cell" is the ai-th cell and the value of treasure in it is ci dollars.Then, Freda went in the first cell. For now, she can go just k cells forward, or return to the first cell. That means Freda was able to reach the 1st, (k + 1)-th, (2Β·k + 1)-th, (3Β·k + 1)-th cells and so on.Then Rainbow gave Freda m operations. Each operation is one of the following three types: Add another method x: she can also go just x cells forward at any moment. For example, initially she has only one method k. If at some moment she has methods a1, a2, ..., ar then she can reach all the cells with number in form , where vi β€” some non-negative integer. Reduce the value of the treasure in the x-th "Treasure Cell" by y dollars. In other words, to apply assignment cx = cx - y. Ask the value of the most valuable treasure among the cells Freda can reach. If Freda cannot reach any cell with the treasure then consider the value of the most valuable treasure equal to 0, and do nothing. Otherwise take the most valuable treasure away. If several "Treasure Cells" have the most valuable treasure, take the "Treasure Cell" with the minimum number (not necessarily with the minimum number of cell). After that the total number of cells with a treasure is decreased by one. As a programmer, you are asked by Freda to write a program to answer each query.
Input: ['10 3 5 25 507 608 1002 2 531 333'] Output:['5510050']
[ 0 ]
Information technologies are developing and are increasingly penetrating into all spheres of human activity. Incredible as it is, the most modern technology are used in farming!A large farm has a meadow with grazing sheep. Overall there are n sheep and each of them contains a unique number from 1 to n β€” because the sheep need to be distinguished and you need to remember information about each one, and they are so much alike! The meadow consists of infinite number of regions numbered from 1 to infinity. It's known that sheep i likes regions from li to ri.There are two shepherds taking care of the sheep: First and Second. First wakes up early in the morning and leads the sheep graze on the lawn. Second comes in the evening and collects all the sheep.One morning, First woke up a little later than usual, and had no time to lead the sheep graze on the lawn. So he tied together every two sheep if there is a region they both like. First thought that it would be better β€” Second would have less work in the evening, because sheep won't scatter too much, being tied to each other!In the evening Second came on the lawn, gathered the sheep and tried to line them up in a row. But try as he might, the sheep wouldn't line up as Second want! Second had neither the strength nor the ability to untie the sheep so he left them as they are, but with one condition: he wanted to line up the sheep so that the maximum distance between two tied sheep was as small as possible. The distance between the sheep is the number of sheep in the ranks that are between these two.Help Second find the right arrangement.
Input: ['31 35 72 4'] Output:['1 3 2']
[ 2, 4 ]
Professional sport is more than hard work. It also is the equipment, designed by top engineers. As an example, let's take tennis. Not only should you be in great shape, you also need an excellent racket! In this problem your task is to contribute to the development of tennis and to help to design a revolutionary new concept of a racket!The concept is a triangular racket. Ant it should be not just any triangle, but a regular one. As soon as you've chosen the shape, you need to stretch the net. By the time you came the rocket had n holes drilled on each of its sides. The holes divide each side into equal n + 1 parts. At that, the m closest to each apex holes on each side are made for better ventilation only and you cannot stretch the net through them. The next revolutionary idea as to stretch the net as obtuse triangles through the holes, so that for each triangle all apexes lay on different sides. Moreover, you need the net to be stretched along every possible obtuse triangle. That's where we need your help β€” help us to count the number of triangles the net is going to consist of.Two triangles are considered to be different if their pictures on the fixed at some position racket are different.
Input: ['3 0'] Output:['9']
[ 0 ]
You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine.We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly n memory clusters, the i-th cluster consists of ai cells. You need to find memory for m arrays in your program. The j-th array takes 2bj consecutive memory cells. There possibly isn't enough memory for all m arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays.
Input: ['5 38 4 3 2 23 2 2'] Output:['2']
[ 2, 4 ]
People like to be fit. That's why many of them are ready to wake up at dawn, go to the stadium and run. In this problem your task is to help a company design a new stadium. The city of N has a shabby old stadium. Many people like it and every morning thousands of people come out to this stadium to run. The stadium can be represented as a circle, its length is exactly l meters with a marked start line. However, there can't be simultaneous start in the morning, so exactly at 7, each runner goes to his favorite spot on the stadium and starts running from there. Note that not everybody runs in the same manner as everybody else. Some people run in the clockwise direction, some of them run in the counter-clockwise direction. It mostly depends on the runner's mood in the morning, so you can assume that each running direction is equiprobable for each runner in any fixed morning. The stadium is tiny and is in need of major repair, for right now there only is one running track! You can't get too playful on a single track, that's why all runners keep the same running speed β€” exactly 1 meter per a time unit. Nevertheless, the runners that choose different directions bump into each other as they meet. The company wants to design a new stadium, but they first need to know how bad the old one is. For that they need the expectation of the number of bumpings by t time units after the running has begun. Help the company count the required expectation. Note that each runner chooses a direction equiprobably, independently from the others and then all runners start running simultaneously at 7 a.m. Assume that each runner runs for t time units without stopping. Consider the runners to bump at a certain moment if at that moment they found themselves at the same point in the stadium. A pair of runners can bump more than once.
Input: ['2 5 10 2'] Output:['0.2500000000']
[ 3, 4 ]
A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13.In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program.
Input: ['10 43 33 14 19 2'] Output:['22 3 ']
[ 2 ]
Olya has got a directed non-weighted graph, consisting of n vertexes and m edges. We will consider that the graph vertexes are indexed from 1 to n in some manner. Then for any graph edge that goes from vertex v to vertex u the following inequation holds: v < u.Now Olya wonders, how many ways there are to add an arbitrary (possibly zero) number of edges to the graph so as the following conditions were met: You can reach vertexes number i + 1, i + 2, ..., n from any vertex number i (i < n). For any graph edge going from vertex v to vertex u the following inequation fulfills: v < u. There is at most one edge between any two vertexes. The shortest distance between the pair of vertexes i, j (i < j), for which j - i ≀ k holds, equals j - i edges. The shortest distance between the pair of vertexes i, j (i < j), for which j - i > k holds, equals either j - i or j - i - k edges. We will consider two ways distinct, if there is the pair of vertexes i, j (i < j), such that first resulting graph has an edge from i to j and the second one doesn't have it.Help Olya. As the required number of ways can be rather large, print it modulo 1000000007 (109 + 7).
Input: ['7 8 21 22 33 43 64 54 75 66 7'] Output:['2']
[ 3 ]
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b β‰₯ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v β‰₯ 0). Help Ivan, find the required quantity of numbers.
Input: ['40 1 1 1'] Output:['0']
[ 2 ]
A continued fraction of height n is a fraction of form . You are given two rational numbers, one is represented as and the other one is represented as a finite fraction of height n. Check if they are equal.
Input: ['9 422 4'] Output:['YES']
[ 0, 3 ]
Unfortunately, Vasya can only sum pairs of integers (a, b), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4.Vasya has a set of k distinct non-negative integers d1, d2, ..., dk.Vasya wants to choose some integers from this set so that he could sum any two chosen numbers. What maximal number of integers can he choose in the required manner?
Input: ['4100 10 1 0'] Output:['40 1 10 100 ']
[ 0 ]
Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February.Look at the sample to understand what borders are included in the aswer.
Input: ['1900:01:012038:12:31'] Output:['50768']
[ 0 ]
In mathematics, the Pythagorean theorem β€” is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states: In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle). The theorem can be written as an equation relating the lengths of the sides a, b and c, often called the Pythagorean equation:a2 + b2 = c2where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Given n, your task is to count how many right-angled triangles with side-lengths a, b and c that satisfied an inequality 1 ≀ a ≀ b ≀ c ≀ n.
Input: ['5'] Output:['1']
[ 0, 3 ]
Imagine a real contest or exam of n participants. Every participant will get a particular score. We can predict the standings board more or less, if we do some statistics on their previous performance. Let's say the score of the participants will be uniformly distributed in interval [li, ri] (the score can be a real number). Can you predict the standings board according to these data? In other words you should say for each participant the probability that he gets some fixed place in the scoreboard. The participants are sorted by increasing of their scores in the scoreboard. So, the participant with the largest score gets the last place.
Input: ['21 64 9'] Output:['0.9200000000 0.080 0.080 0.9200000000 ']
[ 3 ]
Bike is a smart boy who loves math very much. He invented a number called "Rotatable Number" inspired by 142857. As you can see, 142857 is a magic number because any of its rotatings can be got by multiplying that number by 1, 2, ..., 6 (numbers from one to number's length). Rotating a number means putting its last several digit into first. For example, by rotating number 12345 you can obtain any numbers: 12345, 51234, 45123, 34512, 23451. It's worth mentioning that leading-zeroes are allowed. So both 4500123 and 0123450 can be obtained by rotating 0012345. You can see why 142857 satisfies the condition. All of the 6 equations are under base 10. 142857Β·1 = 142857; 142857Β·2 = 285714; 142857Β·3 = 428571; 142857Β·4 = 571428; 142857Β·5 = 714285; 142857Β·6 = 857142. Now, Bike has a problem. He extends "Rotatable Number" under any base b. As is mentioned above, 142857 is a "Rotatable Number" under base 10. Another example is 0011 under base 2. All of the 4 equations are under base 2. 0011Β·1 = 0011; 0011Β·10 = 0110; 0011Β·11 = 1001; 0011Β·100 = 1100. So, he wants to find the largest b (1 < b < x) so that there is a positive "Rotatable Number" (leading-zeroes allowed) of length n under base b.Note that any time you multiply a rotatable number by numbers from 1 to its length you should get a rotating of that number.
Input: ['6 11'] Output:['10']
[ 3 ]
You have been given n distinct integers a1, a2, ..., an. You can remove at most k of them. Find the minimum modular m (m > 0), so that for every pair of the remaining integers (ai, aj), the following unequality holds: .
Input: ['7 00 2 3 6 7 12 18'] Output:['13']
[ 0, 3 ]
You are given a rectangle grid. That grid's size is n × m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β€” a pair of integers (x, y) (0 ≀ x ≀ n, 0 ≀ y ≀ m).Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 ≀ x1 ≀ x ≀ x2 ≀ n, 0 ≀ y1 ≀ y ≀ y2 ≀ m, .The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers. If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input: ['9 9 5 5 2 1'] Output:['1 3 9 7']
[ 3 ]
Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not.A permutation triple of permutations of length n (a, b, c) is called a Lucky Permutation Triple if and only if . The sign ai denotes the i-th element of permutation a. The modular equality described above denotes that the remainders after dividing ai + bi by n and dividing ci by n are equal.Now, he has an integer n and wants to find a Lucky Permutation Triple. Could you please help him?
Input: ['5'] Output:['1 4 3 2 01 0 2 4 32 4 0 1 3']
[ 3 ]
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
Input: ['1 22 81 16'] Output:['11']
[ 4 ]
Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (xi, yi) of the plane. As the player visits station number i, he increases the current time on his timer by ai. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow.A player spends dΒ·dist time units to move between stations, where dist is the distance the player has covered and d is some constant. The distance between stations i and j is determined as |xi - xj| + |yi - yj|.Initially, the player is at station number 1, and the player has strictly more than zero and strictly less than one units of time. At station number 1 one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units).Now Yaroslav is wondering, how much money he needs to get to station n. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small.
Input: ['3 100010000 00 10 3'] Output:['2000']
[ 4 ]
In a far away galaxy there is war again. The treacherous Republic made k precision strikes of power ai on the Empire possessions. To cope with the republican threat, the Supreme Council decided to deal a decisive blow to the enemy forces. To successfully complete the conflict, the confrontation balance after the blow should be a positive integer. The balance of confrontation is a number that looks like , where p = n! (n is the power of the Imperial strike), . After many years of war the Empire's resources are low. So to reduce the costs, n should be a minimum positive integer that is approved by the commanders.Help the Empire, find the minimum positive integer n, where the described fraction is a positive integer.
Input: ['21000 1000'] Output:['2000']
[ 3, 4 ]
Vitaly is a very weird man. He's got two favorite digits a and b. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits a and b. Vitaly calls a good number excellent, if the sum of its digits is a good number.For example, let's say that Vitaly's favourite digits are 1 and 3, then number 12 isn't good and numbers 13 or 311 are. Also, number 111 is excellent and number 11 isn't. Now Vitaly is wondering, how many excellent numbers of length exactly n are there. As this number can be rather large, he asks you to count the remainder after dividing it by 1000000007 (109 + 7).A number's length is the number of digits in its decimal representation without leading zeroes.
Input: ['1 3 3'] Output:['1']
[ 0 ]
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
Input: ['3 0'] Output:['3 2 1 ']
[ 0 ]
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero ( < 0). The product of all numbers in the second set is greater than zero ( > 0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.
Input: ['3-1 2 0'] Output:['1 -11 21 0']
[ 0 ]
Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i + 1, i + 2, ..., i + k. Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?
Input: ['2 1..'] Output:['YES']
[ 0 ]
Ksusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!
Input: ['32 2 4'] Output:['2']
[ 0 ]
The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y). If the wind blows to the east, the boat will move to (x + 1, y). If the wind blows to the south, the boat will move to (x, y - 1). If the wind blows to the west, the boat will move to (x - 1, y). If the wind blows to the north, the boat will move to (x, y + 1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?
Input: ['5 0 0 1 1SESNW'] Output:['4']
[ 0, 2 ]
There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.
Input: ['9..RRLL...'] Output:['3 4']
[ 2 ]
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≀ w2 ≀ ... ≀ wk holds.Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights wi (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?
Input: ['3 3 32 2 21 1 3'] Output:['YES']
[ 2 ]
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.Help Yaroslav.
Input: ['11'] Output:['YES']
[ 2, 3 ]
Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of nΒ·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.Let's consider an examples depicted below. If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input: ['3 41 1 DR'] Output:['7']
[ 0 ]
Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is ti and its pages' width is equal to wi. The thickness of each book is either 1 or 2. All books have the same page heights. Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure. Help Shaass to find the minimum total thickness of the vertical books that we can achieve.
Input: ['51 121 32 152 52 1'] Output:['5']
[ 2 ]
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols sitting on the i-th wire. Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away. Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.
Input: ['510 10 10 10 1052 53 132 121 134 6'] Output:['0125016']
[ 3 ]
Ksusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles. Today Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the polygon and then draws a square with two opposite vertices lying in the chosen points, what will the expectation of this square's area be?A pair of distinct points is chosen uniformly among all pairs of distinct points, located inside or on the border of the polygon. Pairs of points p, q (p ≠ q) and q, p are considered the same.Help Ksusha! Count the required expectation.
Input: ['30 05 55 0'] Output:['4.6666666667']
[ 3 ]
Yaroslav, Andrey and Roman love playing cubes. Sometimes they get together and play cubes for hours and hours! Today they got together again and they are playing cubes. Yaroslav took unit cubes and composed them into an a × a × a cube, Andrey made a b × b × b cube and Roman made a c × c × c cube. After that the game was finished and the guys left. But later, Vitaly entered the room. He saw the cubes and wanted to make a cube as well. But what size should the cube be? Of course it should be a large cube with the side of length a + b + c. Besides, Vitaly decided to decompose the cubes built by Yaroslav, Andrey and Roman and compose his own large cube out of them. However, it turned out that the unit cubes he got from destroying the three cubes just weren't enough to make a large cube. We know that Vitaly was short of exactly n cubes. Vitaly got upset, demolished everything and left. As he was leaving, he met Petya and told him that there had been three cubes in the room and that he needed another n unit cubes to make his own large cube.Petya entered the room and saw the messily scattered cubes. He wanted to make it neat and orderly again. But he only knows that there had been three cubes, made of small unit cubes and that Vitaly needed n more unit cubes to make a large one! Help Petya understand, how many ways of sizes a, b, c are there to restore Yaroslav's, Andrey's and Roman's cubes.
Input: ['24'] Output:['1']
[ 0, 3 ]
You have a rectangular n × m-cell board. Some cells are already painted some of k colors. You need to paint each uncolored cell one of the k colors so that any path from the upper left square to the lower right one doesn't contain any two cells of the same color. The path can go only along side-adjacent cells and can only go down or right.Print the number of possible paintings modulo 1000000007 (109 + 7).
Input: ['2 2 40 00 0'] Output:['48']
[ 0 ]
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2Β·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2Β·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string. Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
Input: ['201110001'] Output:['First']
[ 2 ]
The problem uses a simplified TCP/IP address model, please read the statement carefully.An IP address is a 32-bit integer, represented as a group of four decimal 8-bit integers (without leading zeroes), separated by commas. For example, record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In the given problem an arbitrary group of four 8-bit integers is a correct IP address.Our hero Polycarpus still works as a system administrator in some large corporation. He likes beautiful IP addresses. To check if some IP address is beautiful, he should do the following: write out in a line four 8-bit numbers of the IP address, without the commas; check if the resulting string is a palindrome. Let us remind you that a palindrome is a string that reads the same from right to left and from left to right.For example, IP addresses 12.102.20.121 and 0.3.14.130 are beautiful (as strings "1210220121" and "0314130" are palindromes), and IP addresses 1.20.20.1 and 100.4.4.1 are not.Polycarpus wants to find all beautiful IP addresses that have the given set of digits. Each digit from the set must occur in the IP address at least once. IP address must not contain any other digits. Help him to cope with this difficult task.
Input: ['60 1 2 9 8 7'] Output:['678.190.209.18779.180.208.19787.190.209.17889.170.207.19897.180.208.17998.170.207.189']
[ 0 ]
Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n.Polycarpus needs to come up with a parallel program model. For each memory cell number i this program must record the value n - i to this cell. In other words, for each cell you've got to find the distance to cell n.Let's denote the value that is written in the i-th cell as ai. Initially, ai = 1 (1 ≀ i < n) and an = 0. We will consider that only processor i can write values in the memory cell number i. All processors can read an information from some cell (several processors can read an information from some cell simultaneously).The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows: Each processor independently of the other ones chooses some memory cell. Let's say that processor i has chosen a cell with number ci (1 ≀ ci ≀ n). All processors simultaneously execute operation ai = ai + aci. Help Polycarpus come up with the parallel program model that is executed in exactly k steps. Calculate the operations that need to be executed. Note that after k steps for all i's value ai must be equal n - i.
Input: ['1 1'] Output:['1']
[ 2 ]
The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively.Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address.Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess.The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as "11...11000..000". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000.To get the network address of the IP address, you need to perform the operation of the bitwise "and" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise "and" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one.Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so.
Input: ['5 30.0.0.10.1.1.20.0.2.10.1.1.00.0.2.3'] Output:['255.255.254.0']
[ 0 ]
Petya is an unexperienced programming contestant. Recently he has come across the following problem:You are given a non-directed graph which consists of n nodes and m edges. Your task is to determine whether the graph contains a Hamiltonian path.Petya wrote a quick bug-free code which he believes solves this problem. After that Petya decided to give this problem for April Fools Day contest. Unfortunately, Petya might have made a mistake, and it's quite possible that his algorithm is wrong. But this isn't a good excuse to leave the contest without submitting this problem, is it?
Input: ['2 31 22 11 1'] Output:['Yes']
[ 2 ]
Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input: ['2 2 22 46 8'] Output:['4']
[ 0, 4 ]
Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≀ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≀ x ≀ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.
Input: ['2 31 23 4'] Output:['2']
[ 0 ]
Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Polo the Penguin have two positive integers l and r (l < r), both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other.Let's assume that n is the number of distinct lucky numbers, each of them cannot be greater than r or less than l, and ai is the i-th (in increasing order) number of them. Find a1Β·a2 + a2Β·a3 + ... + an - 1Β·an. As the answer can be rather large, print the remainder after dividing it by 1000000007 (109 + 7).
Input: ['47'] Output:['28']
[ 3 ]
Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.For permutation p = p0, p1, ..., pn, Polo has defined its beauty β€” number .Expression means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal β€” as "xor".Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.
Input: ['4'] Output:['200 2 1 4 3']
[ 3 ]
Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≀ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.
Input: ['7 4'] Output:['ababacd']
[ 2 ]
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only one pipe with flowing water. Besides, Vova has several splitters.A splitter is a construction that consists of one input (it can be connected to a water pipe) and x output pipes. When a splitter is connected to a water pipe, water flows from each output pipe. You can assume that the output pipes are ordinary pipes. For example, you can connect water supply to such pipe if there's water flowing out from it. At most one splitter can be connected to any water pipe. The figure shows a 4-output splitter Vova has one splitter of each kind: with 2, 3, 4, ..., k outputs. Help Vova use the minimum number of splitters to build the required pipeline or otherwise state that it's impossible.Vova needs the pipeline to have exactly n pipes with flowing out water. Note that some of those pipes can be the output pipes of the splitters.
Input: ['4 3'] Output:['2']
[ 3, 4 ]
In the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2 × 2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed. Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2 × 2 square, consisting of cells of the same color.
Input: ['####.#..####....'] Output:['YES']
[ 0 ]
A ladies' shop has recently opened in the city of Ultima Thule. To get ready for the opening, the shop bought n bags. Each bag is characterised by the total weight ai of the items you can put there. The weird thing is, you cannot use these bags to put a set of items with the total weight strictly less than ai. However the weights of the items that will be sold in the shop haven't yet been defined. That's what you should determine right now.Your task is to find the set of the items' weights p1, p2, ..., pk (1 ≀ p1 < p2 < ... < pk), such that: Any bag will be used. That is, for any i (1 ≀ i ≀ n) there will be such set of items that their total weight will equal ai. We assume that there is the infinite number of items of any weight. You can put multiple items of the same weight in one bag. For any set of items that have total weight less than or equal to m, there is a bag into which you can put this set. Similarly, a set of items can contain multiple items of the same weight. Of all sets of the items' weights that satisfy points 1 and 2, find the set with the minimum number of weights. In other words, value k should be as small as possible. Find and print the required set.
Input: ['6 105 6 7 8 9 10'] Output:['YES55 6 7 8 9 ']
[ 3 ]
As you know, Vova has recently become a new shaman in the city of Ultima Thule. So, he has received the shaman knowledge about the correct bracket sequences. The shamans of Ultima Thule have been using lots of different types of brackets since prehistoric times. A bracket type is a positive integer. The shamans define a correct bracket sequence as follows: An empty sequence is a correct bracket sequence. If {a1, a2, ..., al} and {b1, b2, ..., bk} are correct bracket sequences, then sequence {a1, a2, ..., al, b1, b2, ..., bk} (their concatenation) also is a correct bracket sequence. If {a1, a2, ..., al} β€” is a correct bracket sequence, then sequence also is a correct bracket sequence, where v (v > 0) is an integer. For example, sequences {1, 1,  - 1, 2,  - 2,  - 1} and {3,  - 3} are correct bracket sequences, and {2,  - 3} is not.Moreover, after Vova became a shaman, he learned the most important correct bracket sequence {x1, x2, ..., xn}, consisting of n integers. As sequence x is the most important, Vova decided to encrypt it just in case.Encrypting consists of two sequences. The first sequence {p1, p2, ..., pn} contains types of brackets, that is, pi = |xi| (1 ≀ i ≀ n). The second sequence {q1, q2, ..., qt} contains t integers β€” some positions (possibly, not all of them), which had negative numbers in sequence {x1, x2, ..., xn}.Unfortunately, Vova forgot the main sequence. But he was lucky enough to keep the encryption: sequences {p1, p2, ..., pn} and {q1, q2, ..., qt}. Help Vova restore sequence x by the encryption. If there are multiple sequences that correspond to the encryption, restore any of them. If there are no such sequences, you should tell so.
Input: ['21 10'] Output:['YES1 -1']
[ 2 ]
A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≀ pi ≀ n).A lucky permutation is such permutation p, that any integer i (1 ≀ i ≀ n) meets this condition ppi = n - i + 1.You have integer n. Find some lucky permutation p of size n.
Input: ['1'] Output:['1 ']
[ 3 ]
Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.We'll call position i (1 ≀ i ≀ n) in permutation p1, p2, ..., pn good, if |p[i] - i| = 1. Count the number of permutations of size n with exactly k good positions. Print the answer modulo 1000000007 (109 + 7).
Input: ['1 0'] Output:['1']
[ 3 ]
Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
Input: ['23 0'] Output:['2']
[ 2 ]
Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.The decreasing coefficient of permutation p1, p2, ..., pn is the number of such i (1 ≀ i < n), that pi > pi + 1.You have numbers n and k. Your task is to print the permutation of length n with decreasing coefficient k.
Input: ['5 2'] Output:['1 5 2 4 3']
[ 2 ]
There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN".Find the number of cows that can currently show their hands without affecting any betting decisions.
Input: ['6AFFAAA'] Output:['4']
[ 0 ]
The cows have just learned what a primitive root is! Given a prime p, a primitive root is an integer x (1 ≀ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is. Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime p, help the cows find the number of primitive roots .
Input: ['3'] Output:['1']
[ 3 ]
Farmer John is hosting a tennis tournament with his n cows. Each cow has a skill level si, and no two cows having the same skill level. Every cow plays every other cow exactly once in the tournament, and each cow beats every cow with skill level lower than its own.However, Farmer John thinks the tournament will be demoralizing for the weakest cows who lose most or all of their matches, so he wants to flip some of the results. In particular, at k different instances, he will take two integers ai, bi (ai < bi) and flip all the results between cows with skill level between ai and bi inclusive. That is, for any pair x, y he will change the result of the match on the final scoreboard (so if x won the match, the scoreboard will now display that y won the match, and vice versa). It is possible that Farmer John will change the result of a match multiple times. It is not guaranteed that ai and bi are equal to some cow's skill level.Farmer John wants to determine how balanced he made the tournament results look. In particular, he wants to count the number of triples of cows (p, q, r) for which the final leaderboard shows that cow p beats cow q, cow q beats cow r, and cow r beats cow p. Help him determine this number.Note that two triples are considered different if they do not contain the same set of cows (i.e. if there is a cow in one triple that is not in the other).
Input: ['3 21 2 31 22 3'] Output:['1']
[ 3 ]
Bessie and the cows have recently been playing with "cool" sequences and are trying to construct some. Unfortunately they are bad at arithmetic, so they need your help!A pair (x, y) of positive integers is "cool" if x can be expressed as the sum of y consecutive integers (not necessarily positive). A sequence (a1, a2, ..., an) is "cool" if the pairs (a1, a2), (a2, a3), ..., (an - 1, an) are all cool. The cows have a sequence of n positive integers, a1, a2, ..., an. In one move, they may replace some ai with any other positive integer (there are no other limits on the new value of ai). Determine the smallest number of moves needed to make the resulting sequence cool.
Input: ['36 4 1'] Output:['0']
[ 3 ]
The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.A Bitlandish string is a string made only of characters "0" and "1".BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = x xor y, q = x or y. Then he replaces one of the two taken characters by p and the other one by q.The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.
Input: ['1110'] Output:['YES']
[ 3 ]