problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
⌀ | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
D. How many trees?time limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputIn one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terrible Game Cubes fall down on the city, bringing death to those modules, who cannot win the game...For sure, as guard Bob appeared in Mainframe many modules stopped fearing Game Cubes. Because Bob (as he is alive yet) has never been defeated by User, and he always meddles with Game Cubes, because he is programmed to this.However, unpleasant situations can happen, when a Game Cube falls down on Lost Angles. Because there lives a nasty virus — Hexadecimal, who is... mmm... very strange. And she likes to play very much. So, willy-nilly, Bob has to play with her first, and then with User.This time Hexadecimal invented the following entertainment: Bob has to leap over binary search trees with n nodes. We should remind you that a binary search tree is a binary tree, each node has a distinct key, for each node the following is true: the left sub-tree of a node contains only nodes with keys less than the node's key, the right sub-tree of a node contains only nodes with keys greater than the node's key. All the keys are different positive integer numbers from 1 to n. Each node of such a tree can have up to two children, or have no children at all (in the case when a node is a leaf).In Hexadecimal's game all the trees are different, but the height of each is not lower than h. In this problem «height» stands for the maximum amount of nodes on the way from the root to the remotest leaf, the root node and the leaf itself included. When Bob leaps over a tree, it disappears. Bob gets the access to a Cube, when there are no trees left. He knows how many trees he will have to leap over in the worst case. And you?InputThe input data contains two space-separated positive integer numbers n and h (n ≤ 35, h ≤ n).OutputOutput one number — the answer to the problem. It is guaranteed that it does not exceed 9·1018.ExamplesInput3 2Output5Input3 3Output4 | Input3 2 | Output5 | 1 second | 64 megabytes | ['combinatorics', 'divide and conquer', 'dp', '*1900'] |
C. Hexadecimal's Numberstime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputOne beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.But his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. This means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. Now Megabyte wants to know, how many numbers were loaded successfully.InputInput data contains the only number n (1 ≤ n ≤ 109).OutputOutput the only number — answer to the problem.ExamplesInput10Output2NoteFor n = 10 the answer includes numbers 1 and 10. | Input10 | Output2 | 1 second | 64 megabytes | ['brute force', 'implementation', 'math', '*1200'] |
B. Running Studenttime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputAnd again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following: during one run the minibus makes n stops, the i-th stop is in point (xi, 0) coordinates of all the stops are different the minibus drives at a constant speed, equal to vb it can be assumed the passengers get on and off the minibus at a bus stop momentarily Student can get off the minibus only at a bus stop Student will have to get off the minibus at a terminal stop, if he does not get off earlier the University, where the exam will be held, is in point (xu, yu) Student can run from a bus stop to the University at a constant speed vs as long as needed a distance between two points can be calculated according to the following formula: Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.InputThe first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value. OutputIn the only line output the answer to the problem — index of the optimum bus stop.ExamplesInput4 5 20 2 4 64 1Output3Input2 1 10 100000100000 100000Output2NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus. | Input4 5 20 2 4 64 1 | Output3 | 1 second | 64 megabytes | ['brute force', 'geometry', 'implementation', '*1200'] |
A. Die Rolltime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputYakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.InputThe only line of the input file contains two natural numbers Y and W — the results of Yakko's and Wakko's die rolls.OutputOutput the required probability in the form of irreducible fraction in format «A/B», where A — the numerator, and B — the denominator. If the required probability equals to zero, output «0/1». If the required probability equals to 1, output «1/1». ExamplesInput4 2Output1/2NoteDot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points. | Input4 2 | Output1/2 | 1 second | 64 megabytes | ['math', 'probabilities', '*800'] |
E. Beadstime limit per test5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputOne Martian boy called Zorg wants to present a string of beads to his friend from the Earth — Masha. He knows that Masha likes two colours: blue and red, — and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if one unfastens it, one might notice that all the strings of beads in the shop are of the same length. Because of the peculiarities of the Martian eyesight, if Zorg sees one blue-and-red string of beads first, and then the other with red beads instead of blue ones, and blue — instead of red, he regards these two strings of beads as identical. In other words, Zorg regards as identical not only those strings of beads that can be derived from each other by the string turnover, but as well those that can be derived from each other by a mutual replacement of colours and/or by the string turnover.It is known that all Martians are very orderly, and if a Martian sees some amount of objects, he tries to put them in good order. Zorg thinks that a red bead is smaller than a blue one. Let's put 0 for a red bead, and 1 — for a blue one. From two strings the Martian puts earlier the string with a red bead in the i-th position, providing that the second string has a blue bead in the i-th position, and the first two beads i - 1 are identical.At first Zorg unfastens all the strings of beads, and puts them into small heaps so, that in each heap strings are identical, in his opinion. Then he sorts out the heaps and chooses the minimum string in each heap, in his opinion. He gives the unnecassary strings back to the shop assistant and says he doesn't need them any more. Then Zorg sorts out the remaining strings of beads and buys the string with index k. All these manupulations will take Zorg a lot of time, that's why he asks you to help and find the string of beads for Masha.InputThe input file contains two integers n and k (2 ≤ n ≤ 50;1 ≤ k ≤ 1016) —the length of a string of beads, and the index of the string, chosen by Zorg. OutputOutput the k-th string of beads, putting 0 for a red bead, and 1 — for a blue one. If it s impossible to find the required string, output the only number -1.ExamplesInput4 4Output0101NoteLet's consider the example of strings of length 4 — 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110. Zorg will divide them into heaps: {0001, 0111, 1000, 1110}, {0010, 0100, 1011, 1101}, {0011, 1100}, {0101, 1010}, {0110, 1001}. Then he will choose the minimum strings of beads in each heap: 0001, 0010, 0011, 0101, 0110. The forth string — 0101. | Input4 4 | Output0101 | 5 seconds | 64 megabytes | ['dp', 'graphs', '*2600'] |
D. Two Friendstime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputTwo neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it.Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends.The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than t1, and the distance covered by Bob should not differ from the shortest one by more than t2.Find the maximum distance that Alan and Bob will cover together, discussing the film.InputThe first line contains two integers: t1, t2 (0 ≤ t1, t2 ≤ 100). The second line contains the cinema's coordinates, the third one — the house's, and the last line — the shop's. All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building.OutputIn the only line output one number — the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places.ExamplesInput0 20 04 0-3 0Output1.0000000000Input0 00 02 01 0Output2.0000000000 | Input0 20 04 0-3 0 | Output1.0000000000 | 1 second | 64 megabytes | ['binary search', 'geometry', '*2600'] |
C. Looking for Ordertime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGirl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess — all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl cannot carry more than two objects at a time, and cannot move the handbag. Also, if he has taken an object, she cannot put it anywhere except her handbag — her inherent sense of order does not let her do so.You are given the coordinates of the handbag and the coordinates of the objects in some Сartesian coordinate system. It is known that the girl covers the distance between any two objects in the time equal to the squared length of the segment between the points of the objects. It is also known that initially the coordinates of the girl and the handbag are the same. You are asked to find such an order of actions, that the girl can put all the objects back into her handbag in a minimum time period.InputThe first line of the input file contains the handbag's coordinates xs, ys. The second line contains number n (1 ≤ n ≤ 24) — the amount of objects the girl has. The following n lines contain the objects' coordinates. All the coordinates do not exceed 100 in absolute value. All the given positions are different. All the numbers are integer.OutputIn the first line output the only number — the minimum time the girl needs to put the objects into her handbag. In the second line output the possible optimum way for Lena. Each object in the input is described by its index number (from 1 to n), the handbag's point is described by number 0. The path should start and end in the handbag's point. If there are several optimal paths, print any of them. ExamplesInput0 021 1-1 1Output80 1 2 0 Input1 134 33 40 0Output320 1 2 0 3 0 | Input0 021 1-1 1 | Output80 1 2 0 | 4 seconds | 512 megabytes | ['bitmasks', 'dp', '*2000'] |
B. Obsession with Robotstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest.The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest.In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in.InputThe first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100.OutputIn the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist).ExamplesInputLLUUUROutputOKInputRRUULLDDOutputBUG | InputLLUUUR | OutputOK | 2 seconds | 64 megabytes | ['constructive algorithms', 'graphs', 'implementation', '*1400'] |
A. Train and Petertime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputPeter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.InputThe input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. OutputOutput one of the four words without inverted commas: «forward» — if Peter could see such sequences only on the way from A to B; «backward» — if Peter could see such sequences on the way from B to A; «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; «fantasy» — if Peter could not see such sequences. ExamplesInputatobabOutputforwardInputaaacaaaacaaaOutputbothNoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B. | Inputatobab | Outputforward | 1 second | 64 megabytes | ['strings', '*1200'] |
E. Defining Macrostime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMost C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:#define macro_name macro_valueAfter the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.One of the main problems arising while using macros — the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.Let's consider the following example. Say, we declared such a #define construction:#define sum x + yand further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise — suspicious.Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".InputThe first line contains the only number n (0 ≤ n ≤ 100) — the amount of #define constructions in the given program.Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:#define name expressionwhere name — the macro name, expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109. All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.The length of any line from the input file does not exceed 100 characters.OutputOutput "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".ExamplesInput1#define sum x + y1 * sumOutputSuspiciousInput1#define sum (x + y)sum - sumOutputOKInput4#define sum x + y#define mul a * b#define div a / b#define expr sum + mul * div * mulexprOutputOKInput3#define SumSafe (a+b)#define DivUnsafe a/b#define DenominatorUnsafe a*b((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)OutputSuspicious | Input1#define sum x + y1 * sum | OutputSuspicious | 3 seconds | 256 megabytes | ['dp', 'expression parsing', 'implementation', '*2600'] |
D. Palindrome Degreetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputString s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.InputThe first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.OutputOutput the only number — the sum of the polindrome degrees of all the string's prefixes.ExamplesInputa2AOutput1InputabacabaOutput6 | Inputa2A | Output1 | 1 second | 256 megabytes | ['hashing', 'strings', '*2200'] |
C. Linetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist.InputThe first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0.OutputIf the required point exists, output its coordinates, otherwise output -1.ExamplesInput2 5 3Output6 -3 | Input2 5 3 | Output6 -3 | 1 second | 256 megabytes | ['math', 'number theory', '*1800'] |
B. Memory Managertime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputThere is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations: alloc n — to allocate n bytes of the memory and return the allocated block's identifier x; erase x — to erase the block with the identifier x; defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.InputThe first line of the input data contains two positive integers t and m (1 ≤ t ≤ 100;1 ≤ m ≤ 100), where t — the amount of operations given to the memory manager for processing, and m — the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 ≤ n ≤ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment. OutputOutput the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.ExamplesInput6 10alloc 5alloc 3erase 1alloc 6defragmentalloc 6Output12NULL3 | Input6 10alloc 5alloc 3erase 1alloc 6defragmentalloc 6 | Output12NULL3 | 1 second | 64 megabytes | ['implementation', '*1600'] |
A. Kalevitch and Chesstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputA famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.As before, the chessboard is a square-checkered board with the squares arranged in a 8 × 8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke.Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements.It goes without saying that in such business one should economize on everything — for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.InputThe input file contains 8 lines, each of the lines contains 8 characters. The given matrix describes the client's requirements, W character stands for a white square, and B character — for a square painted black.It is guaranteed that client's requirments can be fulfilled with a sequence of allowed strokes (vertical/column or horizontal/row).OutputOutput the only number — the minimum amount of rows and columns that Kalevitch has to paint on the white chessboard to meet the client's requirements.ExamplesInputWWWBWWBWBBBBBBBBWWWBWWBWWWWBWWBWWWWBWWBWWWWBWWBWWWWBWWBWWWWBWWBWOutput3InputWWWWWWWWBBBBBBBBWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWOutput1 | InputWWWBWWBWBBBBBBBBWWWBWWBWWWWBWWBWWWWBWWBWWWWBWWBWWWWBWWBWWWWBWWBW | Output3 | 2 seconds | 64 megabytes | ['brute force', 'constructive algorithms', '*1100'] |
E. Expositiontime limit per test1.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThere are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.InputThe first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.OutputIn the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters.In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.ExamplesInput3 314 12 10Output2 21 22 3Input2 010 10Output2 11 2Input4 58 19 10 13Output2 13 4 | Input3 314 12 10 | Output2 21 22 3 | 1.5 seconds | 64 megabytes | ['binary search', 'data structures', 'dsu', 'trees', 'two pointers', '*1900'] |
D. Lizards and Basements 2time limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThis is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each.As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball.The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies?Polycarp can throw his fire ball into an archer if the latter is already killed.InputThe first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has.OutputIn the first line print t — the required minimum amount of fire balls.In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.ExamplesInput3 2 12 2 2Output32 2 2 Input4 3 11 4 1 1Output42 2 3 3 | Input3 2 12 2 2 | Output32 2 2 | 2 seconds | 64 megabytes | ['brute force', 'dp', '*2600'] |
C. Alice, Bob and Chocolatetime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputAlice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?InputThe first line contains one integer n (1 ≤ n ≤ 105) — the amount of bars on the table. The second line contains a sequence t1, t2, ..., tn (1 ≤ ti ≤ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).OutputPrint two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.ExamplesInput52 9 8 2 7Output2 3 | Input52 9 8 2 7 | Output2 3 | 2 seconds | 64 megabytes | ['greedy', 'two pointers', '*1200'] |
B. President's Officetime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputPresident of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell. InputThe first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.OutputPrint the only number — the amount of President's deputies.ExamplesInput3 4 RG.B..RR.TTT.Output2Input3 3 Z....H...ZOutput0 | Input3 4 RG.B..RR.TTT. | Output2 | 2 seconds | 64 megabytes | ['implementation', '*1100'] |
A. Triangletime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputJohnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.InputThe first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.OutputOutput TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.ExamplesInput4 2 1 3OutputTRIANGLEInput7 2 2 4OutputSEGMENTInput3 5 9 1OutputIMPOSSIBLE | Input4 2 1 3 | OutputTRIANGLE | 2 seconds | 64 megabytes | ['brute force', 'geometry', '*900'] |
E. Bindian Signalizingtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEveryone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.InputThe first line of the input data contains an integer number n (3 ≤ n ≤ 106), n — the amount of hills around the capital. The second line contains n numbers — heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.OutputPrint the required amount of pairs.ExamplesInput51 2 4 5 3Output7 | Input51 2 4 5 3 | Output7 | 4 seconds | 256 megabytes | ['data structures', '*2400'] |
D. Follow Traffic Rulestime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputEverybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed.It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≤ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed.The car can enter Bercouver at any speed.InputThe first line of the input file contains two integer numbers a and v (1 ≤ a, v ≤ 10000). The second line contains three integer numbers l, d and w (2 ≤ l ≤ 10000; 1 ≤ d < l; 1 ≤ w ≤ 10000).OutputPrint the answer with at least five digits after the decimal point.ExamplesInput1 12 1 3Output2.500000000000Input5 70200 170 40Output8.965874696353 | Input1 12 1 3 | Output2.500000000000 | 1 second | 64 megabytes | ['implementation', 'math', '*2100'] |
C. Longest Regular Bracket Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is yet another problem dealing with regular bracket sequences.We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.InputThe first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.OutputPrint the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".ExamplesInput)((())))(()())Output6 2Input))(Output0 1 | Input)((())))(()()) | Output6 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'dp', 'greedy', 'sortings', 'strings', '*1900'] |
B. Center Alignmenttime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputAlmost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!InputThe input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. OutputFormat the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.ExamplesInputThis isCodeforcesBetaRound5Output************* This is ** **Codeforces** Beta ** Round ** 5 *************Inputwelcome to theCodeforcesBetaRound 5andgood luckOutput*****************welcome to the** Codeforces ** Beta ** Round 5 ** ** and ** good luck ***************** | InputThis isCodeforcesBetaRound5 | Output************* This is ** **Codeforces** Beta ** Round ** 5 ************* | 1 second | 64 megabytes | ['implementation', 'strings', '*1200'] |
A. Chat Server's Outgoing Traffictime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputPolycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: Include a person to the chat ('Add' command). Remove a person from the chat ('Remove' command). Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.InputInput file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following: +<name> for 'Add' command. -<name> for 'Remove' command. <sender_name>:<message_text> for 'Send' command. <name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.All names are case-sensitive.OutputPrint a single number — answer to the problem.ExamplesInput+MikeMike:hello+Kate+Dmitry-DmitryKate:hi-KateOutput9Input+Mike-Mike+MikeMike:Hi I am here-Mike+Kate-KateOutput14 | Input+MikeMike:hello+Kate+Dmitry-DmitryKate:hi-Kate | Output9 | 1 second | 64 megabytes | ['implementation', '*1000'] |
D. Mysterious Presenttime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputPeter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes A = {a1, a2, ..., an}, where the width and the height of the i-th envelope is strictly higher than the width and the height of the (i - 1)-th envelope respectively. Chain size is the number of envelopes in the chain. Peter wants to make the chain of the maximum size from the envelopes he has, the chain should be such, that he'll be able to put a card into it. The card fits into the chain if its width and height is lower than the width and the height of the smallest envelope in the chain respectively. It's forbidden to turn the card and the envelopes. Peter has very many envelopes and very little time, this hard task is entrusted to you.InputThe first line contains integers n, w, h (1 ≤ n ≤ 5000, 1 ≤ w, h ≤ 106) — amount of envelopes Peter has, the card width and height respectively. Then there follow n lines, each of them contains two integer numbers wi and hi — width and height of the i-th envelope (1 ≤ wi, hi ≤ 106).OutputIn the first line print the maximum chain size. In the second line print the numbers of the envelopes (separated by space), forming the required chain, starting with the number of the smallest envelope. Remember, please, that the card should fit into the smallest envelope. If the chain of maximum size is not unique, print any of the answers.If the card does not fit into any of the envelopes, print number 0 in the single line.ExamplesInput2 1 12 22 2Output11 Input3 3 35 412 119 8Output31 3 2 | Input2 1 12 22 2 | Output11 | 1 second | 64 megabytes | ['dp', 'sortings', '*1700'] |
C. Registration systemtime limit per test5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputA new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.InputThe first line contains number n (1 ≤ n ≤ 105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.OutputPrint n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.ExamplesInput4abacabaacabaabacabaacabOutputOKOKabacaba1OKInput6firstfirstsecondsecondthirdthirdOutputOKfirst1OKsecond1OKthird1 | Input4abacabaacabaabacabaacab | OutputOKOKabacaba1OK | 5 seconds | 64 megabytes | ['data structures', 'hashing', 'implementation', '*1300'] |
B. Before an Examtime limit per test0.5 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputTomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, they warned Peter that a day before the exam they would check how he has followed their instructions.So, today is the day when Peter's parents ask him to show the timetable of his preparatory studies. But the boy has counted only the sum of hours sumTime spent him on preparation, and now he wants to know if he can show his parents a timetable sсhedule with d numbers, where each number sсhedulei stands for the time in hours spent by Peter each i-th day on biology studies, and satisfying the limitations imposed by his parents, and at the same time the sum total of all schedulei should equal to sumTime.InputThe first input line contains two integer numbers d, sumTime (1 ≤ d ≤ 30, 0 ≤ sumTime ≤ 240) — the amount of days, during which Peter studied, and the total amount of hours, spent on preparation. Each of the following d lines contains two integer numbers minTimei, maxTimei (0 ≤ minTimei ≤ maxTimei ≤ 8), separated by a space — minimum and maximum amount of hours that Peter could spent in the i-th day.OutputIn the first line print YES, and in the second line print d numbers (separated by a space), each of the numbers — amount of hours, spent by Peter on preparation in the corresponding day, if he followed his parents' instructions; or print NO in the unique line. If there are many solutions, print any of them.ExamplesInput1 485 7OutputNOInput2 50 13 5OutputYES1 4 | Input1 485 7 | OutputNO | 0.5 second | 64 megabytes | ['constructive algorithms', 'greedy', '*1200'] |
A. Watermelontime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputOne hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.InputThe first (and the only) input line contains integer number w (1 ≤ w ≤ 100) — the weight of the watermelon bought by the boys.OutputPrint YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case.ExamplesInput8OutputYESNoteFor example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant — two parts of 4 and 4 kilos). | Input8 | OutputYES | 1 second | 64 megabytes | ['brute force', 'math', '*800'] |
D. Least Cost Bracket Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputThis is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.InputThe first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.OutputPrint the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.Print -1, if there is no answer. If the answer is not unique, print any of them. ExamplesInput(??)1 22 8Output4()() | Input(??)1 22 8 | Output4()() | 1 second | 64 megabytes | ['greedy', '*2600'] |
C. Tic-tac-toetime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputCertainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 × 3 grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the game is finished. The player who draws crosses goes first. If the grid is filled, but neither Xs, nor 0s form the required line, a draw is announced.You are given a 3 × 3 grid, each grid cell is empty, or occupied by a cross or a nought. You have to find the player (first or second), whose turn is next, or print one of the verdicts below: illegal — if the given board layout can't appear during a valid game; the first player won — if in the given board layout the first player has just won; the second player won — if in the given board layout the second player has just won; draw — if the given board layout has just let to a draw. InputThe input consists of three lines, each of the lines contains characters ".", "X" or "0" (a period, a capital letter X, or a digit zero).OutputPrint one of the six verdicts: first, second, illegal, the first player won, the second player won or draw.ExamplesInputX0X.0..X.Outputsecond | InputX0X.0..X. | Outputsecond | 1 second | 64 megabytes | ['brute force', 'games', 'implementation', '*1800'] |
B. Lorrytime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputA group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.InputThe first line contains a pair of integer numbers n and v (1 ≤ n ≤ 105; 1 ≤ v ≤ 109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti, pi (1 ≤ ti ≤ 2; 1 ≤ pi ≤ 104), where ti is the vehicle type (1 – a kayak, 2 – a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.OutputIn the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.ExamplesInput3 21 22 71 3Output72 | Input3 21 22 71 3 | Output72 | 2 seconds | 64 megabytes | ['greedy', 'sortings', '*1900'] |
A. Shortest path of the kingtime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least number of moves. Help him to do this. In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).InputThe first line contains the chessboard coordinates of square s, the second line — of square t.Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8.OutputIn the first line print n — minimum number of the king's moves. Then in n lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD. L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them. ExamplesInputa8h1Output7RDRDRDRDRDRDRD | Inputa8h1 | Output7RDRDRDRDRDRDRD | 1 second | 64 megabytes | ['greedy', 'shortest paths', '*1000'] |
C. Commentator problemtime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to choose the best point of observation, that is to say the point from where all the three stadiums can be observed. As all the sport competitions are of the same importance, the stadiums should be observed at the same angle. If the number of points meeting the conditions is more than one, the point with the maximum angle of observation is prefered. Would you, please, help the famous Berland commentator G. Berniev to find the best point of observation. It should be noted, that the stadiums do not hide each other, the commentator can easily see one stadium through the other.InputThe input data consists of three lines, each of them describes the position of one stadium. The lines have the format x, y, r, where (x, y) are the coordinates of the stadium's center ( - 103 ≤ x, y ≤ 103), and r (1 ≤ r ≤ 103) is its radius. All the numbers in the input data are integer, stadiums do not have common points, and their centers are not on the same line. OutputPrint the coordinates of the required point with five digits after the decimal point. If there is no answer meeting the conditions, the program shouldn't print anything. The output data should be left blank.ExamplesInput0 0 1060 0 1030 30 10Output30.00000 0.00000 | Input0 0 1060 0 1030 30 10 | Output30.00000 0.00000 | 1 second | 64 megabytes | ['geometry', '*2600'] |
B. The least round waytime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThere is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.InputThe first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).OutputIn the first line print the least number of trailing zeros. In the second line print the correspondent way itself.ExamplesInput31 2 34 5 67 8 9Output0DDRR | Input31 2 34 5 67 8 9 | Output0DDRR | 2 seconds | 64 megabytes | ['dp', 'math', '*2000'] |
A. Winnertime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.InputThe first line contains an integer number n (1 ≤ n ≤ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.OutputPrint the name of the winner.ExamplesInput3mike 3andrew 5mike 2OutputandrewInput3andrew 3andrew 2mike 5Outputandrew | Input3mike 3andrew 5mike 2 | Outputandrew | 1 second | 64 megabytes | ['hashing', 'implementation', '*1500'] |
C. Ancient Berland Circustime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputNowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a special pillar, and the rope strung between the pillars marked the arena edges.Recently the scientists from Berland have discovered the remains of the ancient circus arena. They found only three pillars, the others were destroyed by the time.You are given the coordinates of these three pillars. Find out what is the smallest area that the arena could have.InputThe input file consists of three lines, each of them contains a pair of numbers –– coordinates of the pillar. Any coordinate doesn't exceed 1000 by absolute value, and is given with at most six digits after decimal point.OutputOutput the smallest possible area of the ancient arena. This number should be accurate to at least 6 digits after the decimal point. It's guaranteed that the number of angles in the optimal polygon is not larger than 100.ExamplesInput0.000000 0.0000001.000000 1.0000000.000000 1.000000Output1.00000000 | Input0.000000 0.0000001.000000 1.0000000.000000 1.000000 | Output1.00000000 | 2 seconds | 64 megabytes | ['geometry', 'math', '*2100'] |
B. Spreadsheetstime limit per test10 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIn the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.InputThe first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .OutputWrite n lines, each line should contain a cell coordinates in the other numeration system.ExamplesInput2R23C55BC23OutputBC23R23C55 | Input2R23C55BC23 | OutputBC23R23C55 | 10 seconds | 64 megabytes | ['implementation', 'math', '*1600'] |
A. Theatre Squaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.InputThe input contains three positive integer numbers in the first line: n, m and a (1 ≤ n, m, a ≤ 109).OutputWrite the needed number of flagstones.ExamplesInput6 6 4Output4 | Input6 6 4 | Output4 | 1 second | 256 megabytes | ['math', '*1000'] |