question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
There are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c1,βc2,β...,βcn. The Old Peykan wants to travel from city c1 to cn using roads. There are (nβ-β1) one way roads, the i-th road goes from city ci to city ciβ+β1 and is di kilometers long.The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.Each city ci (except for the last city cn) has a supply of si liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly k hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times. Initially (at time zero) the Old Peykan is at city c1 and s1 liters of fuel is transferred to it's empty tank from c1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.Find the minimum time the Old Peykan needs to reach city cn. | Input: ['4 61 2 5 22 3 3 4'] Output:['10'] | [
2
] |
A country named Berland has n cities. They are numbered with integers from 1 to n. City with index 1 is the capital of the country. Some pairs of cities have monodirectional roads built between them. However, not all of them are in good condition. For each road we know whether it needs repairing or not. If a road needs repairing, then it is forbidden to use it. However, the Berland government can repair the road so that it can be used.Right now Berland is being threatened by the war with the neighbouring state. So the capital officials decided to send a military squad to each city. The squads can move only along the existing roads, as there's no time or money to build new roads. However, some roads will probably have to be repaired in order to get to some cities.Of course the country needs much resources to defeat the enemy, so you want to be careful with what you're going to throw the forces on. That's why the Berland government wants to repair the minimum number of roads that is enough for the military troops to get to any city from the capital, driving along good or repaired roads. Your task is to help the Berland government and to find out, which roads need to be repaired. | Input: ['3 21 3 03 2 1'] Output:['12'] | [
2
] |
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. Current character pointer (CP); Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right.We repeat the following steps until the first moment that CP points to somewhere outside the sequence. If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one. If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated.It's obvious the every program in this language terminates after some steps.We have a sequence s1,βs2,β...,βsn of "<", ">" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence sl,βslβ+β1,β...,βsr as an independent program in this language. | Input: ['7 41>3>22<1 34 77 71 7'] Output:['0 1 0 1 0 0 0 0 0 0 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 2 1 0 0 0 0 0 0 '] | [
0
] |
Valera had two bags of potatoes, the first of these bags contains x (xββ₯β1) potatoes, and the second β y (yββ₯β1) potatoes. Valera β very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (xβ+βy) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order. | Input: ['10 1 10'] Output:['-1'] | [
2,
3
] |
You must have heard of the two brothers dreaming of ruling the world. With all their previous plans failed, this time they decided to cooperate with each other in order to rule the world. As you know there are n countries in the world. These countries are connected by nβ-β1 directed roads. If you don't consider direction of the roads there is a unique path between every pair of countries in the world, passing through each road at most once. Each of the brothers wants to establish his reign in some country, then it's possible for him to control the countries that can be reached from his country using directed roads. The brothers can rule the world if there exists at most two countries for brothers to choose (and establish their reign in these countries) so that any other country is under control of at least one of them. In order to make this possible they want to change the direction of minimum number of roads. Your task is to calculate this minimum number of roads. | Input: ['42 13 14 1'] Output:['1'] | [
2
] |
A sequence of non-negative integers a1,βa2,β...,βan of length n is called a wool sequence if and only if there exists two integers l and r (1ββ€βlββ€βrββ€βn) such that . In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.The expression means applying the operation of a bitwise xor to numbers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as "^", in Pascal β as "xor".In this problem you are asked to compute the number of sequences made of n integers from 0 to 2mβ-β1 that are not a wool sequence. You should print this number modulo 1000000009 (109β+β9). | Input: ['3 2'] Output:['6'] | [
3
] |
You've got a undirected tree s, consisting of n nodes. Your task is to build an optimal T-decomposition for it. Let's define a T-decomposition as follows.Let's denote the set of all nodes s as v. Let's consider an undirected tree t, whose nodes are some non-empty subsets of v, we'll call them xi . The tree t is a T-decomposition of s, if the following conditions holds: the union of all xi equals v; for any edge (a,βb) of tree s exists the tree node t, containing both a and b; if the nodes of the tree t xi and xj contain the node a of the tree s, then all nodes of the tree t, lying on the path from xi to xj also contain node a. So this condition is equivalent to the following: all nodes of the tree t, that contain node a of the tree s, form a connected subtree of tree t. There are obviously many distinct trees t, that are T-decompositions of the tree s. For example, a T-decomposition is a tree that consists of a single node, equal to set v.Let's define the cardinality of node xi as the number of nodes in tree s, containing in the node. Let's choose the node with the maximum cardinality in t. Let's assume that its cardinality equals w. Then the weight of T-decomposition t is value w. The optimal T-decomposition is the one with the minimum weight.Your task is to find the optimal T-decomposition of the given tree s that has the minimum number of nodes. | Input: ['21 2'] Output:['12 1 2'] | [
2
] |
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors.Consider positive integers a, aβ+β1, ..., b (aββ€βb). You want to find the minimum integer l (1ββ€βlββ€βbβ-βaβ+β1) such that for any integer x (aββ€βxββ€βbβ-βlβ+β1) among l integers x, xβ+β1, ..., xβ+βlβ-β1 there are at least k prime numbers. Find and print the required minimum l. If no value l meets the described limitations, print -1. | Input: ['2 4 2'] Output:['3'] | [
4
] |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method. | Input: ['wjmzbmr'] Output:['CHAT WITH HER!'] | [
0
] |
Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum:Find the sum modulo 1073741824 (230). | Input: ['2 2 2'] Output:['20'] | [
3
] |
You're playing a game called Osu! Here's a simplified version of it. There are n clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of n characters "O" and "X".Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be 22β+β32β+β22β=β17. If there are no correct clicks in a play then the score for the play equals to 0.You know that the probability to click the i-th (1ββ€βiββ€βn) click correctly is pi. In other words, the i-th character in the play sequence has pi probability to be "O", 1β-βpi to be "X". You task is to calculate the expected score for your play. | Input: ['30.5 0.5 0.5'] Output:['2.750000000000000'] | [
3
] |
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum. | Input: ['31 0 141 1 1 1'] Output:['1 4 5 6 7 2 335 6 7'] | [
2
] |
Let's consider equation:x2β+βs(x)Β·xβ-βnβ=β0,β where x,βn are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots. | Input: ['2'] Output:['1'] | [
0,
3,
4
] |
A permutation is a sequence of integers p1,βp2,β...,βpn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1,βp2,β...,βpn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1ββ€βiββ€βn) (n is the permutation size) the following equations hold ppiβ=βi and piββ βi. Nickolas asks you to print any perfect permutation of size n for the given n. | Input: ['1'] Output:['-1'] | [
3
] |
John Doe has a crooked fence, consisting of n rectangular planks, lined up from the left to the right: the plank that goes i-th (1ββ€βiββ€βn) (from left to right) has width 1 and height hi. We will assume that the plank that goes i-th (1ββ€βiββ€βn) (from left to right) has index i.A piece of the fence from l to r (1ββ€βlββ€βrββ€βn) is a sequence of planks of wood with indices from l to r inclusive, that is, planks with indices l,βlβ+β1,β...,βr. The width of the piece of the fence from l to r is value rβ-βlβ+β1.Two pieces of the fence from l1 to r1 and from l2 to r2 are called matching, if the following conditions hold: the pieces do not intersect, that is, there isn't a single plank, such that it occurs in both pieces of the fence; the pieces are of the same width; for all i (0ββ€βiββ€βr1β-βl1) the following condition holds: hl1β+βiβ+βhl2β+βiβ=βhl1β+βhl2. John chose a few pieces of the fence and now wants to know how many distinct matching pieces are for each of them. Two pieces of the fence are distinct if there is a plank, which belongs to one of them and does not belong to the other one. | Input: ['101 2 2 1 100 99 99 100 100 10061 41 23 41 59 1010 10'] Output:['122029'] | [
4
] |
John Doe has an nβΓβm table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size nβΓβn have exactly k points.John Doe wondered, how many distinct ways to fill the table with points are there, provided that the condition must hold. As this number can be rather large, John Doe asks to find its remainder after dividing by 1000000007 (109β+β7).You should assume that John always paints a point exactly in the center of some cell. Two ways to fill a table are considered distinct, if there exists a table cell, that has a point in one way and doesn't have it in the other. | Input: ['5 6 1'] Output:['45'] | [
3
] |
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. | Input: ['1'] Output:['3011101110'] | [
2,
4
] |
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point (0,β0,β0), and the opposite one is at point (x1,βy1,βz1). The six faces of the box contain some numbers a1,βa2,β...,βa6, exactly one number right in the center of each face. The numbers are located on the box like that: number a1 is written on the face that lies on the ZOX plane; a2 is written on the face, parallel to the plane from the previous point; a3 is written on the face that lies on the XOY plane; a4 is written on the face, parallel to the plane from the previous point; a5 is written on the face that lies on the YOZ plane; a6 is written on the face, parallel to the plane from the previous point. At the moment Vasya is looking at the box from point (x,βy,βz). Find the sum of numbers that Vasya sees. Note that all faces of the box are not transparent and Vasya can't see the numbers through the box. The picture contains transparent faces just to make it easier to perceive. You can consider that if Vasya is looking from point, lying on the plane of some face, than he can not see the number that is written on this face. It is enough to see the center of a face to see the corresponding number for Vasya. Also note that Vasya always reads correctly the ai numbers that he sees, independently of their rotation, angle and other factors (that is, for example, if Vasya sees some aiβ=β6, then he can't mistake this number for 9 and so on). | Input: ['2 2 21 1 11 2 3 4 5 6'] Output:['12'] | [
0
] |
A piece of paper contains an array of n integers a1,βa2,β...,βan. Your task is to find a number that occurs the maximum number of times in this array.However, before looking for such number, you are allowed to perform not more than k following operations β choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one. | Input: ['5 36 3 4 0 2'] Output:['3 4'] | [
4
] |
Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.Help Vasya to recover the initial set of cards with numbers. | Input: ['3 3 2'] Output:['2 1 2 '] | [
2
] |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution. | Input: ['31 1 01 1 11 0 0'] Output:['2'] | [
0,
2
] |
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Π’-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Π’-prime or not. | Input: ['34 5 6'] Output:['YESNONO'] | [
3,
4
] |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1ββ€βiββ€βn) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss. | Input: ['2 21 99100 0'] Output:['YES'] | [
2
] |
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with n gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for n names of items from the list. If the fish's list has p occurrences of the given name, then the old man can't ask for this name of item more than p times.The old man knows that if he asks for s gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose s gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the n names in such a way that he can get n gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly.The old man wondered, what is the probability that he can get n most expensive gifts. As the old man isn't good at probability theory, he asks you to help him. | Input: ['3 13 10 20 30'] Output:['1.000000000'] | [
3
] |
The city of D consists of n towers, built consecutively on a straight line. The height of the tower that goes i-th (from left to right) in the sequence equals hi. The city mayor decided to rebuild the city to make it beautiful. In a beautiful city all towers are are arranged in non-descending order of their height from left to right.The rebuilding consists of performing several (perhaps zero) operations. An operation constitutes using a crane to take any tower and put it altogether on the top of some other neighboring tower. In other words, we can take the tower that stands i-th and put it on the top of either the (iβ-β1)-th tower (if it exists), or the (iβ+β1)-th tower (of it exists). The height of the resulting tower equals the sum of heights of the two towers that were put together. After that the two towers can't be split by any means, but more similar operations can be performed on the resulting tower. Note that after each operation the total number of towers on the straight line decreases by 1.Help the mayor determine the minimum number of operations required to make the city beautiful. | Input: ['58 2 7 3 1'] Output:['3'] | [
2
] |
Alice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with n vertices, chooses some m edges and keeps them. Bob gets the remaining edges.Alice and Bob are fond of "triangles" in graphs, that is, cycles of length 3. That's why they wonder: what total number of triangles is there in the two graphs formed by Alice and Bob's edges, correspondingly? | Input: ['5 51 21 32 32 43 4'] Output:['3'] | [
3
] |
Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time tβ+β1, unless there are more travellers arriving at time tβ+β1 to the same planet.Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n. | Input: ['4 61 2 21 3 31 4 82 3 42 4 53 4 301 32 3 40'] Output:['7'] | [
4
] |
You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100".Determine the minimum number of moves needed to make some table column consist only of numbers 1. | Input: ['3 6101010000100100000'] Output:['3'] | [
0
] |
You've got two rectangular tables with sizes naβΓβma and nbβΓβmb cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the i-th row and the j-th column, as ai,βj; we will define the element of the second table, located at the intersection of the i-th row and the j-th column, as bi,βj. We will call the pair of integers (x,βy) a shift of the second table relative to the first one. We'll call the overlap factor of the shift (x,βy) value:where the variables i,βj take only such values, in which the expression ai,βjΒ·biβ+βx,βjβ+βy makes sense. More formally, inequalities 1ββ€βiββ€βna,β1ββ€βjββ€βma,β1ββ€βiβ+βxββ€βnb,β1ββ€βjβ+βyββ€βmb must hold. If there are no values of variables i,βj, that satisfy the given inequalities, the value of the sum is considered equal to 0. Your task is to find the shift with the maximum overlap factor among all possible shifts. | Input: ['3 20110002 3001111'] Output:['0 1'] | [
0
] |
Harry Potter has a difficult homework. Given a rectangular table, consisting of nβΓβm cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second β in the selected column. Harry's task is to make non-negative the sum of the numbers in each row and each column using these spells.Alone, the boy can not cope. Help the young magician! | Input: ['4 1-1-1-1-1'] Output:['4 1 2 3 4 0 '] | [
2
] |
There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of numbers l, lβ+β1, lβ+β2, ..., r; let's consider all its k-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one.Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where F1β=β1, F2β=β1, Fnβ=βFnβ-β1β+βFnβ-β2 for nββ₯β3.Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by m. | Input: ['10 1 8 2'] Output:['3'] | [
3
] |
There are n piles of stones of sizes a1,βa2,β...,βan lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants. | Input: ['52 3 4 1 122 3'] Output:['9 8 '] | [
2
] |
An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one β to the 1-st and the 3-rd ones, the 3-rd one β only to the 2-nd one. The transitions are possible only between the adjacent sections.The spacecraft team consists of n aliens. Each of them is given a rank β an integer from 1 to n. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section a to section b only if it is senior in rank to all aliens who are in the segments a and b (besides, the segments a and b are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.Alien A is senior in rank to alien B, if the number indicating rank A, is more than the corresponding number for B.At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo m. | Input: ['1 10'] Output:['2'] | [
3
] |
Consider the following equation: where sign [a] represents the integer part of number a.Let's find all integer z (zβ>β0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x,βyβ>β0), for which the given above equation holds.Let's write out all such z in the increasing order: z1,βz2,βz3, and so on (ziβ<βziβ+β1). Your task is: given the number n, find the number zn. | Input: ['1'] Output:['1'] | [
3
] |
Numbers k-bonacci (k is integer, kβ>β1) are a generalization of Fibonacci numbers and are determined as follows: F(k,βn)β=β0, for integer n, 1ββ€βnβ<βk; F(k,βk)β=β1; F(k,βn)β=βF(k,βnβ-β1)β+βF(k,βnβ-β2)β+β...β+βF(k,βnβ-βk), for integer n, nβ>βk. Note that we determine the k-bonacci numbers, F(k,βn), only for integer values of n and k.You've got a number s, represent it as a sum of several (at least two) distinct k-bonacci numbers. | Input: ['5 2'] Output:['30 2 3'] | [
2,
4
] |
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not. | Input: ['363 25 42 4'] Output:['YES'] | [
2
] |
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. | Input: ['1 1 1'] Output:['12'] | [
0,
3
] |
You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that: First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1ββ€βiββ€βn) of array s equals . The operation x mod y means that we take the remainder of the division of number x by number y. Then we write the contents of the array s to the array a. Element number i (1ββ€βiββ€βn) of the array s becomes the i-th element of the array a (aiβ=βsi). You task is to find array a after exactly k described operations are applied. | Input: ['3 11 2 3'] Output:['1 3 6'] | [
3
] |
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.Help Vasya's teacher, find two numbers β the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad. | Input: ['5 21 1 1 1 11 1 1 1 1'] Output:['1 5'] | [
2,
4
] |
To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | Input: ['3 2100 5 250 10'] Output:['2 32 11 1 1'] | [
3
] |
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. | Input: ['3 23 1 1'] Output:['1'] | [
0
] |
The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | Input: ['1'] Output:['1 '] | [
3
] |
The Little Elephant is playing with the Cartesian coordinates' system. Most of all he likes playing with integer points. The Little Elephant defines an integer point as a pair of integers (x; y), such that 0ββ€βxββ€βw and 0ββ€βyββ€βh. Thus, the Little Elephant knows only (wβ+β1)Β·(hβ+β1) distinct integer points.The Little Elephant wants to paint a triangle with vertexes at integer points, the triangle's area must be a positive integer. For that, he needs to find the number of groups of three points that form such triangle. At that, the order of points in a group matters, that is, the group of three points (0;0), (0;2), (2;2) isn't equal to the group (0;2), (0;0), (2;2).Help the Little Elephant to find the number of groups of three integer points that form a nondegenerate triangle with integer area. | Input: ['2 1'] Output:['36'] | [
3
] |
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells. | Input: ['6 3ABBACC'] Output:['2ABCACA'] | [
0,
2
] |
Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2nβ+β1 points with coordinates (1,βy1), (2,βy2), ..., (2nβ+β1,βy2nβ+β1), with the i-th segment connecting the point (i,βyi) and the point (iβ+β1,βyiβ+β1). For any even i (2ββ€βiββ€β2n) the following condition holds: yiβ-β1β<βyi and yiβ>βyiβ+β1. We shall call a vertex of a polyline with an even x coordinate a mountain peak. The figure to the left shows the initial picture, the figure to the right shows what the picture looks like after Bolek's actions. The affected peaks are marked red, k = 2. Bolek fancied a little mischief. He chose exactly k mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the y coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1,βr1), (2,βr2), ..., (2nβ+β1,βr2nβ+β1).Given Bolek's final picture, restore the initial one. | Input: ['3 20 5 3 5 1 5 2'] Output:['0 5 3 4 1 4 2 '] | [
0
] |
Byteland is trying to send a space mission onto the Bit-X planet. Their task is complicated by the fact that the orbit of the planet is regularly patrolled by Captain Bitonix, the leader of the space forces of Bit-X.There are n stations around Bit-X numbered clockwise from 1 to n. The stations are evenly placed on a circular orbit, so the stations number i and iβ+β1 (1ββ€βiβ<βn), and the stations number 1 and n, are neighboring. The distance between every pair of adjacent stations is equal to m space miles. To go on a patrol, Captain Bitonix jumps in his rocket at one of the stations and flies in a circle, covering a distance of at least one space mile, before finishing in some (perhaps the starting) station.Bitonix' rocket moves by burning fuel tanks. After Bitonix attaches an x-liter fuel tank and chooses the direction (clockwise or counter-clockwise), the rocket flies exactly x space miles along a circular orbit in the chosen direction. Note that the rocket has no brakes; it is not possible for the rocket to stop before depleting a fuel tank.For example, assume that nβ=β3 and mβ=β60 and Bitonix has fuel tanks with volumes of 10, 60, 90 and 100 liters. If Bitonix starts from station 1, uses the 100-liter fuel tank to go clockwise, then uses the 90-liter fuel tank to go clockwise, and then uses the 10-liter fuel tank to go counterclockwise, he will finish back at station 1. This constitutes a valid patrol. Note that Bitonix does not have to use all available fuel tanks. Another valid option for Bitonix in this example would be to simply use the 60-liter fuel tank to fly to either station 2 or 3.However, if n was equal to 3, m was equal to 60 and the only fuel tanks available to Bitonix were one 10-liter tank and one 100-liter tank, he would have no way of completing a valid patrol (he wouldn't be able to finish any patrol exactly at the station).The Byteland space agency wants to destroy some of Captain Bitonix' fuel tanks so that he cannot to complete any valid patrol. Find how many different subsets of the tanks the agency can destroy to prevent Captain Bitonix from completing a patrol and output the answer modulo 1000000007 (109β+β7). | Input: ['7 6 55 4 12 6 5'] Output:['6'] | [
0,
3
] |
Fibonacci numbers are the sequence of integers: f0β=β0, f1β=β1, f2β=β1, f3β=β2, f4β=β3, f5β=β5, ..., fnβ=βfnβ-β2β+βfnβ-β1. So every next number is the sum of the previous two.Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he performs the following two operations: operation "T": replace the top number with the sum of both numbers; operation "B": replace the bottom number with the sum of both numbers. If he performs n operations, starting with "T" and then choosing operations alternately (so that the sequence of operations looks like "TBTBTBTB..."), the last number written will be equal to fnβ+β1.Unfortunately, Bajtek sometimes makes mistakes and repeats an operation two or more times in a row. For example, if Bajtek wanted to compute f7, then he would want to do nβ=β6 operations: "TBTBTB". If he instead performs the sequence of operations "TTTBBT", then he will have made 3 mistakes, and he will incorrectly compute that the seventh Fibonacci number is 10. The number of mistakes in the sequence of operations is the number of neighbouring equal operations (Β«TTΒ» or Β«BBΒ»).You are given the number n of operations that Bajtek has made in an attempt to compute fnβ+β1 and the number r that is the result of his computations (that is last written number). Find the minimum possible number of mistakes that Bajtek must have made and any possible sequence of n operations resulting in r with that number of mistakes.Assume that Bajtek always correctly starts with operation "T". | Input: ['6 10'] Output:['2TBBTTB'] | [
0,
3
] |
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates. | Input: ['22 11 2'] Output:['1'] | [
0
] |
You know that the Martians use a number system with base k. Digit b (0ββ€βbβ<βk) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year b (by Martian chronology).A digital root d(x) of number x is a number that consists of a single digit, resulting after cascading summing of all digits of number x. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number.For example, d(35047)β=βd((3β+β5β+β0β+β4)7)β=βd(157)β=βd((1β+β5)7)β=βd(67)β=β67. In this sample the calculations are performed in the 7-base notation.If a number's digital root equals b, the Martians also call this number lucky.You have string s, which consists of n digits in the k-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers.Note that substring s[i... j] of the string sβ=βa1a2... an (1ββ€βiββ€βjββ€βn) is the string aiaiβ+β1... aj. Two substrings s[i1... j1] and s[i2... j2] of the string s are different if either i1ββ βi2 or j1ββ βj2. | Input: ['10 5 63 2 0 5 6 1'] Output:['5'] | [
3
] |
Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web. There are n main threads going from the center of the web. All main threads are located in one plane and divide it into n equal infinite sectors. The sectors are indexed from 1 to n in the clockwise direction. Sectors i and iβ+β1 are adjacent for every i, 1ββ€βiβ<βn. In addition, sectors 1 and n are also adjacent.Some sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them.A cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells.Unstable cells are marked red in the figure. Stable cells are marked green.Paw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun. | Input: ['73 1 6 74 3 5 2 92 8 14 3 7 6 43 2 5 93 6 3 83 4 2 9'] Output:['6'] | [
4
] |
A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.The store will work seven days a week, but not around the clock. Every day at least k people must work in the store.Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly n consecutive days, then rest for exactly m days, then work for n more days and rest for m more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day x, then he should work on days [x,βxβ+β1,β...,βxβ+βnβ-β1], [xβ+βmβ+βn,βxβ+βmβ+βnβ+β1,β...,βxβ+βmβ+β2nβ-β1], and so on. Day x can be chosen arbitrarily by Vitaly.There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day β otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least k working employees, and one of the working employees should have the key to the store.Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired. | Input: ['4 3 2'] Output:['41 1 4 5'] | [
2
] |
Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.The hall also turned out hexagonal in its shape. The King walked along the perimeter of the hall and concluded that each of the six sides has a, b, c, a, b and c adjacent tiles, correspondingly.To better visualize the situation, look at the picture showing a similar hexagon for aβ=β2, bβ=β3 and cβ=β4. According to the legend, as the King of Berland obtained the values a, b and c, he almost immediately calculated the total number of tiles on the hall floor. Can you do the same? | Input: ['2 3 4'] Output:['18'] | [
3
] |
The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1ββ€βiββ€βn) region has a stable temperature of ti degrees in summer.This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is tiβ+βk degrees.Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren. | Input: ['2 1030 35 1 10020 35 10 10'] Output:['120'] | [
2
] |
There is a board with a grid consisting of n rows and m columns, the rows are numbered from 1 from top to bottom and the columns are numbered from 1 from left to right. In this grid we will denote the cell that lies on row number i and column number j as (i,βj).A group of six numbers (a,βb,βc,βd,βx0,βy0), where 0ββ€βa,βb,βc,βd, is a cross, and there is a set of cells that are assigned to it. Cell (x,βy) belongs to this set if at least one of two conditions are fulfilled: |x0β-βx|ββ€βa and |y0β-βy|ββ€βb |x0β-βx|ββ€βc and |y0β-βy|ββ€βd The picture shows the cross (0,β1,β1,β0,β2,β3) on the grid 3βΓβ4. Your task is to find the number of different groups of six numbers, (a,βb,βc,βd,βx0,βy0) that determine the crosses of an area equal to s, which are placed entirely on the grid. The cross is placed entirely on the grid, if any of its cells is in the range of the grid (that is for each cell (x,βy) of the cross 1ββ€βxββ€βn; 1ββ€βyββ€βm holds). The area of the cross is the number of cells it has.Note that two crosses are considered distinct if the ordered groups of six numbers that denote them are distinct, even if these crosses coincide as sets of points. | Input: ['2 2 1'] Output:['4'] | [
0
] |
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0β<βr2β<βr1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested inside the ring.The Olympic jury decided that r1 will take one of possible values of x1,βx2,β...,βxn. It is up to jury to decide which particular value r1 will take. Similarly, the Olympic jury decided that p1 will take one of possible value of y1,βy2,β...,βym, and p2 will take a value from list z1,βz2,β...,βzk.According to most ancient traditions the ratio between the outer ring mass mout and the inner disk mass min must equal , where A,βB are constants taken from ancient books. Now, to start making medals, the jury needs to take values for r1, p1, p2 and calculate the suitable value of r2.The jury wants to choose the value that would maximize radius r2. Help the jury find the sought value of r2. Value r2 doesn't have to be an integer.Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring. | Input: ['3 1 2 31 23 3 2 11 2'] Output:['2.683281573000'] | [
2,
3
] |
Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0β<βa1β<βa2β<β...β<βan) teeth, and the j-th star on the rear wheel axle has bj (0β<βb1β<βb2β<β...β<βbm) teeth. Any pair (i,βj) (1ββ€βiββ€βn; 1ββ€βjββ€βm) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i,βj) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i,βj), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i,βj) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction denotes division in real numbers, that is, no rounding is performed. | Input: ['24 5312 13 15'] Output:['2'] | [
0
] |
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | Input: ['10'] Output:['0'] | [
0,
2,
3
] |
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a system of equations: You should count, how many there are pairs of integers (a,βb) (0ββ€βa,βb) which satisfy the system. | Input: ['9 3'] Output:['1'] | [
0
] |
Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies. Rubik has 3 computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from 1 to 3. Rubik can perform the following actions: Complete some part of the game on some computer. Rubik spends exactly 1 hour on completing any part on any computer. Move from the 1-st computer to the 2-nd one. Rubik spends exactly 1 hour on that. Move from the 1-st computer to the 3-rd one. Rubik spends exactly 2 hours on that. Move from the 2-nd computer to the 1-st one. Rubik spends exactly 2 hours on that. Move from the 2-nd computer to the 3-rd one. Rubik spends exactly 1 hour on that. Move from the 3-rd computer to the 1-st one. Rubik spends exactly 1 hour on that. Move from the 3-rd computer to the 2-nd one. Rubik spends exactly 2 hours on that. Help Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary. | Input: ['110'] Output:['1'] | [
2
] |
Vasya the carpenter has an estate that is separated from the wood by a fence. The fence consists of n planks put in a line. The fence is not closed in a circle. The planks are numbered from left to right from 1 to n, the i-th plank is of height ai. All planks have the same width, the lower edge of each plank is located at the ground level.Recently a local newspaper "Malevich and Life" wrote that the most fashionable way to decorate a fence in the summer is to draw a fuchsia-colored rectangle on it, the lower side of the rectangle must be located at the lower edge of the fence.Vasya is delighted with this idea! He immediately bought some fuchsia-colored paint and began to decide what kind of the rectangle he should paint. Vasya is sure that the rectangle should cover k consecutive planks. In other words, he will paint planks number x, xβ+β1, ..., xβ+βkβ-β1 for some x (1ββ€βxββ€βnβ-βkβ+β1). He wants to paint the rectangle of maximal area, so the rectangle height equals min ai for xββ€βiββ€βxβ+βkβ-β1, x is the number of the first colored plank.Vasya has already made up his mind that the rectangle width can be equal to one of numbers of the sequence k1,βk2,β...,βkm. For each ki he wants to know the expected height of the painted rectangle, provided that he selects x for such fence uniformly among all nβ-βkiβ+β1 possible values. Help him to find the expected heights. | Input: ['33 2 131 2 3'] Output:['2.0000000000000001.5000000000000001.000000000000000'] | [
4
] |
A very tense moment: n cowboys stand in a circle and each one points his colt at a neighbor. Each cowboy can point the colt to the person who follows or precedes him in clockwise direction. Human life is worthless, just like in any real western.The picture changes each second! Every second the cowboys analyse the situation and, if a pair of cowboys realize that they aim at each other, they turn around. In a second all such pairs of neighboring cowboys aiming at each other turn around. All actions happen instantaneously and simultaneously in a second.We'll use character "A" to denote a cowboy who aims at his neighbour in the clockwise direction, and character "B" for a cowboy who aims at his neighbour in the counter clockwise direction. Then a string of letters "A" and "B" will denote the circle of cowboys, the record is made from the first of them in a clockwise direction.For example, a circle that looks like "ABBBABBBA" after a second transforms into "BABBBABBA" and a circle that looks like "BABBA" transforms into "ABABB". This picture illustrates how the circle "BABBA" transforms into "ABABB" A second passed and now the cowboys' position is described by string s. Your task is to determine the number of possible states that lead to s in a second. Two states are considered distinct if there is a cowboy who aims at his clockwise neighbor in one state and at his counter clockwise neighbor in the other state. | Input: ['BABBBABBA'] Output:['2'] | [
3
] |
Vasya went for a walk in the park. The park has n glades, numbered from 1 to n. There are m trails between the glades. The trails are numbered from 1 to m, where the i-th trail connects glades xi and yi. The numbers of the connected glades may be the same (xiβ=βyi), which means that a trail connects a glade to itself. Also, two glades may have several non-intersecting trails between them.Vasya is on glade 1, he wants to walk on all trails of the park exactly once, so that he can eventually return to glade 1. Unfortunately, Vasya does not know whether this walk is possible or not. Help Vasya, determine whether the walk is possible or not. If such walk is impossible, find the minimum number of trails the authorities need to add to the park in order to make the described walk possible.Vasya can shift from one trail to another one only on glades. He can move on the trails in both directions. If Vasya started going on the trail that connects glades a and b, from glade a, then he must finish this trail on glade b. | Input: ['3 31 22 33 1'] Output:['0'] | [
2
] |
Flatland is inhabited by pixels of three colors: red, green and blue. We know that if two pixels of different colors meet in a violent fight, only one of them survives the fight (that is, the total number of pixels decreases by one). Besides, if pixels of colors x and y (xββ βy) meet in a violent fight, then the pixel that survives the fight immediately changes its color to z (zββ βx; zββ βy). Pixels of the same color are friends, so they don't fight.The King of Flatland knows that his land will be peaceful and prosperous when the pixels are of the same color. For each of the three colors you know the number of pixels of this color that inhabit Flatland. Help the king and determine whether fights can bring peace and prosperity to the country and if it is possible, find the minimum number of fights needed to make the land peaceful and prosperous. | Input: ['1 1 1'] Output:['1'] | [
3
] |
Polycarpus plays with red and blue marbles. He put n marbles from the left to the right in a row. As it turned out, the marbles form a zebroid.A non-empty sequence of red and blue marbles is a zebroid, if the colors of the marbles in this sequence alternate. For example, sequences (red; blue; red) and (blue) are zebroids and sequence (red; red) is not a zebroid.Now Polycarpus wonders, how many ways there are to pick a zebroid subsequence from this sequence. Help him solve the problem, find the number of ways modulo 1000000007 (109β+β7). | Input: ['3'] Output:['6'] | [
3
] |
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (kβ>β1) of person b, if person b has a 1-ancestor, and a is a (kβ-β1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, xβ>β0).Let's call two people x and y (xββ βy) p-th cousins (pβ>β0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi. | Input: ['60 1 1 0 4 471 11 22 12 24 15 16 1'] Output:['0 0 1 0 0 1 1 '] | [
4
] |
The Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scientist brought ki calculating problems for the device developed by the Smart Beaver from ABBYY. The problems of the i-th scientist are numbered from 1 to ki, and they must be calculated sequentially in the described order, since calculating each problem heavily depends on the results of calculating of the previous ones.Each problem of each of the n scientists is described by one integer ai,βj, where i (1ββ€βiββ€βn) is the number of the scientist, j (1ββ€βjββ€βki) is the number of the problem, and ai,βj is the number of resource units the calculating device needs to solve this problem.The calculating device that is developed by the Smart Beaver is pretty unusual. It solves problems sequentially, one after another. After some problem is solved and before the next one is considered, the calculating device allocates or frees resources.The most expensive operation for the calculating device is freeing resources, which works much slower than allocating them. It is therefore desirable that each next problem for the calculating device requires no less resources than the previous one.You are given the information about the problems the scientists offered for the testing. You need to arrange these problems in such an order that the number of adjacent "bad" pairs of problems in this list is minimum possible. We will call two consecutive problems in this list a "bad pair" if the problem that is performed first requires more resources than the one that goes after it. Do not forget that the problems of the same scientist must be solved in a fixed order. | Input: ['22 1 1 1 102 3 1 1 10'] Output:['01 12 13 24 2'] | [
2
] |
The Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scientist brought ki calculating problems for the device developed by the Smart Beaver from ABBYY. The problems of the i-th scientist are numbered from 1 to ki, and they must be calculated sequentially in the described order, since calculating each problem heavily depends on the results of calculating of the previous ones.Each problem of each of the n scientists is described by one integer ai,βj, where i (1ββ€βiββ€βn) is the number of the scientist, j (1ββ€βjββ€βki) is the number of the problem, and ai,βj is the number of resource units the calculating device needs to solve this problem.The calculating device that is developed by the Smart Beaver is pretty unusual. It solves problems sequentially, one after another. After some problem is solved and before the next one is considered, the calculating device allocates or frees resources.The most expensive operation for the calculating device is freeing resources, which works much slower than allocating them. It is therefore desirable that each next problem for the calculating device requires no less resources than the previous one.You are given the information about the problems the scientists offered for the testing. You need to arrange these problems in such an order that the number of adjacent "bad" pairs of problems in this list is minimum possible. We will call two consecutive problems in this list a "bad pair" if the problem that is performed first requires more resources than the one that goes after it. Do not forget that the problems of the same scientist must be solved in a fixed order. | Input: ['22 1 1 1 102 3 1 1 10'] Output:['01 12 13 24 2'] | [
2
] |
The Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scientist brought ki calculating problems for the device developed by the Smart Beaver from ABBYY. The problems of the i-th scientist are numbered from 1 to ki, and they must be calculated sequentially in the described order, since calculating each problem heavily depends on the results of calculating of the previous ones.Each problem of each of the n scientists is described by one integer ai,βj, where i (1ββ€βiββ€βn) is the number of the scientist, j (1ββ€βjββ€βki) is the number of the problem, and ai,βj is the number of resource units the calculating device needs to solve this problem.The calculating device that is developed by the Smart Beaver is pretty unusual. It solves problems sequentially, one after another. After some problem is solved and before the next one is considered, the calculating device allocates or frees resources.The most expensive operation for the calculating device is freeing resources, which works much slower than allocating them. It is therefore desirable that each next problem for the calculating device requires no less resources than the previous one.You are given the information about the problems the scientists offered for the testing. You need to arrange these problems in such an order that the number of adjacent "bad" pairs of problems in this list is minimum possible. We will call two consecutive problems in this list a "bad pair" if the problem that is performed first requires more resources than the one that goes after it. Do not forget that the problems of the same scientist must be solved in a fixed order. | Input: ['22 1 1 1 102 3 1 1 10'] Output:['01 12 13 24 2'] | [
2
] |
The Little Elephant loves sortings.He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1ββ€βlββ€βrββ€βn) and increase ai by 1 for all i such that lββ€βiββ€βr.Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1ββ€βiβ<βn) aiββ€βaiβ+β1 holds. | Input: ['31 2 3'] Output:['0'] | [
0,
2
] |
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil. | Input: ['27 4'] Output:['2'] | [
0
] |
Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.The Little Elephant has two strings of equal length a and b, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length β the first one from string a, the second one from string b. The choice is equiprobable among all possible pairs. Let's denote the substring of a as x, and the substring of b β as y. The Little Elephant gives string x to Furik and string y β to Rubik.Let's assume that f(x,βy) is the number of such positions of i (1ββ€βiββ€β|x|), that xiβ=βyi (where |x| is the length of lines x and y, and xi, yi are the i-th characters of strings x and y, correspondingly). Help Furik and Rubik find the expected value of f(x,βy). | Input: ['2ABBA'] Output:['0.400000000'] | [
3
] |
The Little Elephant loves to play with color cards.He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. | Input: ['34 74 77 4'] Output:['0'] | [
4
] |
The Little Elephant very much loves sums on intervals.This time he has a pair of integers l and r (lββ€βr). The Little Elephant has to find the number of such integers x (lββ€βxββ€βr), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not.Help him and count the number of described numbers x for a given pair l and r. | Input: ['2 47'] Output:['12'] | [
4
] |
Valera came to Japan and bought many robots for his research. He's already at the airport, the plane will fly very soon and Valera urgently needs to bring all robots to the luggage compartment.The robots are self-propelled (they can potentially move on their own), some of them even have compartments to carry other robots. More precisely, for the i-th robot we know value ci β the number of robots it can carry. In this case, each of ci transported robots can additionally carry other robots.However, the robots need to be filled with fuel to go, so Valera spent all his last money and bought S liters of fuel. He learned that each robot has a restriction on travel distances. Thus, in addition to features ci, the i-th robot has two features fi and li β the amount of fuel (in liters) needed to move the i-th robot, and the maximum distance that the robot can go.Due to the limited amount of time and fuel, Valera wants to move the maximum number of robots to the luggage compartment. He operates as follows. First Valera selects some robots that will travel to the luggage compartment on their own. In this case the total amount of fuel required to move all these robots must not exceed S. Then Valera seats the robots into the compartments, so as to transport as many robots as possible. Note that if a robot doesn't move by itself, you can put it in another not moving robot that is moved directly or indirectly by a moving robot. After that all selected and seated robots along with Valera go to the luggage compartment and the rest robots will be lost. There are d meters to the luggage compartment. Therefore, the robots that will carry the rest, must have feature li of not less than d. During the moving Valera cannot stop or change the location of the robots in any way.Help Valera calculate the maximum number of robots that he will be able to take home, and the minimum amount of fuel he will have to spend, because the remaining fuel will come in handy in Valera's research. | Input: ['3 10 100 12 101 6 100 1 1'] Output:['2 6'] | [
2
] |
When Valera was playing football on a stadium, it suddenly began to rain. Valera hid in the corridor under the grandstand not to get wet. However, the desire to play was so great that he decided to train his hitting the ball right in this corridor. Valera went back far enough, put the ball and hit it. The ball bounced off the walls, the ceiling and the floor corridor and finally hit the exit door. As the ball was wet, it left a spot on the door. Now Valera wants to know the coordinates for this spot.Let's describe the event more formally. The ball will be considered a point in space. The door of the corridor will be considered a rectangle located on plane xOz, such that the lower left corner of the door is located at point (0,β0,β0), and the upper right corner is located at point (a,β0,βb) . The corridor will be considered as a rectangular parallelepiped, infinite in the direction of increasing coordinates of y. In this corridor the floor will be considered as plane xOy, and the ceiling as plane, parallel to xOy and passing through point (a,β0,βb). We will also assume that one of the walls is plane yOz, and the other wall is plane, parallel to yOz and passing through point (a,β0,βb).We'll say that the ball hit the door when its coordinate y was equal to 0. Thus the coordinates of the spot are point (x0,β0,βz0), where 0ββ€βx0ββ€βa,β0ββ€βz0ββ€βb. To hit the ball, Valera steps away from the door at distance m and puts the ball in the center of the corridor at point . After the hit the ball flies at speed (vx,βvy,βvz). This means that if the ball has coordinates (x,βy,βz), then after one second it will have coordinates (xβ+βvx,βyβ+βvy,βzβ+βvz).See image in notes for clarification.When the ball collides with the ceiling, the floor or a wall of the corridor, it bounces off in accordance with the laws of reflection (the angle of incidence equals the angle of reflection). In the problem we consider the ideal physical model, so we can assume that there is no air resistance, friction force, or any loss of energy. | Input: ['7 2 113 -11 2'] Output:['6.5000000000 2.0000000000'] | [
3
] |
Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos.Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up.Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients. | Input: ['3 102 31 42 11 0'] Output:['23 2 '] | [
2
] |
One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.He took a checkered white square piece of paper, consisting of nβΓβn cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him.Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. | Input: ['4 111 11 21 32 22 31 42 43 43 23 34 1'] Output:['10'] | [
0
] |
A boy Valera registered on site Codeforces as Valera, and wrote his first Codeforces Round #300. He boasted to a friend Arkady about winning as much as x points for his first contest. But Arkady did not believe his friend's words and decided to check whether Valera could have shown such a result.He knows that the contest number 300 was unusual because there were only two problems. The contest lasted for t minutes, the minutes are numbered starting from zero. The first problem had the initial cost of a points, and every minute its cost reduced by da points. The second problem had the initial cost of b points, and every minute this cost reduced by db points. Thus, as soon as the zero minute of the contest is over, the first problem will cost aβ-βda points, and the second problem will cost bβ-βdb points. It is guaranteed that at any moment of the contest each problem has a non-negative cost.Arkady asks you to find out whether Valera could have got exactly x points for this contest. You should assume that Valera could have solved any number of the offered problems. You should also assume that for each problem Valera made no more than one attempt, besides, he could have submitted both problems at the same minute of the contest, starting with minute 0 and ending with minute number tβ-β1. Please note that Valera can't submit a solution exactly t minutes after the start of the contest or later. | Input: ['30 5 20 20 3 5'] Output:['YES'] | [
0
] |
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem β a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as , where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise. | Input: ['4find the next palindrome110 find the previous palindrome or print better luck next time'] Output:['1[:||||||:]'] | [
0
] |
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 ββ€β p1β<βp2β<β...β<βpk ββ€β |s|) a subsequence of string s = s1s2... s|s|, where |s| is the length of string s. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba".String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y| if either |x| > |y| and x1β=βy1, x2β=βy2, ...,βx|y|β=βy|y|, or there exists such number r (rβ<β|x|, rβ<β|y|) that x1β=βy1, x2β=βy2, ..., xrβ=βyr and xrββ+ββ1β>βyrββ+ββ1. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post".String s = s1s2... s|s| is a palindrome if it matches string rev(s) = s|s|s|s|β-β1... s1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z". | Input: ['radar'] Output:['rr'] | [
0,
2,
4
] |
Once n people simultaneously signed in to the reception at the recently opened, but already thoroughly bureaucratic organization (abbreviated TBO). As the organization is thoroughly bureaucratic, it can accept and cater for exactly one person per day. As a consequence, each of n people made an appointment on one of the next n days, and no two persons have an appointment on the same day.However, the organization workers are very irresponsible about their job, so none of the signed in people was told the exact date of the appointment. The only way to know when people should come is to write some requests to TBO.The request form consists of m empty lines. Into each of these lines the name of a signed in person can be written (it can be left blank as well). Writing a person's name in the same form twice is forbidden, such requests are ignored. TBO responds very quickly to written requests, but the reply format is of very poor quality β that is, the response contains the correct appointment dates for all people from the request form, but the dates are in completely random order. Responds to all requests arrive simultaneously at the end of the day (each response specifies the request that it answers).Fortunately, you aren't among these n lucky guys. As an observer, you have the following task β given n and m, determine the minimum number of requests to submit to TBO to clearly determine the appointment date for each person. | Input: ['54 14 27 31 142 7'] Output:['323011'] | [
4
] |
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem β a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as , where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise. | Input: ['4find the next palindrome110 find the previous palindrome or print better luck next time'] Output:['1[:||||||:]'] | [
0
] |
A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".The game show takes place on a giant parking lot, which is 4n meters long from north to south and 4m meters wide from west to east. The lot has nβ+β1 dividing lines drawn from west to east and mβ+β1 dividing lines drawn from north to south, which divide the parking lot into nΒ·m 4 by 4 meter squares. There is a car parked strictly inside each square. The dividing lines are numbered from 0 to n from north to south and from 0 to m from west to east. Each square has coordinates (i,βj) so that the square in the north-west corner has coordinates (1,β1) and the square in the south-east corner has coordinates (n,βm). See the picture in the notes for clarifications.Before the game show the organizers offer Yura to occupy any of the (nβ+β1)Β·(mβ+β1) intersection points of the dividing lines. After that he can start guessing the cars. After Yura chooses a point, he will be prohibited to move along the parking lot before the end of the game show. As Yura is a car expert, he will always guess all cars he is offered, it's just a matter of time. Yura knows that to guess each car he needs to spend time equal to the square of the euclidean distance between his point and the center of the square with this car, multiplied by some coefficient characterizing the machine's "rarity" (the rarer the car is, the harder it is to guess it). More formally, guessing a car with "rarity" c placed in a square whose center is at distance d from Yura takes cΒ·d2 seconds. The time Yura spends on turning his head can be neglected.It just so happened that Yura knows the "rarity" of each car on the parking lot in advance. Help him choose his point so that the total time of guessing all cars is the smallest possible. | Input: ['2 33 4 53 9 1'] Output:['3921 1'] | [
3,
4
] |
Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai,βj.Let's call matrix A clear if no two cells containing ones have a common side.Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i,βj) (1ββ€βi,βjββ€βn) both of the following conditions must be met: Ai,βjβ=βAnβ-βiβ+β1,βj and Ai,βjβ=βAi,βnβ-βjβ+β1.Let's define the sharpness of matrix A as the number of ones in it.Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. | Input: ['4'] Output:['3'] | [
3
] |
While most students still sit their exams, the tractor college has completed the summer exam session. In fact, students study only one subject at this college β the Art of Operating a Tractor. Therefore, at the end of a term a student gets only one mark, a three (satisfactory), a four (good) or a five (excellent). Those who score lower marks are unfortunately expelled.The college has n students, and oddly enough, each of them can be on scholarship. The size of the scholarships varies each term. Since the end-of-the-term exam has just ended, it's time to determine the size of the scholarship to the end of next term.The monthly budget for the scholarships of the Tractor college is s rubles. To distribute the budget optimally, you must follow these rules: The students who received the same mark for the exam, should receive the same scholarship; Let us denote the size of the scholarship (in roubles) for students who have received marks 3, 4 and 5 for the exam, as k3, k4 and k5, respectively. The values k3, k4 and k5 must be integers and satisfy the inequalities 0ββ€βk3ββ€βk4ββ€βk5; Let's assume that c3, c4, c5 show how many students received marks 3, 4 and 5 for the exam, respectively. The budget of the scholarship should be fully spent on them, that is, c3Β·k3β+βc4Β·k4β+βc5Β·k5β=βs; Let's introduce function β the value that shows how well the scholarships are distributed between students. In the optimal distribution function f(k3,βk4,βk5) takes the minimum possible value. Given the results of the exam, and the budget size s, you have to find the optimal distribution of the scholarship. | Input: ['5 113 4 3 5 5'] Output:['1 3 3'] | [
3,
4
] |
Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, default values).Valery decided to examine template procedures in this language in more detail. The description of a template procedure consists of the procedure name and the list of its parameter types. The generic type T parameters can be used as parameters of template procedures.A procedure call consists of a procedure name and a list of variable parameters. Let's call a procedure suitable for this call if the following conditions are fulfilled: its name equals to the name of the called procedure; the number of its parameters equals to the number of parameters of the procedure call; the types of variables in the procedure call match the corresponding types of its parameters. The variable type matches the type of a parameter if the parameter has a generic type T or the type of the variable and the parameter are the same. You are given a description of some set of template procedures. You are also given a list of variables used in the program, as well as direct procedure calls that use the described variables. For each call you need to count the number of procedures that are suitable for this call. | Input: ['4void f(int,T)void f(T, T) void foo123 ( int, double, string,string ) void p(T,double)3int a string sdouble x123 5f(a, a) f(s,a )foo (a,s,s) f ( s ,x123)proc(a)'] Output:['21010'] | [
0,
4
] |
Any resemblance to any real championship and sport is accidental.The Berland National team takes part in the local Football championship which now has a group stage. Let's describe the formal rules of the local championship: the team that kicked most balls in the enemy's goal area wins the game; the victory gives 3 point to the team, the draw gives 1 point and the defeat gives 0 points; a group consists of four teams, the teams are ranked by the results of six games: each team plays exactly once with each other team; the teams that get places 1 and 2 in the group stage results, go to the next stage of the championship. In the group stage the team's place is defined by the total number of scored points: the more points, the higher the place is. If two or more teams have the same number of points, then the following criteria are used (the criteria are listed in the order of falling priority, starting from the most important one): the difference between the total number of scored goals and the total number of missed goals in the championship: the team with a higher value gets a higher place; the total number of scored goals in the championship: the team with a higher value gets a higher place; the lexicographical order of the name of the teams' countries: the country with the lexicographically smaller name gets a higher place. The Berland team plays in the group where the results of 5 out of 6 games are already known. To be exact, there is the last game left. There the Berand national team plays with some other team. The coach asks you to find such score X:Y (where X is the number of goals Berland scored and Y is the number of goals the opponent scored in the game), that fulfills the following conditions: X > Y, that is, Berland is going to win this game; after the game Berland gets the 1st or the 2nd place in the group; if there are multiple variants, you should choose such score X:Y, where value Xβ-βY is minimum; if it is still impossible to come up with one score, you should choose the score where value Y (the number of goals Berland misses) is minimum. | Input: ['AERLAND DERLAND 2:1DERLAND CERLAND 0:3CERLAND AERLAND 0:1AERLAND BERLAND 2:0DERLAND BERLAND 4:0'] Output:['6:0'] | [
0
] |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. Then he wondered, how much orange juice the cocktail has.Find the volume fraction of orange juice in the final drink. | Input: ['350 50 100'] Output:['66.666666666667'] | [
3
] |
The capital of Berland has the only movie theater in the country. Besides, it consists of only one room. The room is divided into n rows, each row consists of m seats.There are k people lined up to the box office, each person wants to buy exactly one ticket for his own entertainment. Before the box office started selling tickets, each person found the seat that seemed best for him and remembered it as a pair of coordinates (xi,βyi), where xi is the row number, and yi is the seat number in this row.It is possible that some people have chosen the same place, then when some people see their favorite seat taken in the plan of empty seats in the theater, they choose and buy a ticket to another place. Each of them has the following logic: let's assume that he originally wanted to buy a ticket to seat (x1,βy1), then when he comes to the box office, he chooses such empty seat (x2,βy2), which satisfies the following conditions: the value of |x1β-βx2|β+β|y1β-βy2| is minimum if the choice is not unique, then among the seats that satisfy the first condition, this person selects the one for which the value of x2 is minimum if the choice is still not unique, among the seats that satisfy the first and second conditions, this person selects the one for which the value of y2 is minimum Your task is to find the coordinates of a seat for each person. | Input: ['3 4 61 11 11 11 21 31 3'] Output:['1 11 22 11 31 42 3'] | [
0
] |
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.Let's remember how Fibonacci numbers can be calculated. F0β=β0, F1β=β1, and all the next numbers are Fiβ=βFiβ-β2β+βFiβ-β1.So, Fibonacci numbers make a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, ...If you haven't run away from the PC in fear, you have to help the virus. Your task is to divide given Fibonacci number n by three not necessary different Fibonacci numbers or say that it is impossible. | Input: ['3'] Output:['1 1 1'] | [
0
] |
One day Qwerty the Ranger witnessed two transport ships collide with each other. As a result, all contents of their cargo holds scattered around the space. And now Qwerty wants to pick as many lost items as possible to sell them later.The thing is, both ships had lots of new gravitational grippers, transported to sale. A gripper is a device that can be installed on a spaceship and than draw items in space to itself ("grip") and transport them to the ship's cargo hold. Overall the crashed ships lost n gravitational grippers: the i-th gripper is located at a point with coordinates (xi,βyi). Each gripper has two features β pi (the power) and ri (the action radius) and can grip any items with mass of no more than pi at distance no more than ri. A gripper itself is an item, too and it has its mass of mi.Qwerty's ship is located at point (x,βy) and has an old magnetic gripper installed, its characteristics are p and r. There are no other grippers in the ship's cargo holds.Find the largest number of grippers Qwerty can get hold of. As he picks the items, he can arbitrarily install any gripper in the cargo hold of the ship, including the gripper he has just picked. At any moment of time the ship can have only one active gripper installed. We consider all items and the Qwerty's ship immobile when the ranger picks the items, except for when the gripper moves an item β then the item moves to the cargo holds and the ship still remains immobile. We can assume that the ship's cargo holds have enough room for all grippers. Qwerty can use any gripper he finds or the initial gripper an arbitrary number of times. | Input: ['0 0 5 10 55 4 7 11 5-7 1 4 7 80 2 13 5 62 -3 9 3 413 5 1 9 9'] Output:['3'] | [
4
] |
Qwerty the Ranger arrived to the Diatar system with a very important task. He should deliver a special carcinogen for scientific research to planet Persephone. This is urgent, so Qwerty has to get to the planet as soon as possible. A lost day may fail negotiations as nobody is going to pay for an overdue carcinogen.You can consider Qwerty's ship, the planet Persephone and the star Diatar points on a plane. Diatar is located in the origin of coordinate axes β at point (0,β0). Persephone goes round Diatar along a circular orbit with radius R in the counter-clockwise direction at constant linear speed vp (thus, for instance, a full circle around the star takes of time). At the initial moment of time Persephone is located at point (xp,βyp).At the initial moment of time Qwerty's ship is at point (x,βy). Qwerty can move in any direction at speed of at most v (vβ>βvp). The star Diatar is hot (as all stars), so Qwerty can't get too close to it. The ship's metal sheathing melts at distance r (rβ<βR) from the star.Find the minimum time Qwerty needs to get the carcinogen to planet Persephone. | Input: ['10 0 1-10 0 2 8'] Output:['9.584544103'] | [
4
] |
Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high.At the beginning of the first experiment there is a single bacterium in the test tube. Every second each bacterium in the test tube divides itself into k bacteria. After that some abnormal effects create b more bacteria in the test tube. Thus, if at the beginning of some second the test tube had x bacteria, then at the end of the second it will have kxβ+βb bacteria.The experiment showed that after n seconds there were exactly z bacteria and the experiment ended at this point.For the second experiment Qwerty is going to sterilize the test tube and put there t bacteria. He hasn't started the experiment yet but he already wonders, how many seconds he will need to grow at least z bacteria. The ranger thinks that the bacteria will divide by the same rule as in the first experiment. Help Qwerty and find the minimum number of seconds needed to get a tube with at least z bacteria in the second experiment. | Input: ['3 1 3 5'] Output:['2'] | [
3
] |
You are given two polynomials: P(x)β=βa0Β·xnβ+βa1Β·xnβ-β1β+β...β+βanβ-β1Β·xβ+βan and Q(x)β=βb0Β·xmβ+βb1Β·xmβ-β1β+β...β+βbmβ-β1Β·xβ+βbm. Calculate limit . | Input: ['2 11 1 12 5'] Output:['Infinity'] | [
3
] |
You've got a rectangular table with length a and width b and the infinite number of plates of radius r. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the table's border. During the game one cannot move the plates that already lie on the table. The player who cannot make another move loses. Determine which player wins, the one who moves first or the one who moves second, provided that both players play optimally well. | Input: ['5 5 2'] Output:['First'] | [
3
] |
In problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to d. You are given string s, consisting only of lowercase English letters. Find a good string t with length |s|, consisting of lowercase English letters, which is lexicographically larger than s. Of all such strings string t must be lexicographically minimum.We will call a non-empty string s[a ... b]β=βsasaβ+β1... sb (1ββ€βaββ€βbββ€β|s|) a substring of string sβ=βs1s2... s|s|.A non-empty string sβ=βs1s2... sn is called a palindrome if for all i from 1 to n the following fulfills: siβ=βsnβ-βiβ+β1. In other words, palindrome read the same in both directions.String xβ=βx1x2... x|x| is lexicographically larger than string yβ=βy1y2... y|y|, if either |x|β>β|y| and x1β=βy1,βx2β=βy2,β... ,βx|y|β=βy|y|, or there exists such number r (rβ<β|x|,βrβ<β|y|), that x1β=βy1,βx2β=βy2,β... ,βxrβ=βyr and xrβ+β1β>βyrβ+β1. Characters in such strings are compared like their ASCII codes. | Input: ['3aaaaaaa'] Output:['aabbcaa'] | [
2
] |
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk]β=βsp1sp2... spk(1ββ€βp1β<βp2β<β...β<βpkββ€β|s|) a subsequence of string sβ=βs1s2... s|s|.String xβ=βx1x2... x|x| is lexicographically larger than string yβ=βy1y2... y|y|, if either |x|β>β|y| and x1β=βy1,βx2β=βy2,β... ,βx|y|β=βy|y|, or exists such number r (rβ<β|x|,βrβ<β|y|), that x1β=βy1,βx2β=βy2,β... ,βxrβ=βyr and xrβ+β1β>βyrβ+β1. Characters in lines are compared like their ASCII codes. | Input: ['ababba'] Output:['bbba'] | [
2
] |
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form: Let's define a sum of n functions y1(x),β...,βyn(x) of the given type as function s(x)β=βy1(x)β+β...β+βyn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them. | Input: ['11 0'] Output:['1'] | [
3
] |
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The balls are numbered with numbers from 1 to n.Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which is minimum, where i is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.For every ball print the number of the basket where it will go according to Valeric's scheme.Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on. | Input: ['4 3'] Output:['2132'] | [
3
] |
Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the size of downloaded data per second.The guys want to watch the whole video without any pauses, so they have to wait some integer number of seconds for a part of the video to download. After this number of seconds passes, they can start watching. Waiting for the whole video to download isn't necessary as the video can download after the guys started to watch.Let's suppose that video's length is c seconds and Valeric and Valerko wait t seconds before the watching. Then for any moment of time t0, tββ€βt0ββ€βcβ+βt, the following condition must fulfill: the size of data received in t0 seconds is not less than the size of data needed to watch t0β-βt seconds of the video.Of course, the guys want to wait as little as possible, so your task is to find the minimum integer number of seconds to wait before turning the video on. The guys must watch the video without pauses. | Input: ['4 1 1'] Output:['3'] | [
0,
3,
4
] |