question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
The dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chance.They take turns drawing a mouse from a bag which initially contains w white and b black mice. The person who is the first to draw a white mouse wins. After each mouse drawn by the dragon the rest of mice in the bag panic, and one of them jumps out of the bag itself (the princess draws her mice carefully and doesn't scare other mice). Princess draws first. What is the probability of the princess winning?If there are no more mice in the bag and nobody has drawn a white mouse, the dragon wins. Mice which jump out of the bag themselves are not considered to be drawn (do not define the winner). Once a mouse has left the bag, it never returns to it. Every mouse is drawn from the bag with the same probability as every other one, and every mouse jumps out of the bag with the same probability as every other one.
Input: ['1 3'] Output:['0.500000000']
[ 3 ]
Β«Next pleaseΒ», β€” the princess called and cast an estimating glance at the next groom.The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured Β«Oh...Β». Whenever the groom is richer than all previous ones added together, she exclaims Β«Wow!Β» (no Β«Oh...Β» in this case). At the sight of the first groom the princess stays calm and says nothing.The fortune of each groom is described with an integer between 1 and 50000. You know that during the day the princess saw n grooms, said Β«Oh...Β» exactly a times and exclaimed Β«Wow!Β» exactly b times. Your task is to output a sequence of n integers t1, t2, ..., tn, where ti describes the fortune of i-th groom. If several sequences are possible, output any of them. If no sequence exists that would satisfy all the requirements, output a single number -1.
Input: ['10 2 3'] Output:['5 1 3 6 16 35 46 4 200 99']
[ 2 ]
The princess is going to escape the dragon's cave, and she needs to plan it carefully.The princess runs at vp miles per hour, and the dragon flies at vd miles per hour. The dragon will discover the escape after t hours and will chase the princess immediately. Looks like there's no chance to success, but the princess noticed that the dragon is very greedy and not too smart. To delay him, the princess decides to borrow a couple of bijous from his treasury. Once the dragon overtakes the princess, she will drop one bijou to distract him. In this case he will stop, pick up the item, return to the cave and spend f hours to straighten the things out in the treasury. Only after this will he resume the chase again from the very beginning.The princess is going to run on the straight. The distance between the cave and the king's castle she's aiming for is c miles. How many bijous will she need to take from the treasury to be able to reach the castle? If the dragon overtakes the princess at exactly the same moment she has reached the castle, we assume that she reached the castle before the dragon reached her, and doesn't need an extra bijou to hold him off.
Input: ['121110'] Output:['2']
[ 3 ]
Β«One dragon. Two dragon. Three dragonΒ», β€” the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every k-th dragon got punched in the face with a frying pan. Every l-th dragon got his tail shut into the balcony door. Every m-th dragon got his paws trampled with sharp heels. Finally, she threatened every n-th dragon to call her mom, and he withdrew in panic.How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of d dragons?
Input: ['123412'] Output:['12']
[ 3 ]
A smile house is created to raise the mood. It has n rooms. Some of the rooms are connected by doors. For each two rooms (number i and j), which are connected by a door, Petya knows their value cij β€” the value which is being added to his mood when he moves from room i to room j.Petya wondered whether he can raise his mood infinitely, moving along some cycle? And if he can, then what minimum number of rooms he will need to visit during one period of a cycle?
Input: ['4 41 2 -10 31 3 1 -102 4 -10 -13 4 0 -3'] Output:['4']
[ 4 ]
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number.Petya has two numbers β€” an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b.
Input: ['1 7'] Output:['7']
[ 0 ]
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has sequence a consisting of n integers.The subsequence of the sequence a is such subsequence that can be obtained from a by removing zero or more of its elements.Two sequences are considered different if index sets of numbers included in them are different. That is, the values ​of the elements ​do not matter in the comparison of subsequences. In particular, any sequence of length n has exactly 2n different subsequences (including an empty subsequence).A subsequence is considered lucky if it has a length exactly k and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times).Help Petya find the number of different lucky subsequences of the sequence a. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number 1000000007 (109 + 7).
Input: ['3 210 10 10'] Output:['3']
[ 3 ]
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types: replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4); swap any pair of digits in string a. Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.
Input: ['4774'] Output:['1']
[ 2 ]
The secondary diagonal of a square matrix is a diagonal going from the top right to the bottom left corner. Let's define an n-degree staircase as a square matrix n × n containing no squares above the secondary diagonal (the picture below shows a 5-degree staircase). The squares of the n-degree staircase contain m sportsmen. A sportsman needs one second to move to a side-neighboring square of the staircase. Before the beginning of the competition each sportsman must choose one of the shortest ways to the secondary diagonal. After the starting whistle the competition begins and all sportsmen start moving along the chosen paths. When a sportsman reaches a cell of the secondary diagonal, he stops and moves no more. The competition ends when all sportsmen reach the secondary diagonal. The competition is considered successful if during it no two sportsmen were present in the same square simultaneously. Any square belonging to the secondary diagonal also cannot contain more than one sportsman. If a sportsman at the given moment of time leaves a square and another sportsman comes to it, then they are not considered to occupy the same square simultaneously. Note that other extreme cases (for example, two sportsmen moving towards each other) are impossible as the chosen ways are the shortest ones.You are given positions of m sportsmen on the staircase. Your task is to choose among them the maximum number of sportsmen for who the competition can be successful, that is, so that there existed such choice of shortest ways for the sportsmen at which no two sportsmen find themselves in the same square simultaneously. All other sportsmen that are not chosen will be removed from the staircase before the competition starts.
Input: ['3 32 33 23 3'] Output:['31 2 3 ']
[ 2 ]
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 × 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below. The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below. Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input: ['3 74 65 5'] Output:['1 23 4']
[ 0, 3 ]
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space): ### ..# .#. #...#. ### .#. ###.#. ..# ### #.. Simon faced a quite natural challenge: placing in the given n × m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse.Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?
Input: ['3 3'] Output:['1AAA.A..A.']
[ 0 ]
Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot had a major argument with the Fairy Godmother (there were rumors that the argument occurred after the general spoke badly of the Godmother's flying techniques. That seemed to hurt the Fairy Godmother very deeply). As the result of the argument, the Godmother put a rather strange curse upon the general. It sounded all complicated and quite harmless: "If the squared distance between some two soldiers equals to 5, then those soldiers will conflict with each other!"The drill exercises are held on a rectangular n × m field, split into nm square 1 × 1 segments for each soldier. Thus, the square of the distance between the soldiers that stand on squares (x1, y1) and (x2, y2) equals exactly (x1 - x2)2 + (y1 - y2)2. Now not all nm squad soldiers can participate in the drill exercises as it was before the Fairy Godmother's curse. Unless, of course, the general wants the soldiers to fight with each other or even worse... For example, if he puts a soldier in the square (2, 2), then he cannot put soldiers in the squares (1, 4), (3, 4), (4, 1) and (4, 3) β€” each of them will conflict with the soldier in the square (2, 2).Your task is to help the general. You are given the size of the drill exercise field. You are asked to calculate the maximum number of soldiers that can be simultaneously positioned on this field, so that no two soldiers fall under the Fairy Godmother's curse.
Input: ['2 4'] Output:['4']
[ 2 ]
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored AΒ·BΒ·C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks.At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A - 1) × (B - 2) × (C - 2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1 × 1 × 1 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B ΠΈ C.Given number n, find the minimally possible and maximally possible number of stolen hay blocks.
Input: ['4'] Output:['28 41']
[ 0, 3 ]
In the Main Berland Bank n people stand in a queue at the cashier, everyone knows his/her height hi, and the heights of the other people in the queue. Each of them keeps in mind number ai β€” how many people who are taller than him/her and stand in queue in front of him.After a while the cashier has a lunch break and the people in the queue seat on the chairs in the waiting room in a random order.When the lunch break was over, it turned out that nobody can remember the exact order of the people in the queue, but everyone remembers his number ai.Your task is to restore the order in which the people stood in the queue if it is possible. There may be several acceptable orders, but you need to find any of them. Also, you need to print a possible set of numbers hi β€” the heights of people in the queue, so that the numbers ai are correct.
Input: ['4a 0b 2c 0d 0'] Output:['a 150c 170d 180b 160']
[ 2 ]
So nearly half of the winter is over and Maria is dreaming about summer. She's fed up with skates and sleds, she was dreaming about Hopscotch all night long. It's a very popular children's game. The game field, the court, looks as is shown in the figure (all blocks are square and are numbered from bottom to top, blocks in the same row are numbered from left to right). Let us describe the hopscotch with numbers that denote the number of squares in the row, staring from the lowest one: 1-1-2-1-2-1-2-(1-2)..., where then the period is repeated (1-2). The coordinate system is defined as shown in the figure. Side of all the squares are equal and have length a.Maria is a very smart and clever girl, and she is concerned with quite serious issues: if she throws a stone into a point with coordinates (x, y), then will she hit some square? If the answer is positive, you are also required to determine the number of the square.It is believed that the stone has fallen into the square if it is located strictly inside it. In other words a stone that has fallen on the square border is not considered a to hit a square.
Input: ['1 0 0'] Output:['-1']
[ 3 ]
As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest.The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.).Gennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the i-th problem will take ai minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the i-th problem always equals ai minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.).Help Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum.
Input: ['330 330 720'] Output:['2 10']
[ 2 ]
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
Input: ['71 2 3 4 5 6 7'] Output:['23 2 16 5 4']
[ 2, 4 ]
As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the i-th friend sent to Alexander a card number i.Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules: He will never send to a firend a card that this friend has sent to him. Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times.Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to n. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card.Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible.Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.
Input: ['41 2 3 44 1 3 24 3 1 23 4 2 13 1 2 4'] Output:['2 1 1 4']
[ 0, 2 ]
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input: ['4 10 4'] Output:['YES']
[ 3 ]
Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height).Boris chose m types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type.The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely.After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.
Input: ['15 5 3310 1 10015 2 3203 19 500'] Output:['640']
[ 3 ]
Katya recently started to invent programming tasks and prepare her own contests. What she does not like is boring and simple constraints. Katya is fed up with all those "N does not exceed a thousand" and "the sum of ai does not exceed a million" and she decided to come up with something a little more complicated.The last problem written by Katya deals with strings. The input is a string of small Latin letters. To make the statement longer and strike terror into the people who will solve the contest, Katya came up with the following set of k restrictions of the same type (characters in restrictions can be repeated and some restrictions may contradict each other): The number of characters c1 in a string is not less than l1 and not more than r1. ... The number of characters ci in a string is not less than li and not more than ri. ... The number of characters ck in a string is not less than lk and not more than rk. However, having decided that it is too simple and obvious, Katya added the following condition: a string meets no less than L and not more than R constraints from the above given list.Katya does not like to compose difficult and mean tests, so she just took a big string s and wants to add to the tests all its substrings that meet the constraints. However, Katya got lost in her conditions and asked you to count the number of substrings of the string s that meet the conditions (each occurrence of the substring is counted separately).
Input: ['codeforces2 0 0o 1 2e 1 2'] Output:['7']
[ 0 ]
One day Natalia was walking in the woods when she met a little mushroom gnome. The gnome told her the following story:Everybody knows that the mushroom gnomes' power lies in the magic mushrooms that grow in the native woods of the gnomes. There are n trees and m magic mushrooms in the woods: the i-th tree grows at a point on a straight line with coordinates ai and has the height of hi, the j-th mushroom grows at the point with coordinates bj and has magical powers zj.But one day wild mushroommunchers, the sworn enemies of mushroom gnomes unleashed a terrible storm on their home forest. As a result, some of the trees began to fall and crush the magic mushrooms. The supreme oracle of mushroom gnomes calculated in advance the probability for each tree that it will fall to the left, to the right or will stand on. If the tree with the coordinate x and height h falls to the left, then all the mushrooms that belong to the right-open interval [x - h, x), are destroyed. If a tree falls to the right, then the mushrooms that belong to the left-open interval (x, x + h] are destroyed. Only those mushrooms that are not hit by a single tree survive.Knowing that all the trees fall independently of each other (i.e., all the events are mutually independent, and besides, the trees do not interfere with other trees falling in an arbitrary direction), the supreme oracle was also able to quickly calculate what would be the expectation of the total power of the mushrooms which survived after the storm. His calculations ultimately saved the mushroom gnomes from imminent death.Natalia, as a good Olympiad programmer, got interested in this story, and she decided to come up with a way to quickly calculate the expectation of the sum of the surviving mushrooms' power.
Input: ['1 12 2 50 501 1'] Output:['0.5000000000']
[ 4 ]
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.Given number n, can you find the two digit permutations that have this property?
Input: ['198'] Output:['981819']
[ 2 ]
"Hey, it's homework time" β€” thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
Input: ['33 1 2'] Output:['0']
[ 2 ]
Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the xor operation is performed on this computer (and whether there is anything like it).It turned out that the operation does exist (however, it is called tor) and it works like this. Suppose that we need to calculate the value of the expression a tor b. Both numbers a and b are written in the ternary notation one under the other one (b under a). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren't transferred). For example: 1410 tor 5010 = 01123 tor 12123 = 10213 = 3410.Petya wrote numbers a and c on a piece of paper. Help him find such number b, that a tor b = c. If there are several such numbers, print the smallest one.
Input: ['14 34'] Output:['50']
[ 3 ]
Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle.
Input: ['3 3111101111'] Output:['8']
[ 0 ]
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101. The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.
Input: ['????'] Output:['00011011']
[ 2 ]
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
Input: ['0 010 1110 00 111 12 22 11 2'] Output:['YES5 6 7 81 2 3 4']
[ 0, 3 ]
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
Input: ['51 2 3 4 5'] Output:['1 1 2 3 4']
[ 2 ]
There are n players sitting at a round table. All of them have s cards of n colors in total. Besides, initially the first person had cards of only the first color, the second one had cards of only the second color and so on. They can swap the cards by the following rules: as the players swap, a player can give a card of his color only; a player can't accept a card of a color he already has (particularly, he can't take cards of his color, no matter whether he has given out all of them or not); during one swap a pair of people swaps cards (each person gives one card and takes one card). The aim of all n people is as follows: each of them should give out all the cards he had initially (that is, all cards of his color). Your task is to denote whether such sequence of swaps is possible. If the answer is positive, you should list all the swaps.
Input: ['4 82 2 2 2'] Output:['Yes44 34 21 31 2']
[ 2 ]
Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.
Input: ['5'] Output:['3']
[ 0, 3 ]
You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).
Input: ['51 2 3 4 5'] Output:['13 ']
[ 0 ]
Shakespeare is a widely known esoteric programming language in which programs look like plays by Shakespeare, and numbers are given by combinations of ornate epithets. In this problem we will have a closer look at the way the numbers are described in Shakespeare.Each constant in Shakespeare is created from non-negative powers of 2 using arithmetic operations. For simplicity we'll allow only addition and subtraction and will look for a representation of the given number which requires a minimal number of operations.You are given an integer n. You have to represent it as n = a1 + a2 + ... + am, where each of ai is a non-negative power of 2, possibly multiplied by -1. Find a representation which minimizes the value of m.
Input: ['1111'] Output:['2+2^4-2^0']
[ 2 ]
How many stars are there in the sky? A young programmer Polycarpus can't get this question out of his head! He took a photo of the starry sky using his digital camera and now he analyzes the resulting monochrome digital picture. The picture is represented by a rectangular matrix consisting of n lines each containing m characters. A character equals '1', if the corresponding photo pixel is white and '0', if it is black.Polycarpus thinks that he has found a star on the photo if he finds a white pixel surrounded by four side-neighboring pixels that are also white: 1 111 1 a star on the photo Polycarpus whats to cut out a rectangular area from the photo and give his mom as a present. This area should contain no less than k stars. The stars can intersect, have shared white pixels on the photo. The boy will cut out the rectangular area so that its borders will be parallel to the sides of the photo and the cuts will go straight between the pixel borders.Now Polycarpus keeps wondering how many ways there are to cut an area out of the photo so that it met the conditions given above. Help Polycarpus find this number.
Input: ['4 6 2111000111100011011000111'] Output:['6']
[ 4 ]
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the troupe are considered different.Perform all calculations in the 64-bit type: long long for Π‘/Π‘++, int64 for Delphi and long for Java.
Input: ['5 2 5'] Output:['10']
[ 3 ]
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≀ ti ≀ 10). Of course, one number can be assigned to any number of customers."Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1,  - 1, 1,  - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.Of course, a client can't form a couple with him/herself.
Input: ['5-3 3 0 0 3'] Output:['3']
[ 3 ]
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.
Input: ['3 31 22 33 1'] Output:['0']
[ 0 ]
Anna's got a birthday today. She invited many guests and cooked a huge (nearly infinite) birthday cake decorated by n banana circles of different sizes. Maria's birthday is about to start in 7 minutes too, and while Anna is older, she decided to play the boss a little. She told Maria to cut the cake by k straight-line cuts (the cutting lines can intersect) to divide banana circles into banana pieces. Anna has many guests and she wants everyone to get at least one banana piece. That's why she told Maria to make the total number of banana pieces maximum. It's not a problem if some banana pieces end up on the same cake piece β€” the key is to make the maximum number of banana pieces. Determine what result Maria will achieve.
Input: ['1 10 0 1'] Output:['2']
[ 3 ]
One day in the IT lesson Anna and Maria learned about the lexicographic order.String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≀ i ≀ min(|x|, |y|)), that xi < yi, and for any j (1 ≀ j < i) xj = yj. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​.The teacher gave Anna and Maria homework. She gave them a string of length n. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the k-th string from the list. Help Anna and Maria do the homework.
Input: ['aa2'] Output:['a']
[ 0 ]
Doctor prescribed medicine to his patient. The medicine is represented by pills. Each pill consists of a shell and healing powder. The shell consists of two halves; each half has one of four colors β€” blue, red, white or yellow.The doctor wants to put 28 pills in a rectangular box 7 × 8 in size. Besides, each pill occupies exactly two neighboring cells and any cell contains exactly one half of a pill. Thus, the result is a four colored picture 7 × 8 in size.The doctor thinks that a patient will recover sooner if the picture made by the pills will be special. Unfortunately, putting the pills in the box so as to get the required picture is not a very easy task. That's why doctor asks you to help. Doctor has some amount of pills of each of 10 painting types. They all contain the same medicine, that's why it doesn't matter which 28 of them will be stored inside the box.Place the pills in the box so that the required picture was formed. If it is impossible to place the pills in the required manner, then place them so that the number of matching colors in all 56 cells in the final arrangement and the doctor's picture were maximum.
Input: ['WWWBBWWWWWWBBWWWYYWBBWWWYYWBBWRRYYWBBWRRYYWBBWRRYYWBBWRR0 0 0 80 1 51 105'] Output:['53W.W.W.B.B.W.W.W|.|.|.|.|.|.|.|W.W.W.B.B.W.W.W...............Y.Y.W.B.B.W.W-W|.|.|.|.|.|....Y.Y.W.B.B.W.R.R............|.|Y.Y.W.B.B.R.R.R|.|.|.|.|.|....Y.Y.W.B.B.W.R.R............|.|Y-Y.B-B.B-B.R.R']
[ 0 ]
Fibonacci numbers have the following form:F1 = 1,  F2 = 2,  Fi = Fi - 1 + Fi - 2, i > 2.Let's consider some non-empty set S = {s1, s2, ..., sk}, consisting of different Fibonacci numbers. Let's find the sum of values of this set's elements:Let's call the set S a number n's decomposition into Fibonacci sum. It's easy to see that several numbers have several decompositions into Fibonacci sum. For example, for 13 we have 13, 5 + 8, 2 + 3 + 8 β€” three decompositions, and for 16: 3 + 13, 1 + 2 + 13, 3 + 5 + 8, 1 + 2 + 5 + 8 β€” four decompositions.By the given number n determine the number of its possible different decompositions into Fibonacci sum.
Input: ['21316'] Output:['34']
[ 3 ]
After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers.The display is represented by n × n square of pixels, each of which can be either black or white. The display rows are numbered with integers from 1 to n upside down, the columns are numbered with integers from 1 to n from the left to the right. The display can perform commands like "x, y". When a traditional display fulfills such command, it simply inverts a color of (x, y), where x is the row number and y is the column number. But in our new display every pixel that belongs to at least one of the segments (x, x) - (x, y) and (y, y) - (x, y) (both ends of both segments are included) inverts a color.For example, if initially a display 5 × 5 in size is absolutely white, then the sequence of commands (1, 4), (3, 5), (5, 1), (3, 3) leads to the following changes: You are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white.
Input: ['50111010010100011001111110'] Output:['4']
[ 2 ]
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input: ['fixprefixsuffix'] Output:['fix']
[ 4 ]
Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can transmit from 0 to x2 water units per second.If y1 water units per second flow through the first tap and y2 water units per second flow through the second tap, then the resulting bath water temperature will be:Bob wants to open both taps so that the bath water temperature was not less than t0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible.Determine how much each tap should be opened so that Bob was pleased with the result in the end.
Input: ['10 70 100 100 25'] Output:['99 33']
[ 0, 3, 4 ]
The MST (Meaningless State Team) company won another tender for an important state reform in Berland.There are n cities in Berland, some pairs of the cities are connected by roads. Each road has its price. One can move along any road in any direction. The MST team should carry out the repair works on some set of roads such that one can get from any city to any other one moving only along the repaired roads. Moreover, this set should contain exactly k capital roads (that is, the roads that start or finish in the capital). The number of the capital is 1.As the budget has already been approved, the MST Company will profit by finding the set with minimum lengths of roads.
Input: ['4 5 21 2 12 3 13 4 11 3 31 4 2'] Output:['31 5 2 ']
[ 4 ]
An arithmetic progression is such a non-empty sequence of numbers where the difference between any two successive numbers is constant. This constant number is called common difference. For example, the sequence 3, 7, 11, 15 is an arithmetic progression. The definition implies that any sequences whose length equals 1 or 2 are arithmetic and all sequences whose length equals 0 are non-arithmetic.You are given a sequence of different integers a1, a2, ..., an. You should either split it into two arithmetic progressions or find out that the operation is impossible to perform. Splitting assigns each member of the given sequence to one of two progressions, but the relative order of numbers does not change. Splitting is an inverse operation to merging.
Input: ['64 1 2 7 3 10'] Output:['1 2 3 4 7 10 ']
[ 2 ]
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input: ['4'] Output:['31 2 1 3 2 3 ']
[ 2 ]
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input: ['42'] Output:['1 2']
[ 3 ]
You are given n k-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers.
Input: ['6 4523727537523572353272537'] Output:['2700']
[ 0 ]
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy.
Input: ['3 1 1'] Output:['2']
[ 3 ]
A two dimensional array is called a bracket array if each grid contains one of the two possible brackets β€” "(" or ")". A path through the two dimensional array cells is called monotonous if any two consecutive cells in the path are side-adjacent and each cell of the path is located below or to the right from the previous one. A two dimensional array whose size equals n × m is called a correct bracket array, if any string formed by writing out the brackets on some monotonous way from cell (1, 1) to cell (n, m) forms a correct bracket sequence. Let's define the operation of comparing two correct bracket arrays of equal size (a and b) like that. Let's consider a given two dimensional array of priorities (c) β€” a two dimensional array of same size, containing different integers from 1 to nm. Let's find such position (i, j) in the two dimensional array, that ai, j ≠ bi, j. If there are several such positions, let's choose the one where number ci, j is minimum. If ai, j = "(", then a < b, otherwise a > b. If the position (i, j) is not found, then the arrays are considered equal.Your task is to find a k-th two dimensional correct bracket array. It is guaranteed that for the given sizes of n and m there will be no less than k two dimensional correct bracket arrays.
Input: ['1 2 11 2'] Output:['()']
[ 2 ]
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: |x + y| ≑ 0 (mod 2a), |x - y| ≑ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).
Input: ['2 2 1 0 0 1'] Output:['1']
[ 3 ]
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya was delivered a string s, containing only digits. He needs to find a string that represents a lucky number without leading zeroes, is not empty, is contained in s as a substring the maximum number of times.Among all the strings for which the three conditions given above are fulfilled, Petya only needs the lexicographically minimum one. Find this string for Petya.
Input: ['047'] Output:['4']
[ 0 ]
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number n is almost lucky.
Input: ['47'] Output:['YES']
[ 0 ]
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has n number segments [l1; r1], [l2; r2], ..., [ln; rn]. During one move Petya can take any segment (let it be segment number i) and replace it with segment [li + 1; ri + 1] or [li - 1; ri - 1]. In other words, during one move Petya can shift any segment to the left or to the right by a unit distance. Petya calls a number full if it belongs to each segment. That is, number x is full if for any i (1 ≀ i ≀ n) the condition li ≀ x ≀ ri is fulfilled.Petya makes no more than k moves. After that he counts the quantity of full lucky numbers. Find the maximal quantity that he can get.
Input: ['4 71 46 94 73 5'] Output:['1']
[ 4 ]
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.
Input: ['7 4'] Output:['1']
[ 0 ]
Vasya has been collecting transport tickets for quite a while now. His collection contains several thousands of tram, trolleybus and bus tickets. Vasya is already fed up with the traditional definition of what a lucky ticket is. Thus, he's looking for new perspectives on that. Besides, Vasya cannot understand why all tickets are only divided into lucky and unlucky ones. He thinks that all tickets are lucky but in different degrees. Having given the matter some thought, Vasya worked out the definition of a ticket's degree of luckiness. Let a ticket consist of 2n digits. Let's regard each digit as written as is shown on the picture: You have seen such digits on electronic clocks: seven segments are used to show digits. Each segment can either be colored or not. The colored segments form a digit. Vasya regards the digits as written in this very way and takes the right half of the ticket and puts it one the left one, so that the first digit coincides with the n + 1-th one, the second digit coincides with the n + 2-th one, ..., the n-th digit coincides with the 2n-th one. For each pair of digits, put one on another, he counts the number of segments colored in both digits and summarizes the resulting numbers. The resulting value is called the degree of luckiness of a ticket. For example, the degree of luckiness of ticket 03 equals four and the degree of luckiness of ticket 2345 equals six.You are given the number of a ticket containing 2n digits. Your task is to find among the tickets whose number exceeds the number of this ticket but also consists of 2n digits such ticket, whose degree of luckiness exceeds the degrees of luckiness of the given ticket. Moreover, if there are several such tickets, you should only choose the one with the smallest number.
Input: ['13'] Output:['20']
[ 2 ]
One day mum asked Petya to sort his toys and get rid of some of them. Petya found a whole box of toy spiders. They were quite dear to him and the boy didn't want to throw them away. Petya conjured a cunning plan: he will glue all the spiders together and attach them to the ceiling. Besides, Petya knows that the lower the spiders will hang, the more mum is going to like it and then she won't throw his favourite toys away. Help Petya carry out the plan.A spider consists of k beads tied together by k - 1 threads. Each thread connects two different beads, at that any pair of beads that make up a spider is either directly connected by a thread, or is connected via some chain of threads and beads.Petya may glue spiders together directly gluing their beads. The length of each thread equals 1. The sizes of the beads can be neglected. That's why we can consider that gluing spiders happens by identifying some of the beads (see the picture). Besides, the construction resulting from the gluing process should also represent a spider, that is, it should have the given features. After Petya glues all spiders together, he measures the length of the resulting toy. The distance between a pair of beads is identified as the total length of the threads that connect these two beads. The length of the resulting construction is the largest distance between all pairs of beads. Petya wants to make the spider whose length is as much as possible. The picture two shows two spiders from the second sample. We can glue to the bead number 2 of the first spider the bead number 1 of the second spider. The threads in the spiders that form the sequence of threads of maximum lengths are highlighted on the picture.
Input: ['13 1 2 2 3'] Output:['2']
[ 2 ]
Petya and Gena play a very interesting game "Put a Knight!" on a chessboard n × n in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (r, c) can threat squares (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (r + 1, c - 2), (r - 2, c + 1), (r - 2, c - 1), (r + 2, c + 1) and (r + 2, c - 1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.
Input: ['221'] Output:['10']
[ 3 ]
Three sons inherited from their father a rectangular corn fiend divided into n × m squares. For each square we know how many tons of corn grows on it. The father, an old farmer did not love all three sons equally, which is why he bequeathed to divide his field into three parts containing A, B and C tons of corn.The field should be divided by two parallel lines. The lines should be parallel to one side of the field and to each other. The lines should go strictly between the squares of the field. Each resulting part of the field should consist of at least one square. Your task is to find the number of ways to divide the field as is described above, that is, to mark two lines, dividing the field in three parts so that on one of the resulting parts grew A tons of corn, B on another one and C on the remaining one.
Input: ['3 31 1 11 1 11 1 13 3 3'] Output:['2']
[ 0 ]
As we all know, Winnie-the-Pooh just adores honey. Ones he and the Piglet found out that the Rabbit has recently gotten hold of an impressive amount of this sweet and healthy snack. As you may guess, Winnie and the Piglet asked to come at the Rabbit's place. Thus, there are n jars of honey lined up in front of Winnie-the-Pooh, jar number i contains ai kilos of honey. Winnie-the-Pooh eats the honey like that: each time he chooses a jar containing most honey. If the jar has less that k kilos of honey or if Winnie-the-Pooh has already eaten from it three times, he gives the jar to Piglet. Otherwise he eats exactly k kilos of honey from the jar and puts it back. Winnie does so until he gives all jars to the Piglet. Count how much honey Piglet will overall get after Winnie satisfies his hunger.
Input: ['3 315 8 10'] Output:['9']
[ 3 ]
A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand. One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.
Input: ['front1'] Output:['L']
[ 0, 3 ]
A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one.Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.
Input: ['6 5898196'] Output:['4888188']
[ 0, 2 ]
Let a be an array consisting of n numbers. The array's elements are numbered from 1 to n, even is an array consisting of the numerals whose numbers are even in a (eveni = a2i, 1 ≀ 2i ≀ n), odd is an array consisting of the numberals whose numbers are odd in Π° (oddi = a2i - 1, 1 ≀ 2i - 1 ≀ n). Then let's define the transformation of array F(a) in the following manner: if n > 1, F(a) = F(odd) + F(even), where operation " + " stands for the arrays' concatenation (joining together) if n = 1, F(a) = a Let a be an array consisting of n numbers 1, 2, 3, ..., n. Then b is the result of applying the transformation to the array a (so b = F(a)). You are given m queries (l, r, u, v). Your task is to find for each query the sum of numbers bi, such that l ≀ i ≀ r and u ≀ bi ≀ v. You should print the query results modulo mod.
Input: ['4 5 100002 3 4 52 4 1 31 2 2 42 3 3 51 3 3 4'] Output:['05333']
[ 3 ]
In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string s1, consisting of exactly nine digits and representing a number that does not exceed a. After that second player looks at s1 and writes a string s2, consisting of exactly nine digits and representing a number that does not exceed b. Here a and b are some given constants, s1 and s2 are chosen by the players. The strings are allowed to contain leading zeroes.If a number obtained by the concatenation (joining together) of strings s1 and s2 is divisible by mod, then the second player wins. Otherwise the first player wins. You are given numbers a, b, mod. Your task is to determine who wins if both players play in the optimal manner. If the first player wins, you are also required to find the lexicographically minimum winning move.
Input: ['1 10 7'] Output:['2']
[ 0 ]
And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All n participants who have made it to the finals found themselves in a huge m-floored 108-star hotel. Of course the first thought to come in a place like this is "How about checking out the elevator?".The hotel's elevator moves between floors according to one never changing scheme. Initially (at the moment of time 0) the elevator is located on the 1-st floor, then it moves to the 2-nd floor, then β€” to the 3-rd floor and so on until it reaches the m-th floor. After that the elevator moves to floor m - 1, then to floor m - 2, and so on until it reaches the first floor. This process is repeated infinitely. We know that the elevator has infinite capacity; we also know that on every floor people get on the elevator immediately. Moving between the floors takes a unit of time.For each of the n participant you are given si, which represents the floor where the i-th participant starts, fi, which represents the floor the i-th participant wants to reach, and ti, which represents the time when the i-th participant starts on the floor si.For each participant print the minimum time of his/her arrival to the floor fi. If the elevator stops on the floor si at the time ti, then the i-th participant can enter the elevator immediately. If the participant starts on the floor si and that's the floor he wanted to reach initially (si = fi), then the time of arrival to the floor fi for this participant is considered equal to ti.
Input: ['7 42 4 31 2 02 2 01 2 14 3 51 2 24 2 0'] Output:['91071075']
[ 3 ]
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n × m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of wolves, so there will be at most one wolf adjacent to each little pig. But each wolf may be adjacent to any number of little pigs.They have been living peacefully for several years. But today the wolves got hungry. One by one, each wolf will choose one of the little pigs adjacent to it (if any), and eats the poor little pig. This process is not repeated. That is, each wolf will get to eat at most one little pig. Once a little pig gets eaten, it disappears and cannot be eaten by any other wolf.What is the maximum number of little pigs that may be eaten by the wolves?
Input: ['2 3PPWW.P'] Output:['2']
[ 2 ]
Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n × m square cells.In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows: Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment 1 has ends at top and left side of it.Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size 1 × 2. Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling all of the empty cells with pipe segments. Print this number modulo 1000003 (106 + 3).Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.
Input: ['2 213..'] Output:['2']
[ 3 ]
You have a garden consisting entirely of grass and weeds. Your garden is described by an n × m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either grass or weeds. For example, a 4 × 5 garden may look as follows (empty cells denote grass): You have a land-mower with you to mow all the weeds. Initially, you are standing with your lawnmower at the top-left corner of the garden. That is, at cell (1, 1). At any moment of time you are facing a certain direction β€” either left or right. And initially, you face right.In one move you can do either one of these:1) Move one cell in the direction that you are facing. if you are facing right: move from cell (r, c) to cell (r, c + 1) if you are facing left: move from cell (r, c) to cell (r, c - 1) 2) Move one cell down (that is, from cell (r, c) to cell (r + 1, c)), and change your direction to the opposite one. if you were facing right previously, you will face left if you were facing left previously, you will face right You are not allowed to leave the garden. Weeds will be mowed if you and your lawnmower are standing at the cell containing the weeds (your direction doesn't matter). This action isn't counted as a move.What is the minimum number of moves required to mow all the weeds?
Input: ['4 5GWGGWGGWGGGWGGGWGGGG'] Output:['11']
[ 2 ]
When little Petya grew up and entered the university, he started to take part in АБМ contests. Later he realized that he doesn't like how the АБМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members efficiently), so he decided to organize his own contests PFAST Inc. β€” Petr and Friends Are Solving Tasks Corporation. PFAST Inc. rules allow a team to have unlimited number of members.To make this format of contests popular he organised his own tournament. To create the team he will prepare for the contest organised by the PFAST Inc. rules, he chose several volunteers (up to 16 people) and decided to compile a team from them. Petya understands perfectly that if a team has two people that don't get on well, then the team will perform poorly. Put together a team with as many players as possible given that all players should get on well with each other.
Input: ['3 1PetyaVasyaMashaPetya Vasya'] Output:['2MashaPetya']
[ 0 ]
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million.Petya wanted to modernize the words we use for numbers and invented a word petricium that represents number k. Moreover, petricium la petricium stands for number k2, petricium la petricium la petricium stands for k3 and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.Petya's invention brought on a challenge that needed to be solved quickly: does some number l belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.
Input: ['525'] Output:['YES1']
[ 3 ]
One day Vasya was lying in bed watching his electronic clock to fall asleep quicker.Vasya lives in a strange country, where days have h hours, and every hour has m minutes. Clock shows time in decimal number system, in format H:M, where the string H always has a fixed length equal to the number of digits in the decimal representation of number h - 1. To achieve this, leading zeros are added if necessary. The string M has a similar format, and its length is always equal to the number of digits in the decimal representation of number m - 1. For example, if h = 17, m = 1000, then time equal to 13 hours and 75 minutes will be displayed as "13:075".Vasya had been watching the clock from h1 hours m1 minutes to h2 hours m2 minutes inclusive, and then he fell asleep. Now he asks you to count how many times he saw the moment at which at least k digits changed on the clock simultaneously.For example, when switching 04:19  →  04:20 two digits change. When switching 23:59  →  00:00, four digits change.Consider that Vasya has been watching the clock for strictly less than one day. Note that the last time Vasya saw on the clock before falling asleep was "h2:m2". That is, Vasya didn't see the moment at which time "h2:m2" switched to the next value.
Input: ['5 5 24 42 1'] Output:['3']
[ 3 ]
One day as Petya and his friend Vasya were having one of their numerous trips, they decided to visit a museum castle. The museum has a specific shape: it consists of n rooms connected with m corridors so that one can access any room from any other one.After the two friends had a little walk around the museum, they decided to split and watch the pieces of art each of them found interesting. They agreed to meet in one of the rooms at six p.m. However, they forgot one quite essential thing: they didn't specify the place to meet and when the time came, they started to rush about the museum looking for each other (they couldn't call each other as roaming made a call's cost skyrocket).Yet, even despite the whole rush, they couldn't get enough of the pieces of art, that's why each of them has the following strategy: each minute he make a decision where to go β€” with probability pi he doesn't move to any other place during this minute (i.e. he stays in the room). With probability 1 - pi he equiprobably choose one of the adjacent rooms and went there along the corridor. Here i is the ordinal number of the current room. Building was expensive in ancient times, that's why each corridor connected two different rooms, and any two rooms had no more than one corridor between them. The boys act simultaneously. As the corridors are dark, it is impossible to meet there; however, one can walk along the corridors in both directions (besides, the two boys can be going through the same corridor simultaneously without meeting). The boys act like that until they meet each other. More formally, the two friends meet when at some moment of time both of them decided to appear in the same room.For each room find the probability that the boys will meet there considering that at 6 p.m. they are positioned in rooms a and b correspondingly.
Input: ['2 1 1 21 20.50.5'] Output:['0.5000000000 0.5000000000 ']
[ 3 ]
On the math lesson a teacher asked each pupil to come up with his own lucky numbers. As a fan of number theory Peter chose prime numbers. Bob was more original. He said that number t is his lucky number, if it can be represented as: t = a2 + b2,  where a, b are arbitrary positive integers.Now, the boys decided to find out how many days of the interval [l, r] (l ≀ r) are suitable for pair programming. They decided that the day i (l ≀ i ≀ r) is suitable for pair programming if and only if the number i is lucky for Peter and lucky for Bob at the same time. Help the boys to find the number of such days.
Input: ['3 5'] Output:['1']
[ 0, 3 ]
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him!
Input: ['roundroou'] Output:['1']
[ 0 ]
Little Petya loves playing with squares. Mum bought him a square 2n × 2n in size. Petya marked a cell inside the square and now he is solving the following task.The task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any common points with the marked cell and the resulting two parts should be equal up to rotation.Petya wants to determine whether it is possible to cut the square in the required manner given the sizes of the square side and the coordinates of the marked cell. Help him.
Input: ['4 1 1'] Output:['YES']
[ 3 ]
Little Petya loves looking for numbers' divisors. One day Petya came across the following problem:You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him.
Input: ['64 03 15 26 218 410000 3'] Output:['3112222']
[ 4 ]
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: a12 + a22 + ... + an2 β‰₯ x a1 + a2 + ... + an ≀ y
Input: ['5 15 15'] Output:['44112']
[ 2 ]
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya came across an interval of numbers [a, a + l - 1]. Let F(x) be the number of lucky digits of number x. Find the minimum b (a < b) such, that F(a) = F(b), F(a + 1) = F(b + 1), ..., F(a + l - 1) = F(b + l - 1).
Input: ['7 4'] Output:['17']
[ 0, 3 ]
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the interval [pl, pr] and Vasya chooses an integer v from the interval [vl, vr] (also randomly). Both players choose their integers equiprobably. Find the probability that the interval [min(v, p), max(v, p)] contains exactly k lucky numbers.
Input: ['1 10 1 10 2'] Output:['0.320000000000']
[ 0 ]
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.
Input: ['11'] Output:['47']
[ 0 ]
Tattah's youngest brother, Tuftuf, is new to programming.Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava.Today, Tuftuf was introduced to Gava's unsigned integer datatypes. Gava has n unsigned integer datatypes of sizes (in bits) a1, a2, ... an. The i-th datatype have size ai bits, so it can represent every integer between 0 and 2ai - 1 inclusive. Tuftuf is thinking of learning a better programming language. If there exists an integer x, such that x fits in some type i (in ai bits) and xΒ·x does not fit in some other type j (in aj bits) where ai < aj, then Tuftuf will stop using Gava.Your task is to determine Tuftuf's destiny.
Input: ['364 16 32'] Output:['NO']
[ 3 ]
As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to different departments. There are m departments in GUC, numbered from 1 to m. Herr Wafa's department has number h. For each department i, Herr Wafa knows number si β€” how many students who play basketball belong to this department.Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department. Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.
Input: ['3 2 12 1'] Output:['1']
[ 3 ]
The Galaxy contains n planets, there are many different living creatures inhabiting each planet. And each creature can get into troubles! Space rescuers know it perfectly well and they are always ready to help anyone who really needs help. All you need to do is call for them. Now the space rescuers plan to build the largest in the history of the Galaxy rescue station; however, the rescue station's location is yet to be determined. As some cases are real emergencies, the rescuers want to find such a point in the Galaxy from which it would be possible to get to the remotest planet in the minimum possible time. In other words, the rescuers need such point in the space that the distance between it and the planet remotest from it was minimal (if we compare this point with all other possible points in the space). Unfortunately, the rescuers can't sole this problem.As the planets are quite remote from each other, they can be considered as points in Euclidean three-dimensional space. The distance between points (xi, yi, zi) and (xj, yj, zj) can be calculated by the formula . The rescue station can be positioned in any point in the space. It can also coincide with some planet. Galaxy is in danger! Save the space rescuers and find the required point for them.
Input: ['55 0 0-5 0 00 3 44 -3 02 2 -2'] Output:['0.000 0.000 0.000']
[ 4 ]
Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map.The treasure map can be represented as a rectangle n × m in size. Each cell stands for an islands' square (the square's side length equals to a mile). Some cells stand for the sea and they are impenetrable. All other cells are penetrable (i.e. available) and some of them contain local sights. For example, the large tree on the hills or the cave in the rocks.Besides, the map also has a set of k instructions. Each instruction is in the following form:"Walk n miles in the y direction"The possible directions are: north, south, east, and west. If you follow these instructions carefully (you should fulfill all of them, one by one) then you should reach exactly the place where treasures are buried. Unfortunately the captain doesn't know the place where to start fulfilling the instructions β€” as that very piece of the map was lost. But the captain very well remembers that the place contained some local sight. Besides, the captain knows that the whole way goes through the island's penetrable squares.The captain wants to know which sights are worth checking. He asks you to help him with that.
Input: ['6 10###########K#..######.#..##.###..L.#...####D###A.###########4N 2S 1E 1W 2'] Output:['AD']
[ 0 ]
Vasya is choosing a laptop. The shop has n laptops to all tastes.Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.If all three properties of a laptop are strictly less than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.There are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.
Input: ['52100 512 150 2002000 2048 240 3502300 1024 200 3202500 2048 80 3002000 512 180 150'] Output:['4']
[ 0 ]
You are given a straight half-line divided into segments of unit length, which we will call positions. The positions are numbered by positive integers that start with 1 from the end of half-line, i. e. 1, 2, 3 and so on. The distance between the positions is the absolute difference between the respective numbers. Laharl, Etna and Flonne occupy some positions on the half-line and they want to get to the position with the largest possible number. They are originally placed in different positions. Each of the characters can perform each of the following actions no more than once: Move a certain distance. Grab another character and lift him above the head. Throw the lifted character a certain distance. Each character has a movement range parameter. They can only move to free positions, assuming that distance between those positions doesn't exceed the movement range. One character can lift another character if the distance between the two characters equals 1, and no one already holds that another character. We can assume that the lifted character moves to the same position as the person who has lifted him, and the position in which he stood before becomes free. A lifted character cannot perform any actions and the character that holds him cannot walk. Also, each character has a throwing range parameter. It is the distance at which this character can throw the one lifted above his head. He can only throw a character to a free position, and only when there is a lifted character. We accept the situation when one person grabs another one who in his turn has the third character in his hands. This forms a "column" of three characters. For example, Laharl can hold Etna while Etna holds Flonne. In this case, Etna and the Flonne cannot perform any actions, and Laharl can only throw Etna (together with Flonne) at some distance. Laharl, Etna and Flonne perform actions in any order. They perform actions in turns, that is no two of them can do actions at the same time.Determine the maximum number of position at least one of the characters can reach. That is, such maximal number x so that one of the characters can reach position x.
Input: ['9 3 34 3 12 3 3'] Output:['15']
[ 0 ]
The maps in the game are divided into square cells called Geo Panels. Some of these panels are painted. We shall assume that the Geo Panels without color are painted the transparent color. Besides, the map has so-called Geo Symbols. They look like pyramids of different colors (including Geo Symbols of the transparent color). Each Geo Symbol is located on one Geo Panel, and each Geo Panel may contain no more than one Geo Symbol. Geo Symbols can be eliminated. To understand better what happens when a Geo Symbol is eliminated, let us introduce some queue to which we will put the recently eliminated Geo Symbols. Let's put at the head of the queue a Geo Symbol that was eliminated just now. Next, we will repeat the following operation: Extract the Geo Symbol from the queue. Look at the color of the panel containing the given Geo Symbol. If it differs from transparent and differs from the color of the Geo Symbol, then all Geo Panels of this color are repainted in the color of the given Geo Symbol (transparent Geo Symbols repaint the Geo Panels transparent). Repainting is executed in an infinite spiral strictly in the following order starting from the panel, which contained the Geo Symbol: In other words, we select all the panels that need to be repainted and find their numbers in the infinite spiral whose center is placed in the position of the given Geo Symbol. After that, we repaint them in the order of the number's increasing. If a panel contains another Geo Symbol and this panel is being repainted, then the Geo Symbol is removed from the field and placed at the tail of the queue. After repainting the Geo Symbol is completely eliminated and the next Geo Symbol is taken from the head of the queue (if there is any) and the process repeats. The process ends if the queue is empty. See the sample analysis for better understanding. You know the colors of all the Geo Panels and the location of all the Geo Symbols. Determine the number of repaintings, which will occur if you destroy one of the Geo Symbols.
Input: ['5 59 0 1 1 00 0 3 2 01 1 1 3 01 1 1 3 00 1 2 0 3-1 1 -1 3 -1-1 -1 -1 0 -1-1 -1 -1 -1 -1-1 2 3 -1 -1-1 -1 -1 -1 24 2'] Output:['35']
[ 0 ]
Each item in the game has a level. The higher the level is, the higher basic parameters the item has. We shall consider only the following basic parameters: attack (atk), defense (def) and resistance to different types of impact (res).Each item belongs to one class. In this problem we will only consider three of such classes: weapon, armor, orb.Besides, there's a whole new world hidden inside each item. We can increase an item's level travelling to its world. We can also capture the so-called residents in the Item WorldResidents are the creatures that live inside items. Each resident gives some bonus to the item in which it is currently located. We will only consider residents of types: gladiator (who improves the item's atk), sentry (who improves def) and physician (who improves res).Each item has the size parameter. The parameter limits the maximum number of residents that can live inside an item. We can move residents between items. Within one moment of time we can take some resident from an item and move it to some other item if it has a free place for a new resident. We cannot remove a resident from the items and leave outside β€” any of them should be inside of some item at any moment of time.Laharl has a certain number of items. He wants to move the residents between items so as to equip himself with weapon, armor and a defensive orb. The weapon's atk should be largest possible in the end. Among all equipping patterns containing weapon's maximum atk parameter we should choose the ones where the armor’s def parameter is the largest possible. Among all such equipment patterns we should choose the one where the defensive orb would have the largest possible res parameter. Values of the parameters def and res of weapon, atk and res of armor and atk and def of orb are indifferent for Laharl.Find the optimal equipment pattern Laharl can get.
Input: ['4sword weapon 10 2 3 2pagstarmor armor 0 15 3 1iceorb orb 3 2 13 2longbow weapon 9 1 2 15mike gladiator 5 longbowbobby sentry 6 pagstarmorpetr gladiator 7 iceorbteddy physician 6 swordblackjack sentry 8 sword'] Output:['sword 2 petr mike pagstarmor 1 blackjack iceorb 2 teddy bobby ']
[ 0 ]
Dark Assembly is a governing body in the Netherworld. Here sit the senators who take the most important decisions for the player. For example, to expand the range of the shop or to improve certain characteristics of the character the Dark Assembly's approval is needed.The Dark Assembly consists of n senators. Each of them is characterized by his level and loyalty to the player. The level is a positive integer which reflects a senator's strength. Loyalty is the probability of a positive decision in the voting, which is measured as a percentage with precision of up to 10%. Senators make decisions by voting. Each of them makes a positive or negative decision in accordance with their loyalty. If strictly more than half of the senators take a positive decision, the player's proposal is approved. If the player's proposal is not approved after the voting, then the player may appeal against the decision of the Dark Assembly. To do that, player needs to kill all the senators that voted against (there's nothing wrong in killing senators, they will resurrect later and will treat the player even worse). The probability that a player will be able to kill a certain group of senators is equal to A / (A + B), where A is the sum of levels of all player's characters and B is the sum of levels of all senators in this group. If the player kills all undesired senators, then his proposal is approved.Senators are very fond of sweets. They can be bribed by giving them candies. For each received candy a senator increases his loyalty to the player by 10%. It's worth to mention that loyalty cannot exceed 100%. The player can take no more than k sweets to the courtroom. Candies should be given to the senators before the start of voting.Determine the probability that the Dark Assembly approves the player's proposal if the candies are distributed among the senators in the optimal way.
Input: ['5 6 10011 8014 9023 7080 30153 70'] Output:['1.0000000000']
[ 0 ]
As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space. Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row. If we number all cows in the cowavan with positive integers from 1 to n, then we can formalize the popular model of abduction, known as the (a, b)-Cowavan Raid: first they steal a cow number a, then number a + b, then β€” number a + 2Β·b, and so on, until the number of an abducted cow exceeds n. During one raid the cows are not renumbered. The aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made p scenarios of the (a, b)-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen.
Input: ['31 2 321 11 2'] Output:['64']
[ 0 ]
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all. Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner. Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one. More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots). Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi?
Input: ['3 1 3123'] Output:['..X']
[ 2 ]
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?
Input: ['21 1'] Output:['2']
[ 2, 3 ]
A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.
Input: ['3 31 2 31 22 33 1'] Output:['6']
[ 0 ]
Gerald is positioned in an old castle which consists of n halls connected with n - 1 corridors. It is exactly one way to go from any hall to any other one. Thus, the graph is a tree. Initially, at the moment of time 0, Gerald is positioned in hall 1. Besides, some other hall of the castle contains the treasure Gerald is looking for. The treasure's position is not known; it can equiprobably be in any of other n - 1 halls. Gerald can only find out where the treasure is when he enters the hall with the treasure. That very moment Gerald sees the treasure and the moment is regarded is the moment of achieving his goal. The corridors have different lengths. At that, the corridors are considered long and the halls are considered small and well lit. Thus, it is possible not to take the time Gerald spends in the halls into consideration. The castle is very old, that's why a corridor collapses at the moment when somebody visits it two times, no matter in which direction. Gerald can move around the castle using the corridors; he will go until he finds the treasure. Naturally, Gerald wants to find it as quickly as possible. In other words, he wants to act in a manner that would make the average time of finding the treasure as small as possible. Each corridor can be used no more than two times. That's why Gerald chooses the strategy in such a way, so he can visit every hall for sure.More formally, if the treasure is located in the second hall, then Gerald will find it the moment he enters the second hall for the first time β€” let it be moment t2. If the treasure is in the third hall, then Gerald will find it the moment he enters the third hall for the first time. Let it be the moment of time t3. And so on. Thus, the average time of finding the treasure will be equal to .
Input: ['21 2 1'] Output:['1.0']
[ 2 ]
At a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector А: Turn the vector by 90 degrees clockwise. Add to the vector a certain vector C.Operations could be performed in any order any number of times.Can Gerald cope with the task?
Input: ['0 01 10 1'] Output:['YES']
[ 3 ]
Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n.There are m buses running between the house and the school: the i-th bus goes from stop si to ti (si < ti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to ti - 1 inclusive, but he can get off the i-th bus only on the bus stop ti.Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109 + 7).
Input: ['2 20 11 2'] Output:['1']
[ 4 ]
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than k characters, it will be very suspicious. Find the least number of distinct characters that can remain in the string after no more than k characters are deleted. You also have to find any possible way to delete the characters.
Input: ['aaaaa4'] Output:['1aaaaa']
[ 2 ]
Aryo has got a lot of intervals for his 2418th birthday. He is really excited and decided to color all these intervals with some colors. He has a simple rule for himself. He calls a coloring nice if there exists no three intervals a, b and c such that the following conditions are satisfied simultaneously: a, b and c are colored with the same color, , , . Moreover he found out that for every intervals i and j, there is at least one point in i which isn't in j.Given some set of intervals. You have to find the minimum number k, such that Aryo can find a nice coloring with k colors.
Input: ['2[1,2)(3,4]'] Output:['1']
[ 2, 3 ]
Ehsan loves geometry! Especially he likes to rotate points!Given a point in the plane, Ehsan likes to rotate it by k degrees (counter-clockwise), around the origin. What is the result of this rotation?
Input: ['901 1'] Output:['-1.00000000 1.00000000']
[ 3 ]