1000true
*******InputConstraints*******
*******OutputConstraints*******
*******IOTestCases*******
Hint
______________________________________________________
1001true
The problem is so easy, that the authors were lazy to write a statement for it!
*******InputConstraints*******
The input stream contains a set of integer numbers A_{i} (0 ≤ A_{i} ≤ 10^{18}). The numbers are separated by any number of spaces and line breaks. A size of the input stream does not exceed 256 KB.
*******OutputConstraints*******
For each number A_{i} from the last one till the first one you should output its square root. Each square root should be printed in a separate line with at least four digits after decimal point.
*******IOTestCases*******
input  output 

1427 0
876652098643267843
5276538
 2297.0716
936297014.1164
0.0000
37.7757

______________________________________________________
1002true
In the present world you frequently meet a lot of call numbers and
they are going to be longer and longer. You need to remember such a
kind of numbers. One method to do it in an easy way is to assign
letters to digits as shown in the following picture:
1 ij 2 abc 3 def
4 gh 5 kl 6 mn
7 prs 8 tuv 9 wxy
0 oqz

This way every word or a group of words can be assigned a unique
number, so you can remember words instead of call numbers. It is
evident that it has its own charm if it is possible to find some
simple relationship between the word and the person itself. So you can
learn that the call number 941837296 of a chess playing friend of
yours can be read as WHITEPAWN, and the call number 2855304 of your
favourite teacher is read BULLDOG.
Write a program to find the shortest sequence of words (i.e. one
having the smallest possible number of words) which corresponds to a
given number and a given list of words. The correspondence is
described by the picture above.
*******InputConstraints*******
Input contains a series of tests. The first line of each test contains the call number, the
transcription of which you have to find. The number consists of at
most 100 digits. The second line contains the total number of the
words in the dictionary (maximum is 50 000). Each of the remaining
lines contains one word, which consists of maximally 50 small letters
of the English alphabet. The total size of the input doesn't
exceed 300 KB. The last line contains call number −1.
*******OutputConstraints*******
Each line of output contains the shortest sequence
of words which has been found by your program. The words are separated
by single spaces. If there is no solution to the input data, the line
contains text “No solution.
”. If there are more solutions having the
minimum number of words, you can choose any single one of them.
*******IOTestCases*******
input  output 

7325189087
5
it
your
reality
real
our
4294967296
5
it
your
reality
real
our
1
 reality our
No solution.

______________________________________________________
1003true
Now and then you play the following game with your friend. Your friend
writes down a sequence consisting of zeroes and ones. You choose a
continuous subsequence (for example the subsequence from the third to
the fifth digit inclusively) and ask him, whether this subsequence
contains even or odd number of ones. Your friend answers your question
and you can ask him about another subsequence and so on.
Your task is
to guess the entire sequence of numbers.
You suspect some of your friend's answers may not be correct and you
want to convict him of falsehood. Thus you have decided to write a
program to help you in this matter. The program will receive a series
of your questions together with the answers you have received from
your friend. The aim of this program is to find the first answer which
is provably wrong, i.e. that there exists a sequence satisfying
answers to all the previous questions, but no such sequence satisfies
this answer.
*******InputConstraints*******
Input contains a series of tests. The first line of each test contains one number, which is
the length of the sequence of zeroes and ones. This length is less or
equal to 10^{9}. In the second line, there is one nonnegative integer
which is the number of questions asked and answers to them. The number
of questions and answers is less or equal to 5 000. The remaining lines
specify questions and answers. Each line contains one question and the
answer to this question: two integers (the position of the first and
last digit in the chosen subsequence) and one word which is either
“even
” or “odd
” (the answer, i.e. the parity of the number of ones in
the chosen subsequence, where “even
” means an even number of ones and
“odd
” means an odd number). The input is ended with a line containing −1.
*******OutputConstraints*******
Each line of output containing one
integer X. Number X says that there exists a sequence of zeroes and
ones satisfying first X parity conditions, but there exists none
satisfying X + 1 conditions. If there exists a sequence of zeroes and
ones satisfying all the given conditions, then number X should be the
number of all the questions asked.
*******IOTestCases*******
input  output 

10
5
1 2 even
3 4 odd
5 6 even
1 6 even
7 10 odd
1
 3

______________________________________________________
1004true
There is a travel agency in Adelton town on Zanzibar island. It has decided to
offer its clients, besides many other attractions, sightseeing the town. To
earn as much as possible from this attraction, the agency has accepted a
shrewd decision: it is necessary to find the shortest route which begins and
ends at the same place.
Your task is to write a program which finds such a route.
In the town there are N crossing points numbered from 1 to N and M twoway
roads numbered from 1 to M. Two crossing points can be connected by multiple
roads, but no road connects a crossing point with itself. Each sightseeing
route is a sequence of road numbers y_{1}, …, y_{k}, k > 2. The road y_{i}
(1 ≤ i ≤ k − 1) connects crossing points x_{i} and x_{i+1}, the road y_{k} connects
crossing points x_{k} and x_{1}. All the numbers x_{1}, …, x_{k} should be different.
The length of the sightseeing route is the sum of the lengths of all roads on
the sightseeing route, i.e. L(y_{1}) + L(y_{2}) + … + L(y_{k}) where L(y_{i}) is the
length of the road y_{i} (1 ≤ i ≤ k). Your program has to find such a sightseeing
route, the length of which is minimal, or to specify that it is not possible,
because there is no sightseeing route in the town.
*******InputConstraints*******
Input contains a series of tests.
The first line of each test contains two positive integers: the
number of crossing points N ≤ 100 and the number of roads M ≤ 10000. Each of the
next M lines describes one road. It contains 3 positive integers: the number
of its first crossing point, the number of the second one, and the length of
the road (a positive integer less than 500).
Input is ended with a “−1” line.
*******OutputConstraints*******
Each line of output is an answer. It contains either a string
“No solution.” in case there isn't any sightseeing route, or it contains the
numbers of all crossing points on the shortest sightseeing route in the order
how to pass them (i.e. the numbers x_{1} to x_{k} from our definition of a
sightseeing route), separated by single spaces. If there are multiple
sightseeing routes of the minimal length, you can output any one of them.
*******IOTestCases*******
input  output 

5 7
1 4 1
1 3 300
3 1 10
1 2 16
2 3 100
2 5 15
5 3 20
4 3
1 2 10
1 3 20
1 4 30
1
 1 3 5 2
No solution.

______________________________________________________
1005true
You have a number of stones with known weights W_{1}, …, W_{n}. Write a program that will rearrange the stones into two piles such that weight difference between the piles is minimal.
*******InputConstraints*******
Input contains the number of stones N (1 ≤ N ≤ 20) and weights of the stones W_{1}, …, W_{n} (integers, 1 ≤ W_{i} ≤ 100000) delimited by white spaces.
*******OutputConstraints*******
Your program should output a number representing the minimal possible weight difference between stone piles.
*******IOTestCases*******
input  output 

5
5 8 13 27 14
 3 
______________________________________________________
1006true
Frame consists of the following characters:
Character 
ASCII code 
Description 
┌ 
218 
Left upper corner 
┐ 
191 
Right upper corner 
└ 
192 
Left bottom corner 
┘ 
217 
Right bottom corner 
│ 
179 
Vertical (left and right) border line 
─ 
196 
Horizontal (top and bottom) border line 
N square frames (1 ≤ N ≤ 15) were sequentially drawn on screen 50 characters wide 20 lines tall. If parts of some frames intersect, only the part of the frame drawn latter remains visible. Each frame lies fully on the screen.
You need to write a program that builds a possible sequence of frames that (if drawn sequentially) would produce the same picture on the screen. Your sequence does not have to be the same with the original sequence used to build the picture on the screen. However, it should not contain more than 2000 frames.
*******InputConstraints*******
The screen area was originally filled with dots (ASCII 46). Input contains the final picture on the screen after the sequence of frames is drawn.
*******OutputConstraints*******
Your program should write to output the number of frames in the sequence built and the frames coordinates as follows:
K
X_{1} Y_{1} A_{1}
…
X_{k} Y_{k} A_{k}
Here K is the number of frames, X_{i} and Y_{i} are coordinates of the upper left frame corner (0 ≤ X_{i} ≤ 49, 0 ≤ Y_{i} ≤ 19) and A_{i} is the length of the frame side (2 ≤ A_{i}). All numbers must be delimited with one or more spaces and/or line breaks.
*******IOTestCases*******
input  output 

(see the figure above)  6
16 11 7
32 14 4
4 8 8
11 6 7
36 11 3
28 8 3

______________________________________________________
1007true
A transmitter sends over a noisy line some binary code words. The receiver on the other end uses special technique to recover the original words.
Every word originally consists of symbols 0 and 1. All words have the same length
N (4 ≤
N ≤ 1000). After traveling through the noisy line one (but no more) of the following modifications to a word may occur:
 Any (but only one) symbol 0 is replaced by 1.
 Any (but only one) symbol is removed.
 A symbol (0 or 1) is inserted at any position.
It is known that the original words all have the following property: the sum of positions where symbols 1 are located is a multiple of (N+1) or equal to zero.
*******InputConstraints*******
Input contains number N followed by received words. The words are delimited with line breaks. There will be no more than 2001 words. There is nothing else in the input data, except maybe for some extra spaces or line breaks.
*******OutputConstraints*******
Your program should print to output the original sequence of words as they were transmitted. The words should be delimited by line breaks.
*******IOTestCases*******
input  output 

4
0000
011
1011
11011
 0000
0110
1001
1111

______________________________________________________
1008true
There are several ways to encode an image. In this problem we will consider two representations of an image. We assume that the image consists of black and white pixels. There is at least one black pixel and all black pixels are connected with their sides. Coordinates of black pixels are not less than 1 and not greater than 10. An example of such an image is at the figure.
Both representations describe arrangement of black pixels only.
At the first representation we specify in the first line number of black pixels and coordinates of each black pixel in the following lines. Pixels are listed in order of increasing X. In case of equality of X they are listed in order of increasing Y. Image at the figure is encoded as follows:
6
2 3
2 4
3 3
3 4
4 2
4 3
At the second representation we specify in the first line coordinates of the lowest left black pixel. Each of the following lines contains a description of neighbors for one of the pixels. At first, neighbors of the lowest left pixel are specified, then neighbors of its first neighbor (if it exists) are specified, then neighbors of its second neighbor (if it also exists) follow. When all its neighbors are described the description of the neighbors of its first neighbor follows. The description of the neighbors of its second neighbor follows then and so on.
Each descriptive line contains at most one letter for each neighbor: R for the right, T for the top, L for the left, B for the bottom. If the neighbor was already specified it is not included into the descriptive line and viceversa. Also there is only one descriptive line for each pixel. Neighbors are listed counterclockwise starting with the right. Each descriptive line except the last ends with a comma. The last line ends with a full stop. Image at the figure is encoded as follows:
There are no leading or tailing spaces in any representation. There is exactly one space between X and Y coordinates.
*******InputConstraints*******
One representation of the image will be given to your program in the input.
*******OutputConstraints*******
Your program has to write other representation of the image to the output.
*******IOTestCases*******
input  output 

6
2 3
2 4
3 3
3 4
4 2
4 3
 2 3
RT,
RT,
,
B,
,
.

______________________________________________________
1009true
Let’s consider
Kbased numbers, containing exactly
N digits. We define a number to be valid if its
Kbased notation doesn’t contain two successive zeros. For example:
 1010230 is a valid 7digit number;
 1000198 is not a valid number;
 0001235 is not a 7digit number, it is a 4digit number.
Given two numbers N and K, you are to calculate an amount of valid K based numbers, containing N digits.
You may assume that 2 ≤ K ≤ 10; N ≥ 2; N + K ≤ 18.
*******InputConstraints*******
The numbers N and K in decimal notation separated by the line break.
*******OutputConstraints*******
The result in decimal notation.
*******IOTestCases*******
______________________________________________________
1010true
There is a discrete function. It is specified for integer arguments from 1 to N (2 ≤ N ≤ 100000). Each value of the function is longint (signed long in C++). You have to find such two points of the function for which all points between them are below than straight line connecting them and inclination of this straight line is the largest.
*******InputConstraints*******
There is an N in the first line. Than N lines follow with the values of the function for the arguments 1, 2, …, N respectively.
*******OutputConstraints*******
A pair of integers, which are abscissas of the desired points, should be written into one line of output. The first number must be less then the second one. If it is any ambiguity your program should write the pair with the smallest first number.
*******IOTestCases*******
______________________________________________________
1011true
Background
Everyone making translations from English to Russian knows an English phrase "Naked conductor runs along the bus". It has two very different meanings.
Problem
Every bus in the Ekaterinburg city has a special man (or woman) called
conductor. When you ride the bus, you have to give money to the conductor.
We know that there are more then P% conductors and less then Q% conductors.
Your task is to determine a minimal possible number of Ekaterinburg citizens.
*******InputConstraints*******
Two numbers P,Q such that 0.01 ≤ P, Q ≤ 99.99. Numbers are given with 2 digits precision. These numbers are separated by some spaces or "end of line" symbols.
*******OutputConstraints*******
The minimal number of Ekaterinburg citizens.
*******IOTestCases*******
______________________________________________________
1012true
Let’s consider
Kbased numbers, containing exactly
N digits. We define a number to be valid if its
Kbased notation doesn’t contain two successive zeros. For example:
 1010230 is a valid 7digit number;
 1000198 is not a valid number;
 0001235 is not a 7digit number, it is a 4digit number.
Given two numbers N and K, you are to calculate an amount of valid K based numbers, containing N digits.
You may assume that 2 ≤ K ≤ 10; N ≥ 2; N + K ≤ 180.
*******InputConstraints*******
The numbers N and K in decimal notation separated by the line break.
*******OutputConstraints*******
The result in decimal notation.
*******IOTestCases*******
______________________________________________________
1013true
Let’s consider
Kbased numbers, containing exactly
N digits. We define a number to be valid if its
Kbased notation doesn’t contain two successive zeros. For example:
 1010230 is a valid 7digit number;
 1000198 is not a valid number;
 0001235 is not a 7digit number, it is a 4digit number.
Given two numbers N and K, you are to calculate an amount of valid K based numbers, containing N digits.
You may assume that 2 ≤ K ≤ 10; N ≥ 2; N + K ≤ 1800.
*******InputConstraints*******
The numbers N and K in decimal notation separated by the line break.
*******OutputConstraints*******
The result in decimal notation.
*******IOTestCases*******
______________________________________________________
1014true
Your task is to find the minimal positive integer number Q so that the product of digits of Q is exactly equal to N.
*******InputConstraints*******
The input contains the single integer number N (0 ≤ N ≤ 10^{9}).
*******OutputConstraints*******
Your program should print to the output the only number Q. If such a number does not exist print −1.
*******IOTestCases*******
______________________________________________________
1015true
There are N (1 ≤ N ≤ 10^{5}) dice at the casino’s "Royal Flush" storehouse. Some of them are equal, i.e. one can transform one die to another by properly rotating it. Let’s say that two dice have the same scheme if it’s possible to obtain one of them from another by a series of rotation. In other case (no rotations of the first die lead us to the second die) let’s say that dice have different schemes. Your task is to define the dice with the same scheme.
*******InputConstraints*******
The first line of the input contains the number N. Next N lines contain descriptions of the dice. Each line contains exactly one description of the die. A line describes the die in 6 numbers (separated with spaces): the number of points on the left side of the die, then on the right side, on the top, on the forward side, on the bottom and on the backward side. Certainly, those 6 numbers represent a permutation of integer numbers from 1 to 6 inclusively.
*******OutputConstraints*******
The first line of the output should contain the only number Q of different die’s schemes at the storehouse. Next Q lines should contain the numbers of dice with the same scheme. To be more precisely the second line must begin with 1 and after that (separated by spaces) numbers of dice with the same as die #1 scheme must follow.
We assume that all dice from the input are numbered from 1 to N. The third line (if not all the dice have the same scheme) must begin with the smallest possible number with the scheme different from the scheme of the die #1. This number (say P) is followed by numbers of dice with the same scheme as the scheme of the die #P. All next lines must be printed in the same manner. Numbers in each line of the output must be sorted in increasing order.
*******IOTestCases*******
input  output 

3
1 2 6 4 5 3
4 3 6 2 5 1
4 1 3 6 2 5
 2
1 2
3

______________________________________________________
1016true
A cube placed on some square of a usual chessboard. A cube completely covers one square of the chessboard but not anything more, i.e. size of cube’s edge is equal to the size of square’s edge. The integer number N (0 ≤ N ≤ 1000) is written on the each side of the cube. However it does not imply that the same number is written on all sides. On the different sides there are might be different numbers.
One can move a cube to the next square by rotating it around the common edge of the cube and the square. During this motion the sum of the numbers on the bottom of the cube is calculated (each number is added as much times as it appeared at the bottom of the cube).
Your task is to find the route between two given squares with the minimal sum of numbers on the bottom side. The numbers on the bottom at the beginning and at the end of walk are also counted. The start and the end positions are different.
*******InputConstraints*******
The only line of the input contains the necessary data set (only spaces used as delimiters). First, the start position is given, and then the end position. Each position is composed from the character (from ‘a’ to ‘h’ inclusively, it defines the number of the column on the chessboard) and the digit (from ‘1’ to ‘8’ inclusively, it defines the number of the row). That positions are followed by 6 numbers which are currently written on the near, far, top, right, bottom and left sides of the cube correspondingly.
*******OutputConstraints*******
The only line of the output must contain the minimal sum followed by the optimal route (one of possible routes with minimal sum). The route must be represented by the sequence of cube’s positions during the walk. It begins with the start square and ends with the finish square. All square positions on the chessboard should be given in the same format as in input. Use spaces as delimiters.
*******IOTestCases*******
input  output 

e2 e3 0 8 1 2 1 1
 5 e2 d2 d1 e1 e2 e3

______________________________________________________
1017true
One curious child has a set of N little bricks (5 ≤ N ≤ 500). From these bricks he builds different staircases. Staircase consists of steps of different sizes in a strictly descending order. It is not allowed for staircase to have steps equal sizes. Every staircase consists of at least two steps and each step contains at least one brick. Picture gives examples of staircase for N=11 and N=5:
Your task is to write a program that reads the number N and writes the only number Q — amount of different staircases that can be built from exactly N bricks.
*******InputConstraints*******
*******OutputConstraints*******
*******IOTestCases*******
______________________________________________________
1018true
Let's imagine how apple tree looks in binary computer world. You're right, it looks just like a binary tree, i.e. any biparous branch splits up to exactly two new branches. We will enumerate by integers the root of binary apple tree, points of branching and the ends of twigs. This way we may distinguish different branches by their ending points. We will assume that root of tree always is numbered by 1 and all numbers used for enumerating are numbered in range from 1 to N, where N is the total number of all enumerated points. For instance in the picture below N is equal to 5. Here is an example of an enumerated tree with four branches:
As you may know it's not convenient to pick an apples from a tree when there are too much of branches. That's why some of them should be removed from a tree. But you are interested in removing branches in the way of minimal loss of apples.
So your are given amounts of apples on a branches and amount of branches that should be preserved. Your task is to determine how many apples can remain on a tree after removing of excessive branches.
*******InputConstraints*******
First line of input contains two numbers: N and Q (2 ≤ N ≤ 100; 1 ≤ Q ≤ N − 1). N denotes the number of enumerated points in a tree. Q denotes amount of branches that should be preserved. Next N − 1 lines contains descriptions of branches. Each description consists of a three integer numbers divided by spaces. The first two of them define branch by it's ending points. The third number defines the number of apples on this branch. You may assume that no branch contains more than 30000 apples.
*******OutputConstraints*******
Output should contain the only number — amount of apples that can be preserved. And don't forget to preserve tree's root ;)
*******IOTestCases*******
input  output 

5 2
1 3 1
1 4 10
2 3 20
3 5 20
 21

______________________________________________________
1019true
The segment of numerical axis from 0 to 10^{9} is painted into white color. After that some parts of this segment are painted into black, then some into white again and so on. In total there have been made N repaintings (1 ≤ N ≤ 5000). You are to write a program that finds the longest white open interval after this sequence of repaintings.
*******InputConstraints*******
The first line of input contains the only number N. Next N lines contain information about repaintings. Each of these lines has a form:
a_{i} b_{i} c_{i}
where a_{i} and b_{i} are integers, c_{i} is symbol 'b' or 'w', a_{i}, b_{i}, c_{i} are separated by spaces.
This triple of parameters represents repainting of segment from a_{i} to b_{i} into color c_{i} ('w' — white, 'b' — black). You may assume that 0 < a_{i} < b_{i} < 10^{9}.
*******OutputConstraints*******
Output should contain two numbers x and y (x < y) divided by space(s). These numbers should define the longest white open interval. If there are more than one such an interval output should contain the one with the smallest x.
*******IOTestCases*******
input  output 

4
1 999999997 b
40 300 w
300 634 w
43 47 b
 47 634

______________________________________________________
1020true
Plotters have barbarously hammered N nails into an innocent plane shape, so that one can see now only heads. Moreover, pursuing their mean object, they have hammered all the nails into the vertices of a convex polygon. After that they…it is awful… have roped off the nails, so that the shape felt upset (the rope was very thin). They’ve done it as it is shown in the figure.
Your task is to find out a length of the rope.
*******InputConstraints*******
There two numbers in the first line of the standard input: N — a number of nails (1 ≤ N ≤ 100), and a real number R — a radius of heads of nails. All the heads have the same radius. Further there are N lines, each of them contains a pair of real coordinates (separated by a space) of centers of nails. An absolute value of the coordinates doesn’t exceed 100. The nails are described either in a clockwise or in a counterclockwise order starting from an arbitrary nail. Heads of different nails don’t adjoin.
*******OutputConstraints*******
Output a real number with two digits precision (after a decimal point) — a length of the rope.
*******IOTestCases*******
input  output 

4 1
0.0 0.0
2.0 0.0
2.0 2.0
0.0 2.0
 14.28

______________________________________________________
1021true
Background
— The Brother of mine, the Head of Monastic Order wants to know tomorrow about the results longterm researches. He wants to see neither more nor less than the Summering Machine! Even moreover, he wants our Machine — only a machine — to demonstrate its comprehension of the Sacrament of the Sum as deeply as it is possible. He wants our Machine to find two numbers that give the sum equal to the Sacred Number 10 000.
— Tshshsh! This is madness that borders on blasphemy! How can the Machine calculate the Sacred Number? Twenty seven years we work on it, but we’ve could teach it to tell if the sum of two introduced numbers greater or lower than 10 000. Can an ordinary mortal find two numbers that there sum will be equal to 10 000?
— But we’ll have to do it with the help of our Machine, even if it is not capable. Otherwise we’ll have… let’s say, big problems, if it is possible to call boiling oil like this. However, I have an idea. Do you remember, last week we’ve entered two numbers 7 and 13 into the Machine, and it answered that their sum is lower than 10 000. I don’t know how to check this, but nothing’s left for us than to believe to the fruit of our work. Let’s enter now a greater number than 7 and start up the Machine again. We’ll do like this again and again until we find a number that being added to 13 will give us 10 000. The only thing we are to do is to prepare an ascending list of numbers.
— I don’t believe in this… Let’s start with the sum that is obviously greater than the Sacred Number and we’ll decrease one of the summand. So we have more chances to avoid boilin… big problems.
Haven’t come to an agreement, the Brothers went away to their cells. By next day everyone of them has prepared a list of numbers that, to his opinion, could save them… Can both of the lists save them together?
Problem
Your program should decide, if it is possible to choose from two lists of integers such two numbers that their sum would be equal to 10 000.
*******InputConstraints*******
You are given both of these lists one by one. Format of each of these lists is as follows: in the first line of the list the quantity of numbers N_{i} of the ith list is written. Further there is an ith list of numbers each number in its line (N_{i} lines).The following conditions are satisfied: 1 ≤ N_{i} ≤ 50 000, each element of the lists lays in the range from 32768 to 32767. The first list is ascending and the second one is descending.
*******OutputConstraints*******
You should write "YES" to the standard output if it is possible to choose from the two lists of integers such two numbers that their sum would be equal to 10 000. Otherwise you should write "NO".
*******IOTestCases*******
input  output 

4
175
19
19
10424
3
8951
424
788  YES 
______________________________________________________
1022true
Background
The system of Martians’ blood relations is confusing enough. Actually, Martians bud when they want and where they want. They gather together in different groups, so that a Martian can have one parent as well as ten. Nobody will be surprised by a hundred of children. Martians have got used to this and their style of life seems to them natural.
And in the Planetary Council the confusing genealogical system leads to some embarrassment. There meet the worthiest of Martians, and therefore in order to offend nobody in all of the discussions it is used first to give the floor to the old Martians, than to the younger ones and only than to the most young childless assessors. However, the maintenance of this order really is not a trivial task. Not always Martian knows all of his parents (and there’s nothing to tell about his grandparents!). But if by a mistake first speak a grandson and only than his young appearing greatgrandfather, this is a real scandal.
Problem
Your task is to write a program, which would define once and for all, an order that would guarantee that every member of the Council takes the floor earlier than each of his descendants.
*******InputConstraints*******
The first line of the standard input contains an only number N, 1 ≤ N ≤ 100 — a number of members of the Martian Planetary Council. According to the centuriesold tradition members of the Council are enumerated with integers from 1 up to N. Further, there are exactly N lines, moreover, the ith line contains a list of ith member’s children. The list of children is a sequence of serial numbers of children in a arbitrary order separated by spaces. The list of children may be empty. The list (even if it is empty) ends with 0.
*******OutputConstraints*******
The standard output should contain in its only line a sequence of speakers’ numbers, separated by spaces. If several sequences satisfy the conditions of the problem, you are to write to the standard output any of them. At least one such sequence always exists.
*******IOTestCases*******
input  output 

5
0
4 5 1 0
1 0
5 3 0
3 0
 2 4 5 3 1

______________________________________________________
1023true
Background
As you surely already know, Yekaterinburg has gotten its right to hold The Summer Olympic Games of the 2032. It is planned that it will be allowed to Russia as a countryorganizer to emend a program of the games a bit. So, in order to improve the command result it has been decided to replace the competition in gymnastics by the competition in the new game "Buttons".
The rules of the game are very simple. There’s a small heap of K buttons before two players. The players in turns take buttons from the heap, moreover, at a time one can take a number of buttons from 1 up to L. The one who takes the last button is the winner.
The rules of the Olympic Games will be a bit harder then usual. The one, who is to make a first step according to a lot, has an opportunity to fix a number K with the following restriction to it: 3 ≤ K ≤ 10^{8} (that is the exact number of buttons that has been prepared for the Olympic tournament). The player who is to make the second step fixes a number L that satisfies the following conditions 2 ≤ L < K.
Problem
A very crucial task is given to your team: you are to write a program that should help the second player to make his choice. In other words, given a number K your program is to find a number L that guaranties a victory to the second player with a proper game of both sides.
So, for instance, there are only three buttons in the heap, the choice L = 2 provides for the victory of the second player. Really, if the first player takes only one button at his turn, the second one wins, taking the two last buttons. On the contrary, if the first one takes two buttons, the second one wins, taking the last button.
*******InputConstraints*******
The standard input consists of one line, which contains an only integer number K — a number of buttons in the heap, that has fixed the first player at his turn.
*******OutputConstraints*******
To the standard output you are to write the only number L — the maximal number of buttons that can be taken at a time which provides for the victory of the second player. If there are several those numbers L, you should write the least. If there are no such numbers, you are to write 0 to the standard output.
*******IOTestCases*******
______________________________________________________
1024true
Background
We remind that the permutation of some final set is a onetoone mapping of the set onto itself. Less formally, that is a way to reorder elements of the set. For example, one can define a permutation of the set {1,2,3,4,5} as follows:
This record defines a permutation P as follows: P(1) = 4, P(2) = 1, P(3) = 5, etc.
What is the value of the expression P(P(1))? It’s clear, that P(P(1)) = P(4) = 2. And P(P(3)) = P(5) = 3. One can easily see that if P(n) is a permutation then P(P(n)) is a permutation as well. In our example (check it by yourself)
It is natural to denote this permutation by P^{2}(n) = P(P(n)). In a general form the definition is as follows: P(n) = P^{1}(n), P^{k}(n) = P(P^{k1}(n)).
Among the permutations there is a very important one — that moves nothing:
It is clear that for every k the following relation is satisfied: (E_{N})^{k} = E_{N}. The following less trivial statement is correct (we won’t prove it here, you may prove it yourself incidentally):
Let P(n) be some permutation of an N elements set. Then there exists a positive integer k, that P^{k} = E_{N}.
The least positive integer k such that P^{k} = E_{N} is called an order of the permutation P.
Problem
The problem that your program should solve is formulated now in a very simple manner: “Given a permutation find its order.”
*******InputConstraints*******
The first line contains the only integer N (1 ≤ N ≤ 1000), that is a number of elements in the set that is rearranged by this permutation. In the second line there are N integers of the range from 1 up to N, separated by a space, that define a permutation — the numbers P(1), P(2),…, P(N).
*******OutputConstraints*******
You should write the order of the permutation. You may consider that an answer shouldn’t exceed 10^{9}.
*******IOTestCases*******
______________________________________________________
1025true
Background
In one of the countries of Caribbean basin all decisions were accepted by the simple majority of votes at the general meeting of citizens (fortunately, there were no lots of them). One of the local parties, aspiring to come to power as lawfully as possible, got its way in putting into effect some reform of the election system. The main argument was that the population of the island recently had increased and it was to longer easy to hold general meetings.
The essence of the reform is as follows. From the moment of its coming into effect all the citizens were divided into K (may be not equal) groups. Votes on every question were to be held then in each group, moreover, the group was said to vote “for” if more than half of the group had voted “for”, otherwise it was said to vote “against”. After the voting in each group a number of group that had voted “for” and “against” was calculated. The answer to the question was positive if the number of groups that had voted “for” was greater than the half of the general number of groups.
At first the inhabitants of the island accepted this system with pleasure. But when the first delights dispersed, some negative properties became obvious. It appeared that supporters of the party, that had introduced this system, could influence upon formation of groups of voters. Due to this they had an opportunity to put into effect some decisions without a majority of voters “for” it.
Let’s consider three groups of voters, containing 5, 5 and 7 persons, respectively. Then it is enough for the party to have only three supporters in each of the first two groups. So it would be able to put into effect a decision with the help of only six votes “for” instead of nine, that would be necessary in the case of general votes.
Problem
You are to write a program, which would determine according to the given partition of the electors the minimal number of supporters of the party, sufficient for putting into effect of any decision, with some distribution of those supporters among the groups.
*******InputConstraints*******
In the first line an only odd integer K — a quantity of groups — is written (1 ≤ K ≤ 101). In the second line there are written K odd integers, separated with a space. Those numbers define a number of voters in each group. The population of the island does not exceeds 9999 persons.
*******OutputConstraints*******
You should write a minimal quantity of supporters of the party, that can put into effect any decision.
*******IOTestCases*******
______________________________________________________
1026true
Background
The database of the Pentagon contains a topsecret information. We don’t know what the information is — you know, it’s topsecret, — but we know the format of its representation. It is extremely simple. We don’t know why, but all the data is coded by integers from 1 up to 5000. The size of the main base (we’ll denote it be N) is rather big — it may contain up to 100 000 those numbers. The database is to process quickly every query. The most often query is: "Which element is ith by its value?"— with i being an integer in a range from 1 to N.
Problem
Your program is to play a role of a controller of the database. In the other words, it should be able to process quickly queries like this.
*******InputConstraints*******
Input of the problem consists of two parts. At first, a database is written, and then there’s a sequence of queries. The format of database is very simple: in the first line there’s a number N, in the next N lines there are numbers of the database one in each line in an arbitrary order. A sequence of queries is written simply as well: in the first line of the sequence a number of queries K (1 ≤ K ≤ 100) is written, and in the next K lines there are queries one in each line. The query "Which element is ith by its value?" is coded by the number i. A database is separated from a sequence of queries by the string of three symbols "#".
*******OutputConstraints*******
The output should consist of K lines. In each line there should be an answer to the corresponding query. The answer to the query "i" is an element from the database, which is ith by its value (in the order from the least up to the greatest element).
*******IOTestCases*******
input  output 

5
7
121
123
7
121
###
4
3
3
2
5
 121
121
7
123

______________________________________________________
1027true
Background
The language D++, that was perfected by the participants of our March competition, continues improving. Its founders try to make the syntax as clear as it is possible in order to make the programming simpler in the future. Of course, some minimal set of rules is to stay without changes.
Your program is to check the observance of rules, concerning the arrangement of brackets and comments.
Problem
A text of a correct D++ program contains a symbol part, arithmetic expressions and comments. Comments may appear everywhere and may contain any symbols. A comment is always opened by a pair of symbols "(*" and is closed by a pair of symbols "*)". Each comment must be closed. An arithmetic expression in D++ is always opened by "(", is closed by ")" and may contain only symbols "=+*/0123456789)(" and "end of line" symbols. An arithmetic expression can't start with a pair of symbols "(*". You may run across embedded brackets in an arithmetic expression. In this case these brackets are to be balanced. It means that "((1)))" as well as "(23))((+)" are not correct arithmetic expressions. An arithmetic expression is correct if and only if brackets placed correctly. At last, all the rest of the program text (the result of rejection of all comments and arithmetic expressions from the initial text of the program) may contain every symbol excluding "(" and ")".
We would like to especially notice that the spaces are possible anywhere in a text of a program except when appearing in arithmetic expressions.
*******InputConstraints*******
Some text is written in the standard input. There are not more than 10000 symbols in the text. There may be Latin letters, digits, brackets, symbols of arithmetic operations, spaces and "end of line" symbols.
*******OutputConstraints*******
Your program should write "YES" to the output if the introduced text is a correct D++ program, and "NO" otherwise.
*******IOTestCases*******
input 

Hello, here is a sample D++ program. It contains some arithmetical expressions like
(2+2=4), (2+/*) and ((3+3)*3=20(*this is not true, but you don’t have to verify it :) *)+8)
(* the closing bracket in the previous comment is also in order, since this bracket
does not belong to any arithmetical expression*)

output 

YES

______________________________________________________
1028true
Astronomers often examine star maps where stars are represented by points on a plane and each star has Cartesian coordinates. Let the level of a star be an amount of the stars that are not higher and not to the right of the given star. Astronomers want to know the distribution of the levels of the stars.
For example, look at the map shown on the figure above. Level of the star number 5 is equal to 3 (it's formed by three stars with a numbers 1, 2 and 4). And the levels of the stars numbered by 2 and 4 are 1. At this map there are only one star of the level 0, two stars of the level 1, one star of the level 2, and one star of the level 3.
You are to write a program that will count the amounts of the stars of each level on a given map.
*******InputConstraints*******
The first line of the input contains a number of stars N (1 ≤ N ≤ 15000). The following N lines describe coordinates of stars (two integers X and Y per line separated by a space, 0 ≤ X,Y ≤ 32000). There can be only one star at one point of the plane. Stars are listed in ascending order of Y coordinate. Stars with equal Y coordinates are listed in ascending order of X coordinate.
*******OutputConstraints*******
The output should contain N lines, one number per line. The first line contains amount of stars of the level 0, the second does amount of stars of the level 1 and so on, the last line contains amount of stars of the level N−1.
*******IOTestCases*******
input  output 

5
1 1
5 1
7 1
3 3
5 5
 1
2
1
1
0

______________________________________________________
1029true
Mr. F. wants to get a document be signed by a minister. A minister signs a document only if it is approved by his ministry. The ministry is an Mfloor building with floors numbered from 1 to M, 1 ≤ M ≤ 100. Each floor has N rooms (1 ≤ N ≤ 500) also numbered from 1 to N. In each room there is one (and only one) official.
A document is approved by the ministry only if it is signed by at least one official from the Mth floor. An official signs a document only if at least one of the following conditions is satisfied:
 the official works on the 1st floor;
 the document is signed by the official working in the room with the same number but situated one floor below;
 the document is signed by an official working in a neighbouring room (rooms are neighbouring if they are situated on the same floor and their numbers differ by one).
Each official collects a fee for signing a document. The fee is a nonnegative integer not exceeding 10^{9}.
You should find the cheapest way to approve the document.
*******InputConstraints*******
The first line of an input contains two integers, separated by space. The first integer M represents the number of floors in the building, and the second integer N represents the number of rooms per floor. Each of the next M lines contains N integers separated with spaces that describe fees (the kth integer at lth line is the fee required by the official working in the kth room at the lth floor).
*******OutputConstraints*******
You should print the numbers of
rooms in the order they should be visited to
approve the document in the cheapest way. If there are more
than one way leading to the cheapest cost you may print an any of them.
*******IOTestCases*******
input  output 

3 4
10 10 1 10
2 2 2 10
1 10 10 10
 3 3 2 1 1

Hint
You can assume that for each official there always exists a way to get the approval of a document (from the 1st floor to this official inclusively) paying no more than 10^{9}.
______________________________________________________
1030true
Background
It is a historical fact that during the legendary voyage of "Titanic" the wireless telegraph machine had delivered 6 warnings about the danger of icebergs. Each of the telegraph messages described the point where an iceberg had been noticed. The first five warnings were transferred to the captain of the ship. The sixth one came late at night and a telegraph operator did not notice that the coordinates mentioned were very close to the current ship's position.
Problem
Write a program that will warn the operator about the danger of icebergs!
*******InputConstraints*******
The input messages are of the following format:
Message #<n>.
Received at <HH>:<MM>:<SS>.
Current ship's coordinates are
<X1>^<X2>'<X3>" <NL/SL>
and <Y1>^<Y2>'<Y3>" <EL/WL>.
An iceberg was noticed at
<A1>^<A2>'<A3>" <NL/SL>
and <B1>^<B2>'<B3>" <EL/WL>.
===
Here <n> is a positive integer, <HH>:<MM>:<SS> is the
time of the message reception,
<X1>^<X2>'<X3>" <NL/SL> and <Y1>^<Y2>'<Y3>" <EL/WL> means
"X1 degrees X2 minutes X3 seconds of North (South) latitude and
Y1 degrees Y2 minutes Y3 seconds of East (West) longitude."
*******OutputConstraints*******
Your program should print to the output message in the following format:
The distance to the iceberg: <s> miles.
Where <s> should be the distance between the ship and the iceberg, (that is the length of the shortest path on the sphere between the ship and the iceberg). This distance should be printed up to (and correct to) two decimal digits. If this distance is less than (but not equal to!) 100 miles the program should print one more line with the text:
*******IOTestCases*******
input  output 

Message #513.
Received at 22:30:11.
Current ship’s coordinates are
41^46'00" NL
and 50^14'00" WL.
An iceberg was noticed at
41^14'11" NL
and 51^09'00" WL.
===
 The distance to the iceberg: 52.04 miles.
DANGER!

Hint
For simplicity of calculations assume that the Earth is an ideal sphere with the diameter of 6875 miles completely covered with water. Also you can be sure that lines
break exactly as it is shown in the input samples. The ranges of the ship and the iceberg coordinates are the same as the usual range for geographical coordinates, i.e. from 0 to 90 degrees inclusively for NL/SL and from 0 to 180 degrees inclusively for EL/WL.
______________________________________________________
1031true
The railway line “YekaterinburgSverdlovsk” with several stations has been built. This railway line can be represented as a line segment, railway stations being points on it. The railway line starts at the station “Yekaterinburg” and finishes at the station “Sverdlovsk”, so stations are numbered starting from “Yekaterinburg” (it has number 1) and “Sverdlovsk” is the last station.
Cost of the ticket between any two stations depends only on a distance between them. The prices for the tickets are specified in the following table.
distance X between stations 
price for the ticket 
0 < X ≤ L_{1} 
C_{1} 
L_{1} < X ≤ L_{2} 
C_{2} 
L_{2} < X ≤ L_{3} 
C_{3} 
Direct tickets from one station to another can be booked if and only if the distance between these station does not exceed L_{3}. So sometimes it is necessary to book several tickets to pay for the parts of the whole way between stations.
For example, on the railway line shown at the figure above there are seven stations. The direct ticket from the second station to the sixth one can not be booked. There are several ways to pay for the travel between these stations. One of them is to book two tickets: one ticket at price C_{2} to travel between the second and the third stations, and other at price C_{3} to travel between the third and the sixth stations. Note, that though the distance between the second and the sixth stations is equal to 2L_{2}, the whole travel can not be paid by booking two tickets at price C_{2}, because each ticket is valid for only one travel and each travel should start and end only at stations.
Your task is to write a program, that will find the minimal cost of the travel between two given stations.
*******InputConstraints*******
The first line of the input contains 6 integers L_{1}, L_{2}, L_{3}, C_{1}, C_{2}, C_{3} (1 ≤ L_{1} < L_{2} < L_{3} ≤ 10^{9},
1 ≤ C_{1} < C_{2} < C_{3} ≤ 10^{9}) in the specified order with one space between. The second line contains the amount of stations N (2 ≤ N ≤ 10000). The third line contains two different integers separated by space. They represent serial numbers of stations, the travel between which must be paid. Next N−1 lines contain distances from the first station (“Yekaterinburg”) on the railway line to others. These distances are given as different positive integers and are arranged in the ascending order. The distance from “Yekaterinburg” to “Sverdlovsk” does not exceed 10^{9}. The distance between any neighboring stations does not exceed L_{3}. The minimal travel cost between two given stations will not exceed 10^{9}.
*******OutputConstraints*******
Program should print to the output the only number, which is the minimal travel cost between two given stations.
*******IOTestCases*******
input  output 

3 6 8 20 30 40
7
2 6
3
7
8
13
15
23
 70

______________________________________________________
1032true
The input contains N positive integers (N ≤ 10000). Each of that numbers is not greater than 15000. This numbers are not necessarily different (so it may happen that two or more of them will be equal). Your task is to choose a few of given numbers (1 ≤ few ≤ N) so that the sum of chosen numbers is multiple for N (i.e. N * k = (sum of chosen numbers) for some integer k).
*******InputConstraints*******
The first line of the input contains the single number N. Each of next N lines contains one number from the given set.
*******OutputConstraints*******
In case your program decides that the target set of numbers can not be found it should print to the output the single number 0. Otherwise it should print the number of the chosen numbers in the first line followed by the chosen numbers themselves (on a separate line each) in arbitrary order.
If there are more than one set of numbers with required properties you should print to the output only one (preferably your favorite) of them.
*******IOTestCases*******
input  output 

5
1
2
3
4
1
 2
2
3

______________________________________________________
1033true
Administration of the labyrinth has decided to start a new season with new wallpapers. For this purpose they need a program to calculate the square of the walls inside the labyrinth. This job is just for you!
The labyrinth is represented by a matrix N×N (3 ≤ N ≤ 33, you see, ‘3’ is a magic digit!). Some matrix cells contain a dot character (‘.’) that denotes an empty square. Other cells contain a diesis character (‘#’) that denotes a square filled by monolith block of stone wall. All squares are of the same size 3×3 meters.
The walls are constructed around the labyrinth (except for the upper left and lower right corners, which are used as entrances) and on the cells with a diesis character. No other walls are constructed. There always will be a dot character at the upper left and lower right corner cells of the input matrix.
Your task is to calculate the square of visible part of the walls inside the labyrinth. In other words, the square of the walls' surface visible to a visitor of the labyrinth. Note that there's no holes to look or to move through between any two adjacent blocks of the wall. The blocks are considered to be adjacent if they touch each other in any corner. See picture for an example: visible walls inside the labyrinth are drawn with bold lines. The height of all the walls is 3 meters.
*******InputConstraints*******
The first line of the input contains the single number N. The next N lines contain N characters each. Each line describes one row of the labyrinth matrix. In each line only dot and diesis characters will be used and each line will be finished with a new line character. There will be no spaces in the input.
*******OutputConstraints*******
Your program should print to the output a single integer — the exact value of the square of the wallpaper needed.
*******IOTestCases*******
input  output 

5
.....
...##
..#..
..###
.....
 198

______________________________________________________
1034true
On a chessboard of size N×N (N ≤ 50) N queens are placed. We'll say that queens are in peaceful position if none of them can attack another. You are to find the total amount of peaceful positions that can be obtained from the given peaceful position by rearranging of exactly three queens.
*******InputConstraints*******
The first line of input will contain an integer number N that represents the size of a chessboard (and the number of queens also). It will be followed by N lines describing positions of queens. Each line will contain two integers X and Y separated by a space. These numbers represent horizontal and vertical coordinates and lay in a range from 1 to N.
*******OutputConstraints*******
The output consists of a single integer representing the number of peaceful positions that can be achieved from initial position by moving of exactly three queens. Note: queens are not numbered so if you rearrange them on the chessboard using only squares they already occupied you’ll always get the same peaceful position, not the new one.
*******IOTestCases*******
input  output 

4
2 1
1 3
3 4
4 2
 0

______________________________________________________
1035true
Archaeologists have found a cloth decorated with needlework. This needlework is a crossstitch made with several threads. The following rules have been observed:
 The cloth has a grid with square cells.
 Each stitch covers a diagonal of one cell of the grid. Stitches can lie on both sides of the cloth, but each of them lies only at one side of the cloth (the thread can start, finish and cross the cloth only at the grid vertices).
 At most one stitch can lie on each diagonal of each cell at each side of the cloth.
 Each thread makes up several stitches arranged alternately at different sides of the cloth. (It means that two consecutive stitches formed by one thread lay at the different sides of the cloth and are connected in the grid vertex)
 A needle can go through the cloth only in the vertexes of the grid.
On the figure you can see an example of a pattern made with six stitches. The grid has size 4*5. The face of the cloth is drawn on the upper half of the figure. The stitches lying on the face are drawn with solid lines. The rear stitches uncovered with those of the face are drawn with dotlines. On the lower half of the figure the cloth is oriented as on the upper half. All the rear stitches are drawn with solid lines there. The face stitches, which do not cover rear stitches, are drawn with dotlines. It can be seen that there are the stitches at both sides of one of the cell diagonals. This crossstitch cannot be made with less than four threads.
Archaeologists want to know if the pattern was made with the least number of threads. You have to write a program, which will determine the minimal number of threads needed to make the given pattern.
*******InputConstraints*******
The first line of the input contains two integers N and M separated by a space. They are vertical (N) and horizontal (M) sizes of the grid, i.e. amounts of the cells in a vertical and horizontal rows respectively (1 ≤ N,M ≤ 200). Each of the following 2N lines contains M symbols. Each symbol describes one square of the grid. The first N lines correspond to the face of the cloth and the last N lines correspond to the rear of the cloth. The symbols used are “.”, “/”, “\” and “X” (a dot means an empty square).
For more information see the sample. It corresponds to the cloth drawn at the figure.
*******OutputConstraints*******
The output should contain one integer — the minimal number of threads needed to make the described pattern.
*******IOTestCases*******
input  output 

4 5
.....
.\...
..\..
.....
.....
....\
.\X..
.....
 4

______________________________________________________
1036true
You are given a number 1 ≤ N ≤ 50. Every ticket has its 2Ndigit number. We call a ticket lucky, if the sum of its first N digits is equal to the sum of its last N digits. You are also given the sum of ALL digits in the number.
Your task is to count an amount of lucky numbers, having the specified sum of ALL digits.
*******InputConstraints*******
Two spaceseparated numbers: N and S. Here S is the sum of all digits. Assume that 0 ≤ S ≤ 1000.
*******OutputConstraints*******
The amount of lucky tickets.
*******IOTestCases*******
Hint
The tickets are 0101, 0110, 1001, 1010 in the example above
______________________________________________________
1037true
Background
Don't you know that at school pupils’ programming contest a new computer language has been developed. We call it D++. Generally speaking it doesn't matter if you know about it or not. But to run programs written in D++ we need a new operating system. It should be rather powerful and complex. It should work fast and have a lot of possibilities. But all this should be done in a future.
And now you are to… No. You should not devise the name for the operating system. You are to write the first module for this new OS. And of course it's the memory management module. Let's discuss how it is expected to work.
Problem
Our operating system is to allocate memory in pieces that we’ll call “blocks”. The blocks are to be numbered by integers from 1 up to N. When operating system needs more memory it makes a request to the memory management module. To process this request the memory management module should find free memory block with the least number. You may assume that there are enough blocks to process all requests.
Now we should define the meaning of words “free block”. At the moment of first request to the memory management module all blocks are considered to be free. Also a block becomes free when there were no requests to it during T minutes.
You may wonder about a notion “request to allocated blocks”. What does it mean, “request to allocated block”? The answer is simple: at any time the memory management module may be requested to access a given block. To process this request the memory management module should check if the requested block is really allocated. If it is, the request is considered to be successful and the block remains allocated for T minutes more. Otherwise the request is failed.
That's all about the algorithms of the memory management block. You are to implement them for N = 30 000 and T = 10 minutes.
*******InputConstraints*******
Each line of input contains a request for memory block allocation or memory block access. Memory allocation request has a form:
where <Time> is a nonnegative integer number not greater than 65 000. Time is given in seconds. Memory block access request has a form:
where <Time> meets conditions mentioned above for the memory allocation request and <BlockNo> is an integer value in range from 1 to N. There will be no more than 80000 requests.
*******OutputConstraints*******
For each line of input you should print exactly one line with a result of request processing. For memory allocation request you are to write an only integer — a number of allocated block. As it was mentioned above you may assume that every request can be satisfied, there will be no more than N simultaneously allocated blocks. For memory block access request you should print the only character:
 '+' if request is successful (i.e. block is really allocated);
 '' if request fails (i.e. block with number given is free, so it can't be accessed).
Requests are arranged by their times in an increasing order. Requests with equal times should be processed as they appear in input.
*******IOTestCases*******
input  output 

1 +
1 +
1 +
2 . 2
2 . 3
3 . 30000
601 . 1
601 . 2
602 . 3
602 +
602 +
1202 . 2
 1
2
3
+
+


+

1
3


______________________________________________________
1038true
The boss of a firm that you are employed with is dissatisfied with the text processor Word. He wants you to write a better text processor by tomorrow. The interface of the new processor should be clearer, there should be more options, and the resulting text should be more beautiful. You told the boss that this work would take not less than four days. Then your boss asked you to begin with a spell checking program. This program should check capital and small letters. It should detect a mistake in each of the following cases.
 The first letter in a sentence is small.
 A capital letter is not the first letter in a word.
A word is a sequence of letters not containing any other symbols or ends of line.
The end of a sentence is defined a full stop, a questionmark or an exclamation mark.
*******InputConstraints*******
Input contains a text that consists of capital and small letters of the Latin alphabet (A–Z, a–z), digits (0–9), punctuation marks (.,;:!?) and space characters. The text length is not more than 10000.
*******OutputConstraints*******
Output should contain a number of mistakes in the input text.
*******IOTestCases*******
input  output 

This sentence iz correkt! It Has,No mista;.Kes et oll.
But there are two BIG mistakes in this one!
and here is one more.
 3 
______________________________________________________
1039true
Background
The president of the Ural State University is going to make an 80'th Anniversary party. The university has a hierarchical structure of employees; that is, the supervisor relation forms a tree rooted at the president. Employees are numbered by integer numbers in a range from 1 to N, The personnel office has ranked each employee with a conviviality rating. In order to make the party fun for all attendees, the president does not want both an employee and his or her immediate supervisor to attend.
Problem
Your task is to make up a guest list with the maximal conviviality rating of the guests.
*******InputConstraints*******
The first line of the input contains a number N. 1 ≤ N ≤ 6000.
Each of the subsequent N lines contains the conviviality rating of the corresponding employee.
Conviviality rating is an integer number in a range from –128 to 127. After that the supervisor relation tree goes.
Each line of the tree specification has the form
which means that the Kth employee is an immediate supervisor of Lth employee.
Input is ended with the line
*******OutputConstraints*******
The output should contain the maximal total rating
of the guests.
*******IOTestCases*******
input  output 

7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
 5 
______________________________________________________
1040true
Background
An airline company is a sponsor of the 80th Anniversary celebration at the Ural State University. In return for it the company wants the University to help it. The company serves N airports and carries out flights between some of them. In order to simplify the work the flights are numbered with integers from 1 up to M. If there is a flight between two airports a plane flies in the both directions with the same flight number. There may be only one flight between any two airports. One can fly between any pair of airports served by company using only its flights.
The airline company understands that its planes may attract terrorists. In order to create difficulties for terrorists the company wants to number the flights in some special manner. If there are several flights that depart from one airport then the greatest common divisor of their flight numbers should be equal to 1. The company turns to you for help (remember, this is a sponsor; you are to work properly).
Problem
You should write a program that finds a required numbering or informs that it is impossible to satisfy the requirements. If several numberings are possible, it is sufficient to find any one of them.
*******InputConstraints*******
The first line of input contains numbers N and M separated with a space (2 ≤ N ≤ 50). The next M lines contain information on flights. Each flight is determined by the numbers of the airports that it connects. The numbers of the airports are separated with a space.
*******OutputConstraints*******
The first line of an output should contain YES, if it is possible to find a required numbering, and NO otherwise. If the answer is YES, the second line should contain a possible numbering of flights. The numbers are to be ordered as it is done in the input. Flight numbers are to be separated with a space.
*******IOTestCases*******
input  output 

6 6
1 2
2 3
2 4
4 3
5 6
4 5
 YES
4 2 3 1 5 6

______________________________________________________
1041true
Background
Nikifor has decided to present the dean of the Department of Mathematics and Mechanics with a linearly independent vector system (you know, that we’ve just celebrated jubilees of the University and of the Department). A store sells M items of Ndimensional vectors, 3 ≤ N ≤ M ≤ 2000; N ≤ 50. For each vector its price c_{i} is known, 0 < i ≤ M. Nikifor wants to buy N linearly independent vectors paying for them minimal sum of money.
Problem
Write a program that would determine which vectors Nikifor should buy or would inform that it is impossible to satisfy his requirements.
*******InputConstraints*******
The first line of an input contains numbers M and N separated with a space. The next M lines contain the vectors on sale. All of the coordinates are integers with an absolute value not exceeding 2 000. The numbers are separated from each other with a space. The next M lines contain prices c_{i}, one number in each line. The prices are positive integers not exceeding 15 000.
*******OutputConstraints*******
The first line of an output should contain the minimal amount of money that Nikifor is to pay or the number 0, if Nikifor’s requirements cannot be satisfied in this store. If it is possible to make a purchase, then the next N lines should contain the numbers of the vectors that Nikifor should buy. If several sets of such numbers are possible, then you should write one of them which is minimal according to the lexicographic order.
*******IOTestCases*******
input  output 

5 3
1 0 0
0 1 0
0 0 1
0 0 2
0 0 3
10
20
30
10
10
 40
1
2
4

______________________________________________________
1042true
Winter has come, but at the Ural State University heating is not turned on yet. There’s one little problem: the University is heated only if all of the valves are opened. There are some technicians at the University. Each of them is responsible for one or more valves. There may be several technicians responsible for the same valve. When a technician gets an instruction to turn on the heating he goes round all of his valves and turns them. It means that if a valve was opened then he closes it, and if it was closed then he opens it. It is well known that every technician earns his money not in vain so it’s impossible to replace any technician by any combination of other technicians.
Your task is to determine who of the technicians is to get an instruction “to turn on the heating” in order to heat all the Ural State University. Note that there are N technicians and N valves at the University (1 ≤ N ≤ 250).
*******InputConstraints*******
The first line of the input contains the number N. The next N lines contain lists of the valves in charge of each of the technicians. It means that the line number i + 1 contains numbers of the valves that the ith technician is responsible for. Each list of valves is followed by –1.
*******OutputConstraints*******
An output should contain a list of technicians’ numbers sorted in ascending order. If several lists are possible, you should send to an output the shortest one. If it’s impossible to turn on the heating at the University, you should write “No solution”.
*******IOTestCases*******
input  output 

4
1 2 1
2 3 4 1
2 1
4 1
 1 2 3

______________________________________________________
1043true
Background
A huge dancinghall was constructed for the Ural State University’s 80th anniversary celebration. The size of the hall is 2000 × 2000 metres! The floor was made of square mirror plates with side equal to 1 metre. Then the walls were painted with an indelible paint. Unfortunately, in the end the painter flapped the brush and the beautiful mirror floor was stained with the paint. But not everything is lost yet! The stains can be covered with a carpet.
Nobody knows why, but the paint on the floor formed an arc of a circle (a centre of the circle lies inside the hall). The dean of the Department of Mathematics and Mechanics measured the coordinates of the arc's ends and of some other point of the arc (he is sure that this information is quite enough for any student of the Ural State University). The dean wants to cover the arc with a rectangular carpet. The sides of a carpet must go along the sides of the mirror plates (so, the corners of the carpet must have integer coordinates).
Problem
You should find the minimal square of such a carpet.
*******InputConstraints*******
Input consists of six integers. The first two lines contain the coordinates of the arc's ends. The coordinates of an inner point of the arc follow them. Absolute values of all coordinates don't exceed 1000. The points don't belong the same straight line. The arc lies inside the square [1000,1000]^{2}.
*******OutputConstraints*******
You should write the minimal square of the carpet covering this arc.
*******IOTestCases*******
input  output 

476 612
487 615
478 616
 66

______________________________________________________
1044true
Background
The public transport administration of Ekaterinburg is anxious about the fact that passengers don’t like to pay for passage doing their best to avoid the fee. All the measures that had been taken (hard currency premiums for all of the chiefs, increase in conductors’ salaries, reduction of number of buses) were in vain. An advisor especially invited from the Ural State University says that personally he doesn’t buy tickets because he rarely comes across the lucky ones (a ticket is lucky if the sum of the first three digits in its number equals to the sum of the last three ones). So, the way out is found — of course, tickets must be numbered in sequence, but the number of digits on a ticket may be changed. Say, if there were only two digits, there would have been ten lucky tickets (with numbers 00, 11, …, 99). Maybe under the circumstances the ratio of the lucky tickets to the common ones is greater? And what if we take four digits? A huge work has brought the longawaited result: in this case there will be 670 lucky tickets. But what to do if there are six or more digits?
Problem
So you are to save public transport of our city. Write a program that determines a number of lucky tickets for the given number of digits. By the way, there can’t be more than nine digits on one ticket.
*******InputConstraints*******
contains a positive even integer not greater than 9.
*******OutputConstraints*******
should contain a number of tickets such that the sum of the first half of digits is equal to the sum of the second half of digits.
*******IOTestCases*******
______________________________________________________
1045true
There are several airports in one country, and there are flights between some of them. One can fly from any airport to any other, probably with some changes. For any pair of airports there exists only one sequence of flights that connects them.
Two terrorists play a game. They make moves in turn. Each move consists of the following operations. A player mines an airport, chooses a flight and flies away together with his colleague. After the takeoff he actuates a radiocontrolled fuse. As a result the airport that the terrorists have just left is destroyed, and all the flights to and from this airport are no longer possible. After the aircraft lands the other player makes his move, and so forth. One loses if one cannot make a move.
Given an initial list of flights and the number of an airport where the terrorists are at the start of the game, write a program which would determine who wins if the terrorists play a perfect game (each chooses the best move).
*******InputConstraints*******
The first line contains two integers: n and k separated with a space. Here n is the number of airports (n ≤ 1000) and k is the number of an airport, which is the starting point of the game (1 ≤ k ≤ n). The next n − 1 lines contain pairs of integers separated with a space. These integers are numbers of airports, connected with a flight (all the flights are symmetric and are mentioned only once). There are at most 20 flights to each airport.
*******OutputConstraints*******
If the player who starts the game wins, the program should write “First player wins flying to airport L” where L is the number of an airport to which the players should fly first. If there are several such airports, the program should find one of them that has the minimal number. Otherwise the program should write “First player loses”.
*******IOTestCases*******
input  output 

4 3
3 2
3 1
1 4
 First player wins flying to airport 2

______________________________________________________
1046true
There is a polygon A_{1}A_{2}…A_{N} (the vertices
A_{i} are numbered in clockwise order). On each side A_{i}A_{i+1} an isosceles triangle A_{i}M_{i}A_{i+1} is built on the outer side of the polygon (M_{i}A_{i} = M_{i}A_{i+1}). The angle A_{i}M_{i}A_{i+1} is equal to α_{i}. Here we assume that A_{N+1} = A_{1}.
The set of angles α_{i} satisfies a condition that the sum of angles in any of its nonempty subsets is not aliquot to 360 degrees.
You are given N, coordinates of vertices M_{i} and angles α_{i} (measured in degrees). Write a program, which restores coordinates of the polygon vertices.
*******InputConstraints*******
The first line contains an integer N (3 ≤ N ≤ 50). The next N lines contain pairs of real numbers x_{i}, y_{i} which are coordinates of points M_{i} (–100 ≤ x_{i}, y_{i} ≤ 100). And the last N lines of the input consist of degree values of angles α_{i}. All real numbers in the input contain at most 2 digits after decimal point.
*******OutputConstraints*******
Output N lines with points coordinates, ith line should contain the coordinates of A_{i}. Coordinates must be accurate to 2 digits after decimal point. You may assume that solution always exists.
*******IOTestCases*******
input  output 

3
0 2
3 3
2 0
90
90
90
 1 1
1 3
3 1

______________________________________________________
1047true
There is a sequence of N + 2 elements a_{0}, a_{1}, …,
a_{N+1} (1 ≤ N ≤ 3000,
−2000 ≤ a_{i} ≤ 2000). It is known that
a_{i} = (a_{i−1} + a_{i+1})/2 − c_{i}
You are given a_{0}, a_{N+1}, c_{1}, …, c_{N}. Write a program which calculates a_{1}.
*******InputConstraints*******
The first line contains an integer N. The next two lines consist of numbers a_{0} and a_{N+1} each having two digits after decimal point, and the next N lines contain numbers c_{i} (also with two digits after decimal point), one number per line.
*******OutputConstraints*******
Output a_{1} in the same format as a_{0} and a_{N+1}.
*******IOTestCases*******
input  output 

1
50.50
25.50
10.15
 27.85

______________________________________________________
1048true
The creators of a new programming language D++ have found out that whatever limit for SuperLongInt type they make, sometimes programmers need to operate even larger numbers. A limit of 1000 digits is so small… You have to find the sum of two numbers with maximal size of 1 000 000 digits.
*******InputConstraints*******
The first line contains a single number N (1 ≤ N ≤ 1 000 000) — the length of the integers (in order to make their lengths equal, some leading zeroes can be added). It is followed by these integers written in columns. That is, the next N lines contain two digits each, divided by a space. Each of the two given integers is not less than 1, and the length of their sum does not exceed N.
*******OutputConstraints*******
Output exactly N digits in a single line representing the sum of these two integers.
*******IOTestCases*******
input  output 

4
0 4
4 2
6 8
3 7
 4750 
______________________________________________________
1049true
Ten mathematicians are flying on a balloon over the Pacific ocean. When they are crossing the equator they decide to celebrate this event and open a bottle of champagne. Unfortunately, the cork makes a hole in the balloon. Hydrogen is leaking out and the balloon is descending now. Soon it will fall into the ocean and all the balloonists will be eaten by hungry sharks.
But not everything is lost yet. One of the balloonists can sacrifice himself jumping out, so that his friends would live a little longer. Only one problem still exists: who is the one to get out. There is a fair way to solve this problem. First, each of them writes an integer a_{i} not less than 1 and not more than 10000. Then they calculate the magic number N that is the number of positive divisors of the product
a_{1}*a_{2}*…*a_{10}. For example, the number of positive integer divisors of 6 is 4 (they are 1,2,3,6). The hero (a mathematician who will be thrown out) is determined according to the last digit of N. Your task is to find this digit.
*******InputConstraints*******
Input contains ten integer numbers (each number is in separate line).
*******OutputConstraints*******
Output a single digit from 0 to 9 — the last digit of N.
*******IOTestCases*******
input  output 

1
2
6
1
3
1
1
1
1
1
 9

______________________________________________________
1050true
TeX is the leading typesetting system for mathematics, science, and
engineering and has been adopted as standard by the American Mathematical
Society. LaTeX was developed later by Leslie Lamport. It is based on TeX and
provides a set of higher level commands for production of complex documents. In
TeX or LaTeX, any text editor program may be used to enter and modify the input
text.
The source text contains the actual text as well as formatting commands
beginning with \. Commands are delimited by any nonalphabetic character.
One example of beautification by TeX is that it uses `` (two
leftsinglequotes) and '' (two rightsinglequotes) to delimit
quotations, rather than the mundane " (one double quote) which is provided by
most keyboards. Keyboards typically do not have an oriented doublequote,
but they do have a leftsinglequote (`) and rightsinglequote (').
TeX lets the user type two leftsinglequotes (``) to create a
leftdoublequote and two rightsinglequotes ('') to
create a rightdoublequote.
Now, you have a text only file containing
at most 250 lines at most 80 symbols each, as source or input, and you want to
use TeX to beautify it. Rather than doing everything by hand, as the first step
of automation you want to convert the quotes into the TeX format by using a
program. This program will convert the text with doublequotes (") into an
identical text except that double quotes have been replaced by the
twocharacter sequences required by TeX for delimiting quotations with
oriented doublequotes. The doublequote (") characters should be
replaced appropriately by proper double single quotes depending on whether it is
an opening or closing quotation mark. Question of nested quotations does not
arise. The first " must be replaced by ``, the next by '', the next by
``, the next by '', and so on. An opening
double quote must have its closing quote in the same paragraph. If a match is
not found in the same paragraph for an opening quote, this quote has to be
deleted. Paragraph ends in the source text are marked either by at least one
blank line, or a \par command or both. Your program must also be careful about
the \" command which is used to produce umlaut or dieresis (\"e
leads to ë). These are to be left untouched.
*******InputConstraints*******
Input will consist of several lines of text containing a number of double
quotes ("), as well as some TeX commands. End of input will be marked by an
\endinput command.
*******OutputConstraints*******
Output will be an exact replica of the input, except the double quotes are to
be modified according to the rules described above.
*******IOTestCases*******
input  output 

There is no "q in this sentence. \par
"Talk child," said the unicorn.
She s\"aid, "\thinspace `Enough!', he said."
\endinput
 There is no q in this sentence. \par
``Talk child,'' said the unicorn.
She s\"aid, ``\thinspace `Enough!', he said.''
\endinput

Hint
Doublequote (") has ASCII code 34,
leftsinglequote (`) has ASCII code 96,
rightsinglequote (') has ASCII code 39.
______________________________________________________
1051true
There is an infinite grid and an M × N rectangle of stones on it (1 ≤ M, N ≤ 10000). The stones are located in the knots of the grid.
A following game for a single player is being played. One stone can jump over another along a vertical or a horizontal line. A stone which had been overjumped is taken away. The purpose of the game is to minimize number of stones on a
grid.
Given a pair of numbers M and N separated with one space you are to write a program which should determine a minimal number of the stones left on the grid.
*******InputConstraints*******
Numbers M and N separated by space.
*******OutputConstraints*******
The minimal number of the stones left on the grid.
*******IOTestCases*******
______________________________________________________
1052true
A good hunter kills two rabbits with one shot. Of course, it can be easily done since for any two points we can always draw a line containing the both. But killing three or more rabbits in one shot is much more difficult task. To be the best hunter in the world one should be able to kill the maximal possible number of rabbits. Assume that rabbit is a point on the plane with integer x and y coordinates. Having a set of rabbits you are to find the largest number of rabbits that can be killed with single shot, i.e. maximum number of points lying exactly on the same line. No two rabbits sit at one point.
*******InputConstraints*******
An input contains an integer N (2 ≤ N ≤ 200) specifying the number of rabbits. Each of the next N lines in the input contains the x coordinate and the y coordinate (in this order) separated by a space (−1000 ≤ x, y ≤ 1000).
*******OutputConstraints*******
The output contains the maximal number of rabbits situated in one line.
*******IOTestCases*******
input  output 

6
7 122
8 139
9 156
10 173
11 190
100 1
 5

______________________________________________________
1053true
Father Carlo got the commission to make Pinocchio. Client expressed a wish to be unknown and he left material and insisted on finding Pinocchio's nose length as a result of performing the following algorithm:
 There's a set of N numbered blanks with integer lengths.
 If the set consists of only one blank, then it's length can be admitted as the length of Pinocchio's nose
 Let's choose some 2 blanks
 If lengths of the blanks coincide, then one of the blanks is eliminated from the set and algorithm goes back to point 2 to be repeated.
 If lengths of the blanks are different, then the piece of the long blank is sawed off and its length must be equal to the length of the other blank. Then the algorithm is repeated from point 2.
Example. There are 3 blanks in a set with lengths: 2, 3, 4. Then the change of the blank lengths can be shown in the following table. As a result Pinocchio will get the nose with length of 1.
Length of the first blank 
Length of the second blank 
Length of the third blank 
Comments 
2 
3 
4 
Initial blank lengths 
2 
1 
4 
Sawing off the second blank 
2 
1 
3 
Sawing off the third blank 
2 
1 
2 
Sawing off the third blank 
1 
1 
2 
Sawing off the first blank 
 
1 
2 
The first blank is eliminated 
 
1 
1 
Sawing off the third blank 
 
 
1 
The second blank is eliminated 
*******InputConstraints*******
The first line contains integer N (1 ≤ N ≤ 1000). The other N successive lines contain integers L_{1}, L_{2}, …, L_{N}.
1 ≤ L_{1}, L_{2}, …, L_{N} ≤ MaxLongInt.
*******OutputConstraints*******
Output should contain either one number (Pinocchio nose length), or the word IMPOSSIBLE (in upper case) if the nose length cannot be defined.
*******IOTestCases*******
______________________________________________________
1054true
Background
"Hanoi tower" puzzle is well known. There are 3 pegs with numbers: #1, #2 and #3. N disks of different diameters are set on the first peg in the following order: the lower disk is set, the larger diameter it has. Your aim is to move all disks onto the second peg using the peg #3 as an auxiliary one. Following the rules within a move it's allowed to replace only one uppermost disk. Besides it's forbidden to put the disk of the bigger diameter onto the disk of the smaller one.
Distribution of disks on the pegs during the game must be assigned as sequence D (element #i of the sequence is equal to the number of peg where the disk #i is placed on). For instance, game status after the third move is apparently determined by sequence D=(3, 3, 1) (the first and the second disks are set on the third peg and the third disk is on the peg #1).
Example. Let's assume that 3 disks are set on the peg #1. Then the movement of the disks can be depicted in the following table (disks are numbered in ascending order of diameters):
Point of move 
Peg #1 disks 
Peg #2 disks 
Peg #3 disks 
sequence D 
0 
1, 2, 3 
 
 
1, 1, 1 
1 
2, 3 
1 
 
2, 1, 1 
2 
3 
1 
2 
2, 3, 1 
3 
3 
 
1, 2 
3, 3, 1 
4 
 
3 
1, 2 
3, 3, 2 
5 
1 
3 
2 
1, 3, 2 
6 
1 
2, 3 
 
1, 2, 2 
7 
 
1, 2, 3 
 
2, 2, 2 
Problem
Your aim is either to determine (using arbitrary sequence D) the number of moves from the beginning of the game to the given position on condition of performing the optimal algorithm; or to print "−1" in the case of incorrect sequence declaration (i.e. the given position cannot be achieved performing the optimal algorithm).
Reference notes. Optimal algorithm can be specified with the following recursive procedure.
procedure Hanoi(N:integer; From, To_, Temp : integer);
Begin
if N>0 then
begin
Hanoi(N1, From, Temp, To_);
writeln (N, From, To_);
Hanoi(N1, Temp, To_, From)
end
End;
For example, to move 5 disks it's enough to call Hanoi(5,1,2,3)
Admonition. It is obvious that during the game process simultaneous setting of disks on all the pegs (#1, #2, #3) is never repeated, thus the answer will always be unequivocal.
*******InputConstraints*******
The first line of input contains integer N (1 ≤ N ≤ 31). The other N successive lines contain integers D_{1}, D_{2}, …, D_{N}.
1 ≤ D_{1}, D_{2}, …, D_{N} ≤ 3.
*******OutputConstraints*******
Output should contain either the number of moves, or −1.
*******IOTestCases*******
______________________________________________________
1055true
Background
As you have known MMM corporation lab researches the matter of haricot proportions in soup For every day. As we wrote in the previous problem (T) the ladle is placed down into the soup pan. But now we are not interested in the form and linear sizes of the ladle. This time the ladle holds exactly M haricot seeds of N got into the pan. All the seeds are of different size.
Experimenters calculate the quantity of possible methods to proportion M seeds in the pan. Requisite quantity of methods is calculated with the formula: C=N!/(M!·(N−M)!). The main feature of these experiments is the quantity of different prime divisors of number C.
Example. N=7, M=3. C=7!/(3!*4!)=5040/(6*24)=35=5*7. This example shows that the quantity of different prime divisors is 2.
Lest money would be spent for programmer, MMM corporation board decided to make necessary estimating during trial tour of quarterfinal world programming contest in Rybinsk.
Problem
Thus, your aim is to find the quantity of different prime divisors of number C.
*******InputConstraints*******
Input contains integers N and M.
You may assume that 1 ≤ N, M ≤ 50000.
*******OutputConstraints*******
Output should contain one integer.
*******IOTestCases*******
______________________________________________________
1056true
Background
Computer net is created by consecutive computer plugup to one that has already been connected to the net. Each new computer gets an ordinal number, but the protocol contains the number of its parent computer in the net. Thus, protocol consists of several numbers; the first of them is always 1, because the second computer can only be connected to the first one, the second number is 1 or 2 and so forth. The total quantity of numbers in the protocol is N − 1 (N is a total number of computers).
For instance, protocol 1, 1, 2, 2 corresponds to the following net:
The distance between the computers is the quantity of mutual connections (between each other) in chain. Thus, in example mentioned above the distance between computers #4 and #5 is 2, and between #3 and #5 is 3.
Definition. Let the center of the net be the computer which has a minimal distance to the most remote computer. In the shown example computers #1 and #2 are the centers of the net.
Problem
Your task is to find all the centers using the set protocol.
*******InputConstraints*******
The first line of input contains an integer N, the quantity of computers (2 ≤ N ≤ 10000). Successive N − 1 lines contain protocol.
*******OutputConstraints*******
Output should contain ordinal numbers of the determined net centers in ascending order.
*******IOTestCases*******
______________________________________________________
1057true
Create a code to determine the amount of integers, lying in the set [X;Y] and being a sum of exactly K different integer degrees of B.
Example. Let X=15, Y=20, K=2, B=2. By this example 3 numbers are the sum of exactly two integer degrees of number 2:
17 = 2^{4}+2^{0},
18 = 2^{4}+2^{1},
20 = 2^{4}+2^{2}.
*******InputConstraints*******
The first line of input contains integers X and Y, separated with a space (1 ≤ X ≤ Y ≤ 2^{31}−1). The next two lines contain integers K and B (1 ≤ K ≤ 20;
2 ≤ B ≤ 10).
*******OutputConstraints*******
Output should contain a single integer — the amount of integers, lying between X and Y, being a sum of exactly K different integer degrees of B.
*******IOTestCases*******
______________________________________________________
1058true
Fishburg confectionery factory produces convex polygonshaped chocolates. Little Boy and Karlsson bought one and wanted to break it into two fragments. The areas of the fragments must be equal. Create a code to find out the length of breakageline of a minimal length using the given chocolate form.
*******InputConstraints*******
The first line of input contains an integer N — the number of polygon vertices (4 ≤ N ≤ 50). The other N lines contain coordinates of the vertices in the counterclockwise order. Coordinates are real numbers from −100 to 100 and given with at most 3 digits after decimal point.
*******OutputConstraints*******
Output should contain the minimal length of breakageline with accuracy to 0.0001.
*******IOTestCases*******
input  output 

4
0 0
4 0
4 3
0 3
 3

______________________________________________________
1059true
Petr got an assignment to cipher out the value of polynomial P with calculator working in mode of reverse polish record. His calculator is able only to add and multiply numbers of any length (capacity). Input data — degree of the polynomial, argument x and coefficient values.
Help Petr to set correct and at the same time the shortest sequence of operands and signs of operations in the order of entering in calculator. Reference notes. Expression written in mode of reverse polish record consists of operands and signs of operations; the sign of operation is preceded by operands. The brackets in reverse polish record are eliminated. The algorithm to compute such an expression is the following:
 If the expression consists of only one operand, then the value of the operand is the value of the expression.
 Otherwise:
 seek for the first operation sign leftmost in the expression
 process the operation with those operands that stand to the left from this sign
 write the result instead of the sign and operands
 recalculate the ultimate expression using rules 12
 If rules 12 are unacceptable, then the expression hasn’t been properly written.
Example. Expression of reverse polish record “a b c d + * e  /” is the equivalence of ordinary expression “a / (b * (c + d) – e)”
*******InputConstraints*******
Input contains an integer N (1 ≤ N ≤ 1000). Here you assume that polynom is a_{0}x^{N}+
a_{1}x^{N−1} + … .
Instead of the coefficient a_{i} you may just write the number i.
*******OutputConstraints*******
Output should contain a sequence of minimal length corresponding to polynomial in reverse polish record. This record can include only signs of operations ('+', '*'), capital Latin letter X and unsigned integers that set the weights of coefficients of x degrees.
Each element (sign of operation, symbol X, weight of coefficient) should be written without initial space characters by one in a line.
*******IOTestCases*******
______________________________________________________
1060true
Flip game is played on a rectangular 4×4 field with
twosided pieces placed on each of its 16 squares. One side of each piece is white and the other one is black and each piece is lying either it's black or white side up. Each round
you flip 3 to 5 pieces, thus changing the color of their
upper side from black to white and vice versa. The pieces
to be flipped are chosen every round according to the
following rules:
 Choose any one of the 16 pieces.
 Flip the chosen piece and also all adjacent pieces
to the left, to the right, to the top, and to the bottom
of the chosen piece (if there are any).
Consider the following position as an example:
Here "b" denotes pieces lying their black side up and "w"
denotes pieces lying their white side up. If we choose to flip
the 1st piece from the 3rd row (this choice is shown at the picture),
then the field will become:
The goal of the game is to flip either all pieces white side up or
all pieces black side up. You are to write a program that
will search for the minimum number of rounds needed to
achieve this goal.
*******InputConstraints*******
The input consists of 4 lines with 4 characters "w" or "b" each that denote game field position.
*******OutputConstraints*******
Write to the output a single integer number — the minimum number of rounds needed to achieve the goal of the game from the given position. If the goal is initially achieved, then write 0. If it's impossible to achieve the goal, then write the word "Impossible" (without quotes).
*******IOTestCases*******
input  output 

bwbw
wwww
bbwb
bwwb
 Impossible

______________________________________________________
1061true
Data blocks being read by DBMS from the hard drive
are stored in the main memory
in a fixed number of preallocated buffers.
Each buffer can hold one data block.
Each buffer can be either free
(does not contain any useful information) or occupied by some data.
When DBMS is going to read data block from the hard drive it has
to decide which buffer to use for data storing.
If there
are any free buffers, then one of them is used for that purpose.
If there are no free buffers, then one of the occupied buffers
has to be flushed to become free, unless it was locked by
some part of DBMS.
The choice of the buffer to flush is critical to DBMS performance.
A lot of different algorithms were developed, LRU (Least Recently
Used) algorithm being the
one used most often. However, your DBMS is
going to implement the Advanced Buffer Management algorithm
which takes advantage
of the fact that maximal
performance is achieved when
a number of consecutive data blocks from the hard drive are read
into consecutive memory buffers.
Buffers are numbered from 1 to N, where N
(1 ≤ N ≤ 100000)
is a total number of buffers.
Each buffer can be in any one of the following states:
free, occupied or locked.
Each occupied
buffer is assigned an integer number from 1 to 9 –
the worthiness of
the currently stored information in that
buffer. The worthiness of
free buffers is considered to be zero. Locked buffers cannot be
neither used nor flushed and their worthiness is undefined.
Having received the request to read K
(1 ≤ K ≤ 10000)
data blocks from the hard drive, Buffer Manager has to choose
K consecutive nonlocked
buffers numbered from L to
L+K1 that have minimal possible sum of their
worthiness, or to report that it is impossible to find K
consecutive nonlocked buffers. The latter can also happen
if total number of buffers is less than K.
Your task is to write a program that models the processing
of one request to Buffer Manager using the above algorithm.
*******InputConstraints*******
The first line of the input contains two integers,
N and K, separated by a space.
Starting from the second line there is a description of a buffers' state.
The state of each buffer is represented by a single character:
 0 – when the corresponding buffer is free.
 1 – when the corresponding buffer is occupied
and has worthiness of 1.
 2 – when the corresponding buffer is occupied
and has worthiness of 2.
 ...
 9 – when the corresponding buffer is occupied
and has worthiness of 9.
 * – when the corresponding buffer is locked.
Those characters are situated on the consecutive lines grouped by 80
characters per line without any spaces. Thus, each line starting
from the second one contains exactly 80 characters with a possible exception
for the last line.
*******OutputConstraints*******
Write to the output the single integer number L.
This number gives the buffer number where first of the
K
blocks from the hard drive shall be read to ensure the minimal
possible total worthiness of the blocks that
have to be flushed.
If there are more than one such value for L,
then write the smallest one.
Write to the output a single number 0 if it's impossible to find
K consecutive nonlocked buffers.
*******IOTestCases*******
input 

100 53
2165745216091853477755800393859785807207523169954341**7363*9*94664808*4777717089
09825185827659480548

output 

0

______________________________________________________
1062true
Triathlon is an athletic contest consisting of three consecutive sections that
should be completed as fast as possible as a whole.
The first section is swimming, the second section is riding bicycle
and the third one is running.
The speed of each contestant in all three sections is known. The judge
can choose the length of each section arbitrarily provided that no section
has zero length.
As a result sometimes she could choose their lengths in such a way
that some particular contestant would win the competition.
*******InputConstraints*******
The first line of the input contains integer number N
(1 ≤ N ≤ 100),
denoting the number of contestants.
Then N lines follow, each line contains three integers
V_{i}, U_{i} and W_{i}
(1 ≤ V_{i}, U_{i},
W_{i} ≤ 10000),
separated by spaces, denoting the speed of i^{th}
contestant in each section.
*******OutputConstraints*******
For every contestant write to the output one line, that contains
word "Yes" if the judge could choose the lengths of the sections in such a way
that this particular contestant would win (i.e. she is the only one who
would come first), or word "No" if this is impossible.
*******IOTestCases*******
input  output 

9
10 2 6
10 7 3
5 6 7
3 2 7
6 2 6
3 5 7
8 4 6
10 4 2
1 8 7
 Yes
Yes
Yes
No
No
No
Yes
No
Yes

______________________________________________________
1063true
Background
Dominoes,
game played with small, rectangular blocks of wood or other material,
each identified by a number of dots, or pips, on its face. The blocks
usually are called bones, dominoes, or pieces and sometimes men, stones,
or even cards.
The face of each piece is divided, by a line or ridge, into two squares,
each of which is marked as would be a pair of dice...
The principle in nearly all modern dominoes games is to match one end
of a piece to another that is identically or reciprocally numbered.
Problem
Consider an arbitrary set of domino pieces where each piece is marked
with two digits from 1 to 6. Some sets can be completely laid
out in a row matching one end of a piece to another that is identically
numbered, while others cannot. For example, the set consisting of 5 pieces:
(1, 5), (1, 6), (5, 5) and (2, 4) twice, cannot
be laid out in a row. However, if we add (2, 5) piece to the above
set we could lay out the resulting set in the following row:
However, we are interested in a row having the smallest sum of digits on
its pieces. In our example, instead of the piece (2, 5) with a sum of 7,
we could add two pieces (1, 2) with a total sum of 6 to
lay out the following row:
Your task is to write a program that for a given domino set will find an additional
(possibly empty) set with the smallest possible sum of digits, so that a row could be
laid out with both sets combined.
*******InputConstraints*******
The first line contains a single integer N
(2 ≤ N ≤ 100) representing the total
number of pieces in the domino set. The following N lines describe
pieces. Each piece is represented on a separate line in a form of two digits
from 1 to 6 separated by a space. The digits of a piece can be written in
any order.
*******OutputConstraints*******
On the first line write the smallest sum of digits of the additional set or 0 if
that set is empty. On the second line write the total number of pieces in the additional set or 0 if that set is empty. Then write the pieces of the additional set in the same format as in input.
If there are a number of additional sets with the same smallest
sum of digits exist then write any one of them.
*******IOTestCases*******
input  output 

6
6 1
1 5
5 5
5 2
2 4
4 2
 0
0

5
1 5
6 1
5 5
2 4
2 4
 6
2
1 2
1 2

______________________________________________________
1064true
The program fragment below performs binary search of an integer
number in an array that is sorted in a nondescending order:
Pascal 
C 
const
MAXN = 10000;
var
A: array[0..MAXN1] of integer;
N: integer;
procedure BinarySearch(x: integer);
var
p, q, i, L: integer;
begin
p := 0; { Left border of the search }
q := N1; { Right border of the search }
L := 0; { Comparison counter }
while p <= q do begin
i := (p + q) div 2;
inc(L);
if A[i] = x then begin
writeln('Found item i = ', i,
' in L = ', L, ' comparisons');
exit
end;
if x < A[i] then
q := i  1
else
p := i + 1
end
end;

#define MAXN 10000
int A[MAXN];
int N;
void BinarySearch(int x)
{
int p, q, i, L;
p = 0; /* Left border of the search */
q = N1; /* Right border of the search */
L = 0; /* Comparison counter */
while (p <= q) {
i = (p + q) / 2;
++L;
if (A[i] == x) {
printf("Found item i = %d"
" in L = %d comparisons", i, L);
return;
}
if (x < A[i])
q = i  1;
else
p = i + 1;
}
}

Before BinarySearch was called, N was set to some
integer number from 1 to 10000 inclusive and
array A was filled with a nondescending integer sequence.
It is known that the procedure has terminated with the message
"Found item i = XXX in L = XXX comparisons" with some
known values of i and L.
Your task is to write a program that finds all possible values of
N that could lead to such message. However, the number of
possible values of N can be quite big. Thus, you are asked to group all
consecutive Ns into intervals and write down only first and
last value in each interval.
*******InputConstraints*******
The input consists of a single line with two integers i
and L (0 ≤ i < 10000 and
1 ≤ L ≤ 14), separated by a space.
*******OutputConstraints*******
On the first line of the output write the single
integer number K
representing the total number of intervals for possible values of N.
Then K lines shall follow listing those intervals in an ascending order.
Each line shall contain
two integers A_{i} and B_{i}
(A_{i} ≤ B_{i})
separated by a space, representing first and last value of the interval.
If there are no possible values of N exist, then the output
shall contain the single 0.
*******IOTestCases*******
input  output 

10 3
 4
12 12
17 18
29 30
87 94

______________________________________________________
1065true
Lilliputian frontier is a convex polygon with nonzero area.
The vertices of this polygon are guard towers, which are
connected by straight lines.
This frontier is too long and expensive for Lilliputia to maintain;
therefore the Lilliputian government has decided to revise it to make it shorter.
However, they don't want to build new guard towers, but to use existing
ones as a part of a new frontier.
Each day frontier guards inspect the frontier. They go
from one guard tower to the next one, traversing the frontier
clockwise. Guard towers are numbered from 1 to N according
to this inspection order. Frontier revision should not change this
way of inspection and the area of Lilliputia shall remain nonzero.
For example, the frontier that is shown on the picture
(axes are in kilometer scale) is traversed by
1  2  3  4  5  1
route, which is 57.89 kilometers long.
To make the frontier as short as possible
Lilliputia should revise it so that the frontier is traversed by
2  3  4  2 route, thus reducing
its length to 27.31 kilometers.
However, Lilliputia has a number of historical monuments which
are its major pride. The historical monuments shall be kept
inside Lilliputia at any cost and they should not end up on the
frontier. So, the task is to design the shortest frontier
that will preserve all historical monuments inside Lilliputia.
On the sample picture two historical monuments marked "A" and "B"
are shown. The desire to keep them inside Lilliputia will lead
to the shortest frontier with a traverse path
1  2  3  4  1
having 51.78 kilometers in length.
*******InputConstraints*******
The first line of the input contains two integers N
and M, separated by a space. N
(3 ≤ N ≤ 50) is a total number
of guard towers on the Lilliputian frontier. M
(0 ≤ M ≤ 1000) is a total number
of historical monuments that are situated inside Lilliputia.
Next N lines contain guard towers' coordinates
in a clockwise order followed by M lines that
contain historical monuments' coordinates. All coordinates
are represented as two integers (for X and Y
correspondingly) separated by a space. Coordinates are
given in a kilometer scale and each coordinate
does not exceed 10000 by an absolute value. All guard towers
are located at distinct points.
*******OutputConstraints*******
Write to the output a single real number – the minimal
possible length of the Lilliputian frontier (in kilometers)
accurate to two digits to the right of the decimal point.
*******IOTestCases*******
input  output 

5 0
8 9
0 7
8 7
8 1
8 9
 27.31

______________________________________________________
1066true
The New Year garland consists of N lamps attached to a common wire
that hangs down on the ends to which outermost lamps are affixed.
The wire sags under the weight of lamp in a particular way: each lamp is hanging
at the height that is 1 millimeter lower than the average height of the
two adjacent lamps.
The leftmost lamp is hanging at the height of A millimeters above the
ground. You have to determine the lowest height B of the rightmost lamp
so that no lamp in the garland lies on the ground
though some of them may touch the ground.
You shall neglect the lamp's size in this problem. By numbering the lamps with
integers from 1 to
N and denoting the
i^{th} lamp
height in millimeters as
H_{i} we derive the following
equations:
 H_{1} = A
 H_{i} =
(H_{i−1} + H_{i+1})/2 − 1,
for all 1 < i < N
 H_{N} = B
 H_{i} ≥ 0, for all 1 ≤ i ≤ N
The sample garland with 8 lamps that is shown on the picture
has A = 15 and B = 9.75.
*******InputConstraints*******
The input consists of a single line with two numbers N and A separated by a space.
N (3 ≤ N ≤ 1000) is an integer representing the number of lamps in the garland, A (10 ≤ A ≤ 1000) is a real
number representing the height of the leftmost lamp above the ground in millimeters.
*******OutputConstraints*******
Write to the output the single real number B
accurate to two digits to the right of the decimal point
representing the lowest possible height of the rightmost lamp.
*******IOTestCases*******
input  output 

692 532.81
 446113.34

______________________________________________________
1067true
Hacker Bill has accidentally lost all the information from his
workstation's hard drive and he has no backup copies of its contents.
He does not regret for the loss of the files themselves, but
for the very nice and convenient directory structure that he had
created and cherished during years of work.
Fortunately, Bill has several copies of directory listings
from his hard drive. Using those listings he was able to recover
full paths (like "WINNT\SYSTEM32\CERTSRV\CERTCO~1\X86") for some directories.
He put all of them in a file by writing each path he has found
on a separate line.
Your task is to write a program that will help Bill to restore
his state of the art directory structure by providing nicely formatted
directory tree.
*******InputConstraints*******
The first line of the input contains single integer number
N (1 ≤ N ≤ 500)
that denotes a total number of distinct directory paths.
Then N lines with directory paths follow.
Each directory path occupies a single line and does not
contain any spaces, including leading or trailing ones.
No path exceeds 80 characters.
Each path is listed once and consists of a number of
directory names separated by a back slash
("\").
Each directory name consists of 1 to 8 uppercase letters,
numbers, or the special characters from the following
list: exclamation mark, number sign, dollar sign, percent sign,
ampersand, apostrophe, opening and closing parenthesis,
hyphen sign, commercial at, circumflex accent, underscore,
grave accent, opening and closing curly bracket, and tilde
("!#$%&'()@^_`{}~").
*******OutputConstraints*******
Write to the output the formatted directory tree. Each
directory name shall be listed on its own line preceded by a number
of spaces that indicate its depth in the directory hierarchy. The
subdirectories shall be listed in lexicographic order immediately
after their parent directories preceded by one more space than their
parent directory. Top level directories shall have no spaces printed
before their names and shall be listed in lexicographic order.
See sample below for clarification of the output format.
*******IOTestCases*******
input  output 

7
WINNT\SYSTEM32\CONFIG
GAMES
WINNT\DRIVERS
HOME
WIN\SOFT
GAMES\DRIVERS
WINNT\SYSTEM32\CERTSRV\CERTCO~1\X86
 GAMES
DRIVERS
HOME
WIN
SOFT
WINNT
DRIVERS
SYSTEM32
CERTSRV
CERTCO~1
X86
CONFIG

______________________________________________________
1068true
Your task is to find the sum of all integer numbers
lying between 1 and N inclusive.
*******InputConstraints*******
The input consists of a single integer N that is
not greater than 10000 by it's absolute value.
*******OutputConstraints*******
Write a single integer number that is the sum of all
integer numbers lying between 1 and N inclusive.
*******IOTestCases*******
______________________________________________________
1069true
A tree (i.e. a connected graph without cycles) with vertices is given (N ≥ 2). Vertices of the tree are numbered by the integers 1,…,N. A Prufer code for the tree is built as follows: a leaf (a vertex that is incident to the only edge) with a minimal number is taken. Then this vertex and the incident edge are removed from the graph, and the number of the vertex that was adjacent to the leaf is written down. In the obtained graph once again a leaf with a minimal number is taken, removed and this procedure is repeated until the only vertex is left. It is clear that the only vertex left is the vertex with the number N. The written down set of integers (N−1 numbers, each in a range from 1 to N) is called a Prufer code of the graph.
Your task is, given a Prufer code, to reconstruct a tree, i.e. to find out the adjacency lists for every vertex in the graph.
You may assume that 2 ≤ N ≤ 7500
*******InputConstraints*******
A set of numbers corresponding to a Prufer code of some tree. The numbers are separated with a spaces and/or line breaks.
*******OutputConstraints*******
Adjacency lists for each vertex. Format: a vertex number, colon, numbers of adjacent vertices separated with a space. The vertices inside lists and lists itself should be sorted by vertex number in an ascending order (look at sample output).
*******IOTestCases*******
input  output 

2 1 6 2 6
 1: 4 6
2: 3 5 6
3: 2
4: 1
5: 2
6: 1 2

______________________________________________________
1070true
Soon the USU team will go to Vancouver to participate in the final of the ACM International Collegiate Programming Contest. They will be to take four different planes (three changes on the way)!
By the way, our team plans to return from Vancouver, so the twoway tickets are bought. The departure time (local time of the airport of departure) and the time of the arrival (local time of the destination airport) are printed on the tickets.
For example, the departure at 15.42 and the arrival at 16.23, and a return flight departs at 08.10 and arrives at 17.51.
Your task is to help to our team to find out how much does the time of the first airport differs from the one of the second. It is known that time in different airports differs by an integer amount of hours. The time of flights there and back may differ from each other not more than by 10 minutes.
The duration of a flight doesn't exceed 6 hours. The difference between airport local times is not greater than 5 hours.
*******InputConstraints*******
There are two lines, each of them contains two numbers. The first line consists of the departure time and the arrival time of the flight there, the second one — the departure and the arrival times of the back flight. Numbers in the lines are separated with a space, an amount of minutes is separated from an amount of hours with a point.
*******OutputConstraints*******
Your program should write a nonnegative integer (without extra zeroes) that corresponds to the difference in time between the two airports.
*******IOTestCases*******
input  output 

23.42 00.39
08.10 17.11  4 
______________________________________________________
1071true
Nikifor has a number x. He doesn't need it. He needs a number y. Nikifor tries to obtain the required number by erasing some digits from x. But he is not lucky in the meanwhile. May be he is to choose an appropriate number system?
Write a program that reads numbers x and y, and determines a minimal radix of a number system that it is possible to obtain in it the number y from x by erasing some digits. If it is impossible, your program should write to an output a message "No solution".
*******InputConstraints*******
The only line contains integers x and y (1 ≤ y < x ≤ 1 000 000), separated with a space.
*******OutputConstraints*******
Output either the message "No solution", if there is no appropriate number system, or an integer, not less than 2, that is an answer in the problem.
*******IOTestCases*******
______________________________________________________
1072true
There is a TCP/IP net of several computers. It means that:
 Each computer has one or more net interfaces.
 Each interface is identified by its IPaddress and a subnet mask — these are two fourbyte numbers with a point after each byte. A subnet mask has a binary representation as follows: there are k 1bits, then — m 0bits, k+m=8*4=32 (e.g., 212.220.35.77 — is an IPaddress and 255.255.255.128 — is a subnet mask).
 Two computers belong to the same subnet, if and only if (IP_{1} AND NetMask_{1}) = (IP_{2} AND NetMask_{2}), where IP_{i} and NetMask_{i } — are an IPaddress and subnet mask of ith computer, AND — is bitwise.
 A packet is transmitted between two computers of one subnet directly.
 If two computers belong to different subnets, a packet is to be transmitted via some other computers. The packet can pass from one subnet to another only on computer that has both subnets interfaces.
Your task is to find the shortest way of a packet between two given computers.
*******InputConstraints*******
The first line contains a number N — an amount of computers in the net, then go N sections, describing interfaces of each computer. There is a number K in the first line of a section — that is an amount of interfaces of the computer, then go K lines — descriptions of the interfaces, i.e. its IPaddress and a subnet mask. The last line of an input contains two integers — the numbers of the computers that you are to find a way between them.
You may assume that 2 ≤ N ≤ 90 and K ≤ 5.
*******OutputConstraints*******
The word “Yes” if the route exists, then in the next line the computer numbers passed by the packet, separated with a space. The word “No” otherwise.
*******IOTestCases*******
input  output 

6
2
10.0.0.1 255.0.0.0
192.168.0.1 255.255.255.0
1
10.0.0.2 255.0.0.0
3
192.168.0.2 255.255.255.0
212.220.31.1 255.255.255.0
212.220.35.1 255.255.255.0
1
212.220.31.2 255.255.255.0
2
212.220.35.2 255.255.255.0
195.38.54.65 255.255.255.224
1
195.38.54.94 255.255.255.224
1 6
 Yes
1 3 5 6

______________________________________________________
1073true
There live square people in a square country. Everything in this country is square also. Thus, the Square Parliament has passed a law about a land. According to the law each citizen of the country has a right to buy land. A land is sold in squares, surely. Moreover, a length of a square side must be a positive integer amount of meters. Buying a square of land with a side a one pays a^{2} quadrics (a local currency) and gets a square certificate of a landowner.
One citizen of the country has decided to invest all of his N quadrics into the land. He can, surely, do it, buying square pieces 1 × 1 meters. At the same time the citizen has requested to minimize an amount of pieces he buys: "It will be easier for me to pay taxes," — he has said. He has bought the land successfully.
Your task is to find out a number of certificates he has gotten.
*******InputConstraints*******
The only line contains a positive integer N ≤ 60 000 , that is a number of quadrics that the citizen has invested.
*******OutputConstraints*******
The only line contains a number of certificates that he has gotten.
*******IOTestCases*******
______________________________________________________
1074true
There are no long stories here, no long introductions and no complicated settings. All you need is to read from an input a real number in a format that is specified below, and to write it to an output in another format that is described below as well.
Here a syntactical description of the used notions follows.
<digit> ::= 0123456789
<unsigned integer number> ::= <digit><digit><unsigned integer number>
<sign> ::= +
<integer number> ::= <unsigned integer number><sign><unsigned integer number>
<exponent symbol> ::= eE
<exponent> ::= <exponent symbol><integer number>
<simple unsigned real number> ::= <unsigned integer number>.<unsigned integer number><unsigned integer number>.<unsigned integer number>
<simple real number> ::= <simple unsigned real number><sign><simple unsigned real number>
<real number> ::= <simple real number><simple real number><exponent>
*******InputConstraints*******
consists of one or several pairs of lines. The first line of a pair contains an arbitrary set of symbols S. A length of the string S doesn't exceed 100 symbols. The second line of a pair contains a integer number N (0 ≤ N ≤ 100). An input is ended with the pair of lines, the first one of them contains the only symbol "#".
*******OutputConstraints*******
For each pair of lines your program should write to an output a message: "Not a floating point number", if the string
S is not a correct <real number> according to the given above specification. If
S represents a correct <real number>, your program should write to an output this number formatted as a <simple real number> with N symbols after a decimal point. While forming the result you ought to note:
 An integral part of a number should be nonempty.
 There shouldn't be leading zeroes in a nonzero integral part of a number. A zero integral part of a number should consist of an only zero.
 A fractional part of a number should contain exactly N symbols.
 There shouldn't be a sign "+" before a positive number.
 You shouldn't round off a number.
It is guaranteed that a length of a result will not exceed 200 symbols.
*******IOTestCases*******
input  output 

10.23
0
.04
1
0.051e0
1
1.1e30
10
1.1E30
1
2468097632.1358642324268913e2
20
e23
3
1 e3
1
#  10
0.0
0.0
1100000000000000000000000000000.0000000000
0.0
24680976.32135864232426891300
Not a floating point number
Not a floating point number 
______________________________________________________
1075true
There are three points in a 3dimensional space: A, B and C. All the coordinates of the points are integer numbers with absolute values not greater than 1000. A solid ball with a center in the point C is firmly fixed. A radius of the ball is R, a positive integer number. Distances from the point C to the points A and B are strictly greater than R.
It is necessary to stretch a thread of minimal length between points A and B. Surely, the thread should be outside of the ball.
You are to find out a length of the thread.
*******InputConstraints*******
The first three lines contain coordinates of the points A, B and C respectively. The fourth one contains a radius R of the ball.
*******OutputConstraints*******
should contain a minimal length of the thread to within 2 symbols after a decimal point. You should output answer with two or more digits.
*******IOTestCases*******
input  output 

0 0 12
12 0 0
10 0 10
10
 19.71

______________________________________________________
1076true
You were just hired as CEO of the local junkyard.One of your jobs is dealing with the incoming trash and sorting it for recycling.The trash comes every day in N containers and each of these containers contains certain amount of each of the N types of trash. Given the amount of trash in the containers find the optimal way to sort the trash. Sorting the trash means putting every type of trash in separate container. Each of the given containers has infinite capacity. The effort for moving one unit of trash
from container i to j is 1 if i ≠ j otherwise it is 0.You are to minimize the total effort.
*******InputConstraints*******
The first line contains the number N (1 ≤ N ≤ 150), the rest of the input contains the descriptions of the containers.The (1 + i)th line contains the description of the ith container the jth amount (0 ≤ amount ≤ 100) on this line denotes the amount of the jth type of trash in the ith container.
*******OutputConstraints*******
You should write the minimal effort that is required for sorting the trash.
*******IOTestCases*******
input  output 

4
62 41 86 94
73 58 11 12
69 93 89 88
81 40 69 13
 650 
______________________________________________________
1077true
There are
N cities numbered from 1 to
N (1 ≤
N ≤ 200)
and
M twoway roads connect them. There are at most one road between two cities. In summer holiday, members of DSAP Group want to make some traveling tours. Each tour is a route passes
K different cities (
K > 2)
T_{1},
T_{2}, …,
T_{K}
and return to
T_{1}. Your task is to help them make
T tours such that:
 Each of these T tours has at least a road that does not belong to (T−1) other tours.
 T is maximum.
*******InputConstraints*******
The first line of input contains N and M separated with white spaces. Then follow by M lines, each has two number H and T which means there is a road connect city H and city T.
*******OutputConstraints*******
You must output an integer number T — the maximum number of tours. If T > 0, then T lines followed, each describe a tour. The first number of each line is K — the amount of different cities in the tour, then K numbers which represent K cities in the tour.
If there are more than one solution, you can output any of them.
*******IOTestCases*******
input  output 

5 7
1 2
1 3
1 4
2 4
2 3
3 4
5 4
 3
3 1 2 4
3 1 4 3
4 1 2 3 4

______________________________________________________
1078true
A number of segments are lying on a line. Every segment is given with the coordinates of its endpoints. Segments are numbered from 1 to N (0 < N < 500). We assume, that one segment is inside another, if the two segments are different, the first one is fully contained in the second one, and their endpoints do not coincide. Write a program, which finds the numbers of the segments in the longest sequence of segments which are contained in. In the sequence, every segment except the last is inside the next segment in the sequence.
*******InputConstraints*******
The first line contains one integer N. Next, there are N lines, with two integers on every line, which are the coordinates of the left and the right endpoints of the corresponding segment. These coordinates
are integers in the interval [–10000, 10000]. We assume that, the given segments are numbered according to their place in the input.
*******OutputConstraints*******
The first line must contain one integer, equal to the number of segments in the found sequence. The following line must contain the numbers of the segments in this sequence. These numbers must be outputted, in the order in which the segments' lengths increase, starting from the smallest.
If there are more than one output sequences, write any of them.
*******IOTestCases*******
input  output 

4
2 2
1 1
3 3
4 5
 3
2 1 3

______________________________________________________
1079true
Consider the sequence of numbers
a_{i},
i = 0, 1, 2, …, which satisfies the following requirements:
 a_{0} = 0
 a_{1} = 1
 a_{2i} = a_{i}
 a_{2i+1} = a_{i} + a_{i+1}
for every
i = 1, 2, 3, … .
Write a program which for a given value of n finds
the largest number among the numbers a_{0}, a_{1}, …, a_{n}.
*******InputConstraints*******
You are given several test cases (not more than 10). Each test case is a line containing an integer n (1 ≤ n ≤ 99 999).
The last line of input contains 0.
*******OutputConstraints*******
For every n in the input write the corresponding maximum value found.
*******IOTestCases*******
______________________________________________________
1080true
We consider a geographical map with N countries numbered from 1 to N (0 < N < 99). For every country we know the numbers of other countries which are connected with its border. From every country we can reach to any other one, eventually crossing some borders. Write a program which determines whether it is possible to color the map only in two colors — red and blue in such a way that if two countries are connected their colors are different. The color of the first country is red. Your program must output one possible coloring for the other countries, or show, that such coloring is impossible.
*******InputConstraints*******
On the first line is written the number N. On the following N lines, the ith line contains the countries to which the ith country is connected. Every integer on this line is bigger than i, except the last one which is 0 and marks that no more countries are listed for country i. If a line contains 0, that means that the ith country is not connected to any other country, which number is larger than i.
*******OutputConstraints*******
The output contains exactly one line. If the coloring is
possible, this line must contain a list of zeros and ones,
without any separators between them. The ith digit
in this sequence is the color of the ith country. 0 corresponds to red color, and one — to blue color. If a coloring is not possible, output the integer −1.
*******IOTestCases*******
input  output 

3
2 0
3 0
0
 010

______________________________________________________
1081true
Consider all the sequences with length (0 < N < 44), containing only the elements 0 and 1, and no two ones are adjacent (110 is not a valid sequence of length 3, 0101 is a valid sequence of length 4). Write a program which finds the sequence, which is on Kth place (0 < K < 10^{9}) in the lexicographically sorted in ascending order collection of the described sequences.
*******InputConstraints*******
The first line of input contains two positive integers N and K.
*******OutputConstraints*******
Write the found sequence or −1 if the number K is larger then the number of valid sequences.
*******IOTestCases*******
______________________________________________________
1082true
Once upon a time there lived a tsar that has a daughter — Beautiful Vasilisa. There
were many of the young men that wanted to marry her but she repelled all suitors. The
tsar was tired of her jigs, he got angry and issued an order: "The first who solves my
puzzle, will marry Vasilisa!"
Ivanushka decided to try his fortune. He came to the tsar and the tsar told him:
"This is a program for you. Input N numbers and the program will tell you who you
should marry. I give you a day to think."
Ivanuska looked at the program and got upset: there were unknown letters,
omnifarious symbols. The time passed. Ivanushka has thought out nothing.
The program was as follows.
The C program  The Pascal program 
#include <stdio.h>
long c;
long A[N];
long P(long l, long r)
{
long x=A[l],
i=l1,
j=r+1,
t;
while(1)
{
do{j; ++c;}
while(A[j]>x);
do{++i; ++c;}
while(A[i]<x);
if(i<j)
{
t=A[i];
A[i]=A[j];
A[j]=t;
}
else return j;
}
}
void Q(long l, long r)
{
long n;
if(l<r)
{
n=P(l,r);
Q(l,n);
Q(n+1,r);
}
}
int main(void)
{
c=0;
for(long i=0; i<N; ++i)
scanf("%ld", &A[i]);
Q(0,N1);
if(c==(N*N+3*N4)/2)
printf
("Beutiful Vasilisa");
else printf
("Immortal Koshcei");
return 0;
}

var A:array [1..N] of
longint;
c:longint;
i:integer;
function
P(l,r:longint):longint;
var i,j,t,x:longint;
begin
x:=A[l]; i:=l1; j:=r+1;
while true do
begin
repeat dec(j);inc(c)
until A[j]<=x;
repeat inc(i);inc(c)
until A[i]>=x;
if i<j then
begin
t:=A[i];
A[i]:=A[j];
A[j]:=t
end
else
begin P:=j; exit end
end
end;
procedure Q(l,r:longint);
var n:longint;
begin
if l<r then
begin
n:=P(l,r);
Q(l,n);
Q(n+1,r)
end
end;
begin
c:=0;
for i:=1 to N do
read(A[i]);
Q(1,N);
if c=(N*N+3*N4) div 2
then
writeln
('Beutiful Vasilisa')
else writeln
('Immortal Koshcei');
end.

Now you know this program. You may try to help Ivanushka.
*******InputConstraints*******
The first line of an input contains a positive number N ≤ 1000.
*******OutputConstraints*******
You are to write to an output N numbers in one line. The tsar's program given
those numbers should output a message "Beautiful Vasilisa" The numbers should be
separated with a space. If several variants are possible choose any you like.
*******IOTestCases*******
______________________________________________________
1083true
Definition 1. n!!…! = n(n−k)(n−2k)…(n mod k), if k doesn’t divide n;
n!!…! = n(n−k)(n−2k)…k, if k divides n (There are k marks ! in the both cases).
Definition 2.
X mod Y — a remainder after division of X by Y.
For example, 10 mod 3 = 1; 3! = 3·2·1; 10!!! = 10·7·4·1.
Given numbers n and k we have calculated a value of the expression in the first definition. Can you do it as well?
*******InputConstraints*******
contains the only line: one integer n, 1 ≤ n ≤ 10, then exactly one space, then k exclamation marks, 1 ≤ k ≤ 20.
*******OutputConstraints*******
contains one number — n!!…! (there are k marks ! here).
*******IOTestCases*******
______________________________________________________
1084true
Someone has let a goat in a square kitchengarden and had bound it to a stake. The stake is driven into the ground in the very midst of the square. The goat is hungry as a hunter and very voracious, and eats everything that can be reached without leaving the square and tearing off the rope. What area of the kitchengarden will be ate round?
*******InputConstraints*******
contains lengths of the garden sides and a cord length in meters (positive integers not exceeding 100, located in one line and separated with a space).
*******OutputConstraints*******
should contain an area of the kitchengarden (in square meters to within 3 symbols after a decimal point), ate round by the goat.
*******IOTestCases*******
______________________________________________________
1085true
K friends has decided to meet in order to celebrate their victory at the programming contest. Unfortunately, because of the tickets rise in price there is a problem: all of them live in different parts of the city, and they are to choose a place of meeting so that they wouldn't pay too much for the tickets. You are to help them make the best choice.
All stops are enumerated with integers 1, …, N inclusive. There are M tram routes in the city (the friends take only trams and do not go on foot from stop to stop). For each route numbers of its stops are known. For each friend we know an amount of money he has and whether he has a month tram ticket. A ticket price equals 4 rubles.
You are to find out a stop number, such that all of the friends might come there and the sum of money they spend for their tramps would be minimal. Naturally, they may change routes (it means that each one may make changes on his way to the required stop). Note, that changing the route one has to pay for a new ticket: the friends are honest people — they do always pay for tickets. Everyone pays for a ticket from his own money. No one is to leave money for the return tickets.
*******InputConstraints*******
The first line contains two integers N and M; 1 ≤ N, M ≤ 100 (N is a number of stops, M is a number of routes). The next M lines define the routes in the following sort: there is an integer L in the beginning of a line — that is an amount of stops of the corresponding route (1 ≤ L ≤ 100). Then L integers defining stops numbers of the route follow. The numbers are separated with a space. A route is defined by its stops along the line in one direction.
The next line contains an integer K (1 ≤ K ≤ 100), that is an amount of friends. The next K lines contain information about each of them (one line for one person): there is a positive integer in the beginning of a line that is an amount of money (in rubles) the person has, then a number of a stop that he goes there from his home on foot, then 0 (if this person has no month ticket) or 1 (if he has). The numbers in a line are separated with a space. No one of the friends has more than 1000 rubles.
*******OutputConstraints*******
Output a number of a stop that is a meeting
point (if there are several numbers choose the minimal one) and a total sum of money (in rubles) that the friends has paid for their trips to the appointed place. The numbers should be separated with a space. If the friends won't be able to meet at one stop, output the only number 0.
*******IOTestCases*******
input  output 

4 3
2 1 2
2 2 3
2 3 4
3
27 1 0
15 4 0
45 4 0  4 12 
______________________________________________________
1086true
While preparing this problem set the jury has run into the following problem: it was
necessary to send by email the texts of the problems. As it is well known, email is not reliable, messages are sent not enciphered, there is a danger that someone can intercept them. The members of the program committee wanted no participant know the texts of the problems before the start of the contest. That's why they resorted to cryptography methods in order to save the texts of the problems from an unsanctioned reading. The jury gas worked up a new way of enciphering of a text. It is not patented yet, so it's kept secret. However, we'll reveal you one secret: the new algorithm is based on the work with prime numbers. In particular, in uses a calculation of nth by order prime number.
Several members of the program committee independently have worked up
programs that make such calculations, but these programs produce different answers.
Each one of the programmers is sure that his program works correctly. That's why the
jury has reached the deadlock and can't continue working. The contest is about not to
take place.
You are to help to the jury and to save the contest. We want you to write a
program that calculates the nth by order prime number. The main thing is that your
program should work correctly.
*******InputConstraints*******
First line contains a positive integer k. Then k positive integers follow (one in each line). The numbers don't exceed 15000.
*******OutputConstraints*******
For each number n you should output the nth by order prime number.
Each number should be in its line.
*******IOTestCases*******
input  output 

4
3
2
5
7
 5
3
11
17

Hint
The prime number is a positive integer that has exactly two different
positive divisors, i.e. 1 is not a prime number.
______________________________________________________
1087true
You probably know the game where two players in turns take 1 to 3 stones from a
pile. Looses the one who takes the last stone. We'll generalize this well known game.
Assume that both of the players can take not 1, 2 or 3 stones, but
k_{1}, k_{2}, …, k_{m} ones.
Again we'll be interested in one question: who wins in the perfect game. It is guaranteed that it is possible to make next move irrespective to already made moves.
*******InputConstraints*******
The first line contains two integers: n and m (1 ≤ n ≤ 10000; 1 ≤ m ≤ 50) — they are an initial amount of stones in the pile and an amount of numbers k_{1}, …, k_{m}. The
second line consists of the numbers k_{1}, …, k_{m}, separated with a space (1 ≤ k_{i} ≤ n).
*******OutputConstraints*******
Output 1, if the first player (the first to take stones) wins in a perfect game.
Otherwise, output 2.
*******IOTestCases*******
______________________________________________________
1088true
Misfortune has come to the Russian land. Foul Idol has dragged away good fellow
Alyosha Popovich and has chained him with iron chains to the magical stone, so that Alyosha canТt even step. It is necessary to rescue Alyosha from the captivity but nobody is able to: the Tsar is on the war with his detachment. Ilya Murometz has thought a bit and says: "I'll go to rescue my friend Alyosha from Foul Idol alone, and if he is to die there, so am I". Ilya has said these words, and has leaped on to his good horse and has gone seeking for Alyosha.
Ilya rides his horse and comes to a stone, but not the magic one that he has been looking for, but to the road stone. As usual, it is written there: "If you go left — you'll get `time limit', if you go right — you'll get `wrong answer'". Ilya Murometz sits down and falls apart. Suddenly a little bird sits near and asks: "Why are you upset, good fellow?" Ilya Murometz tells her about his problem and the bird tells him: "It's always here like this: if you go left — in an hour you'll see such road stone; and so until you come to the sea. Foul Idol has made this. He wants you to get lost here. Go home, Ilya Murometz, don't try your doom!" And the bird disappears, as there hasn't been the one. Ilya Murometz thinks a lot, but decides not to betray his friendship. He leaps on to his good horse and continues his way. And he rides, and he rides, and he rides.
Ilya Murometz dismounts near a road stone that is like the first one and falls apart more than the first time. Suddenly he sees the magic stone — it is close to him, but Ilya Murometz can't leave the road — he'll disappear in the marsh. He sees the sea very close to him — he can even count: there's D hours of the way from the magic stone to the sea, and from himself he'll have to ride E hours. But from his father he new that from the first stone to the sea (no metter where he turns)
there's F hours way.
He looks closely and sees that the road leads to the moorings, and the moorings are
enumerated with integers. Ilya looks veryvery closely and he finds out that there is a rule of the enumeration: if one rides from the first stone always to the right — he comes to the mooring #1, if at the last moment one turns left — he comes to the mooring #2, and if one always turns right, one before the last time he turns left and then turns right — he comes to the mooring #3! Ilya Murometz sees, that the nearest mooring to his stone is #E_{p}, and the nearest one to the magic stone is #D_{p}. But the roads branch, and there are other moorings.
The good horse turns his head and tells to Ilya Murometz: "Ilyusha! I won't gallop more
than H hours." Help to Ilya Murometz to find out, wether he saves Alyosha Popovich, or he
stays himself in the foreign land.
*******InputConstraints*******
The first line contains 6 integers: D, E, F, D_{p}, E_{p}, H. 0 ≤ D, E, F, H ≤ 30; 1 ≤ E_{p}, D_{p} ≤ 1 073 741 824. All numbers are separated with a space.
*******OutputConstraints*******
should contain the word “YES”, if Ilya Murometz will reach Alyosha Popovich on his horse, and otherwise — the word “NO”.
*******IOTestCases*******
input  output 

1 2 3 2 6 4  YES 
______________________________________________________
1089true
Your teacher of English has recently told you that she dreams about the automated
system of correction and count of mistakes that her pupils do very frequently.
The 8^{th} of March is soon and you've decided that if you write such program and you'll present your teacher with it, then she will be glad and may be will be more favorable to you at the exam. The task is to replace words that differ from the ones in the vocabulary not more than by a letter and to count an amount of the made mistakes. Your teacher must have forgotten that her pupils sometimes forget to write letters and even sometimes they write extra letters  excellent! You are not to think about it!
*******InputConstraints*******
In the first line and then up to the line containing the only symbol `#' go
vocabulary words, each word in its line. In the lines that go after the one containing `#' goers a text that you are to checkup. There are not more than 100 words in the
vocabulary. A length of a word in the vocabulary doesn't exceed 8 symbols. A length of
the text being checkedup doesn't exceed 1000 words. All the words are written in the
lower case. A word might contain Latin letters from `a' to `z'. The vocabulary is compiled so that for each word not more than one variant of correction is possible. There's exactly one end of line character at the end of the text.
*******OutputConstraints*******
You are to output the corrected text in the same format as the initial one (the same punctuation marks, line breaks and words that are absent in the vocabulary) and in the line next to the text there is to be a number of corrections.
*******IOTestCases*******
input 

country
occupies
surface
covers
russia
largest
europe
part
about
world
#
the rushia is the larjest cauntry in the vorld.
it ockupies ebout oneseventh of the earth's surfase.
it kovers the eastern park of yurope and the northern
park of asia.

output 

the russia is the largest country in the world.
it occupies about oneseventh of the earth's surface.
it covers the eastern part of europe and the northern
part of asia.
11

______________________________________________________
1090true
The sergeant ordered that all the recruits stand in rows. The recruits have formed K rows with N people in each, but failed to stand according to their height. The right way to stand in a row is as following: the first soldier must be the highest, the second must be the second highest and so on; the last soldier in a row must be the shortest. In order to teach the young people how to form rows, the sergeant ordered that each of the recruits jump as many times as there are recruits before him in his row who are shorter than he. Note that there are no two recruits of the same height.
The sergeant wants to find which of the rows will jump the greatest total number of times in order to send this row to work in the kitchen. Help the sergeant to find this row.
*******InputConstraints*******
The first line of the input contains two positive integers N and K (2 ≤ N ≤ 10000, 1 ≤ K ≤ 20). The following K lines contain N integers each. The recruits in each row are numbered according to their height (1 — the highest, N — the shortest). Each line shows the order in which the recruits stand in the corresponding row. The first integer in a line is the number of the first recruit in a row and so on. Therefore a recruit jumps as many times as there are numbers which are greater than his number in the line before this number.
*******OutputConstraints*******
You should output the number of the row in which the total amount of jumps is the greatest. If there are several rows with the maximal total amount of jumps you should output the minimal of their numbers.
*******IOTestCases*******
input  output 

3 3
1 2 3
2 1 3
3 2 1
 3

______________________________________________________
1091true
University of New Tmutarakan trains the firstclass specialists in mental arithmetic. To enter the University you should master arithmetic perfectly. One of the entrance exams at the Divisibility Department is the following. Examinees are asked to find K different numbers that have a common divisor greater than 1. All numbers in each set should not exceed a given number S. The numbers K and S are announced at the beginning of the exam. To exclude copying (the Department is the most prestigious in the town!) each set of numbers is credited only once (to the person who submitted it first).
Last year these numbers were K=25 and S=49 and, unfortunately, nobody passed the exam. Moreover, it was proved later by the best minds of the Department that there do not exist sets of numbers with the required properties. To avoid embarrassment this year, the dean asked for your help. You should find the number of sets of K different numbers, each of the numbers not exceeding S, which have a common divisor greater than 1. Of course, the number of such sets equals the maximal possible number of new students of the Department.
*******InputConstraints*******
The input contains numbers K and S (2 ≤ K ≤ S ≤ 50).
*******OutputConstraints*******
You should output the maximal possible number of the Department's new students if this number does not exceed 10000 which is the maximal capacity of the Department, otherwise you should output 10000.
*******IOTestCases*******
______________________________________________________
1092true
Consider a square table of size 2N+1 by 2N+1 with a cells each containing the sign "+" or the sign "−". We call an arbitrary set of 2N+1 cells a transversal if each line and each column of the table contain exactly one cell belonging to the set.
By one operation you are allowed to change signs to opposite in all cells of one transversal. You are asked to determine if it is possible to obtain a table containing not more than 2N cells with the sign "+" by a sequence of such operations.
*******InputConstraints*******
The first line of the input contains a positive integer N not exceeding 20. The next 2N+1 lines contain the table. They consist of the symbols "+" and "" without spaces between them.
*******OutputConstraints*******
The first line of the output should contain the words "No solution" if a necessary sequence of operations does not exist. Otherwise, the first line of the output should contain the words "There is solution:" and the next lines should contain a sequence of operations that leads to the required result. Each of these lines should describe one transversal and should contain the numbers from 1 to 2N+1. Number K at position S means that the transversal includes the cell at the intersection of the line number S with the column number K. The numbers should be separated with a space.
It is sufficient to give only one sequence of operations if there exist many.
*******IOTestCases*******
input  output 

1
+++
++
++
 There is solution:
1 2 3
2 3 1
1 3 2
3 1 2

______________________________________________________
1093true
Maybe you know about the game called Darts. The goal of the game is to hit a circular target, which is called a dartboard. To do so you should take a dart and throw it to the dartboard. Of course, it takes time to learn how to hit the dartboard. And your task is to speed the learning by writing a program that determines if a dart will hit or miss the dartboard.
Let's make some assumptions about the objects under consideration.
 A dartboard is a circular part of a plane. It is defined by coordinates of its center (C_{x}, C_{y} and C_{z}), radius R, and coordinates of a vector that is orthogonal to the plane of the dartboard (N_{x}, N_{y} and N_{z}).
 A dart is a point that moves according the following equations:
M_{x} = S_{x} + V_{x}·t
M_{y} = S_{y} + V_{y}·t
M_{z} = S_{z} + V_{z}·t − (g/2)·t^{2}
Here S_{x}, S_{y}, and S_{z} are coordinates of initial position of the dart, V_{x}, V_{y}, and V_{z} are components of initial velocity of the dart, M_{x}, M_{y}, and M_{z} are coordinates of the point where the dart will be at time t, g is the acceleration of gravity and is assumed to be equal to 10.
 You may assume that the dart is thrown with a nonzero horizontal component (i.e. V_{x} or V_{y} is nonzero).
 You may assume no friction.
 To hit the dartboard the dart should hit it strictly inside boundary from any side.
 Initially the dart is not inside the dartboard's boundary.
*******InputConstraints*******
Input contains 13 real numbers. They are (according to notation given before):
C_{x} C_{y} C_{z} N_{x} N_{y} N_{z} R
S_{x} S_{y} S_{z} V_{x} V_{y} V_{z}
All numbers are not greater than 500 in their absolute values and given with at most 4 digits after decimal point. R is positive.
*******OutputConstraints*******
Output should contain the only word "HIT" (without quotes) if dart hits the dartboard, and word "MISSED" otherwise.
*******IOTestCases*******
input  output 

47 0 72 1 0 1 4.25
0 0 0 10 0 10  HIT 
______________________________________________________
1094true
A new oneline electronic screen (escreen) especially designed for quick input and change of information was installed at a supermarket. All information is entered by an operator. Every time the operator presses a button corresponding to a symbol this symbol is shown on the escreen at the position where the cursor is located at that moment (therefore the symbol that was shown at that position earlier is erased) and then the cursor moves one position to the right.
The keyboard contains letters az, AZ, digits 09, punctuation signs (:;!?.,), and the space button. There are also two keys that move the cursor one position to the right and to the left without erasing anything. The width of the screen is 80 symbols. When the cursor reaches left or right edge of the screen it is automatically placed at the first position to the left.
The new escreen had worked perfectly when it was run by its seller, but when the seller had gone it was found that nobody could operate the escreen properly. Besides, the escreen was installed in such a place that the operator could not see it. Your task is to make a program emulation of the escreen so that the operator could see the results of his or her actions.
*******InputConstraints*******
The single line of the input contains a sequence of the buttons pressed by the operator. The symbol '>' stands for the move of the cursor one position to the right and the symbol '<' stands for the move of the cursor one position to the left. There are no more than 10000 symbols at the input.
*******OutputConstraints*******
The output should contain the line that would be shown on the escreen after pressing the given sequence of the buttons. Assume that at the beginning the escreen contains 80 spaces and the cursor is placed at the first position to the left.
*******IOTestCases*******
input 

>><<<Look for clothes at the <<<<<<<<<<<<<<<second flo
or. <<<<<<<Fresh pizza and <<<<<<<<<<<<<<<<hamburger a
t a shop right to <<<<<<<<<<<<<the entrance. Call <<<<
<<<<<< 123<456<8790 <<<<<<<<<<<<<<<<to order <<<<<<<
<<<<<<<<<<computers< and office<<<<<<< chairs.

output 

Look for second hamburger at computer and chairs.790

______________________________________________________
1095true
Nikifor knows that a certain positive integer has in its decimal form each of the digits 1,2,3,4. You are asked to determine if Nikifor can rearrange the digits of the number in such a way that the new number divides by 7.
*******InputConstraints*******
The first line contains the number N (not exceeding 10000) of positive integers that are to be checked. The next N lines contain these integers. Each number has no more than 20 digits.
*******OutputConstraints*******
For each of the N numbers output a number divisible by 7 that can be obtained from the corresponding number from the input data by a rearrangement of the digits. If such rearrangement does not exist you should output 0 in the corresponding line. In the case of several valid rearrangements you may find only one of them.
*******IOTestCases*******
input  output 

2
1234
531234
 4123
354123

______________________________________________________
1096true
Everybody who had ridden a Ekaterinburg bus could notice that on the inner side of the plate with the number of the route there was a number of another route.
One day the driver of a new bus came to the storehouse and found that there was no plate with the number of the route he had been assigned to ride. The storekeeper simply gave him a random plate and advised to change it for a plate from another bus. But the drivers who had the necessary plates did not need the plate given by the storekeeper. Any driver will agree to change his plate for another only if this plate has the number of his route. Help the new driver to find a shortest sequence of changes that will enable him to get a plate with the number of his route.
*******InputConstraints*******
The first line contain the number K ≤ 1000 of the acting buses (excluding the new bus). The buses are numbered from 1 to K. The next K lines contain the number of the route of the corresponding bus and the number on the other side of its plate. Numbers of routes are integers from 1 to 2000.
The last line of the input contains the number of the route of the new bus and the numbers on the plate given by the storekeeper.
*******OutputConstraints*******
The first line of the output should contain the word IMPOSSIBLE if it is impossible to get the needed number by a sequence of changes otherwise it should contain the least necessary number of changes M > 0 followed by an M lines that contain sequentially numbers of buses (not routes!) with drivers of which the plates must be changed. If there are several solutions, you can output any one.
*******IOTestCases*******
input  output 

4
8 5
5 4
7 4
1 5
4 1 8
 2
4
2

______________________________________________________
1097true
The Square Parliament of the Square country (recall the corresponding problem from the USU 2001 personal contest) has decreed that the National Square Park be created. Of course, the Park should occupy a large square. Unfortunately, at the moment a lot of square citizens have invested (with the help of last championship's participants) their quadrics into the land so that a part of the country is already occupied. It is now impossible to find a land for the Park without affecting interests of the private owners. Thus some of the pieces of land must be expropriated.
To avoid social unrest the Parliament has to locate the Park so that the interests of as less important as possible citizens were affected. It is better to expropriate land from a thousand of simple citizens than from one member of the Parliament or from one bankowner.
The occupied pieces of land are marked with numbers from 1 to 100 according to importance of the owner. So all free land and pieces of land belonging to honest taxpayers are marked with number 1, the land belonging to members of the Parliament is marked with 98, possessions of great businessmen are marked with 99, and the property of the square President is marked with 100.
*******InputConstraints*******
The first line contains the number L, which is the length of a side of the Square country (in meters), and the number A, which is the length of a side of the Park (1 ≤ A ≤ L ≤ 10000). The next line contains the number M (1 ≤ M ≤ 100) of occupied pieces of land (according to the square rules a piece of land is a square with integer coordinates of corners and its sides are parallel to the axes).
The next M lines contain information about these pieces of land: importance of the owner, length of the square's side and the coordinates of the lower left corner, which are integers from 1 to L (the coordinates of the lower left corner of the Square country itself are 1,1). Each piece of land is contained in the country and may intersect another piece of land only along its boundary.
Note that land marked with number 1 (that is of importance 1) is not mentioned in the list altogether. Besides, some pieces of land belong to the members of (not square) Jury who helped to formulate the previous problem. This land is marked with number 255 and cannot be expropriated at all.
*******OutputConstraints*******
You should output the least possible importance of land which must be expropriated (a number from 1 to 100) or the word IMPOSSIBLE if it is impossible to create the Park not involving land of importance more than 100. The number and area of expropriated pieces of land are not important. You should only take into account importance of the most important of the affected landowners.
*******IOTestCases*******
input  output 

5 3
6
94 2 4 1
3 1 1 1
2 1 1 2
2 2 2 1
100 1 2 4
255 1 5 5
 3

______________________________________________________
1098true
Holding a collegiate programming contest is a very exhausting work. There is a wellknown proverb that one fool can ask so many questions that a hundred clever men will not answer. And during a collegiate programming contest questions are asked by one hundred clever people.
The jury of the Third Urals Collegiate Programming Contest being clever enough has found a simple way to make its work easier. We have invented a simple algorithm that will help us answer ALL your numerous questions! Moreover, this algorithm guarantees that the same questions will have the same answers (this would be hardly possible, if we would undertook such a task ourselves). According to this algorithm a member of the jury starts to delete characters of the question in the following order:
 Starting from the first character he or she counts out N−1 characters (spaces, punctuation marks etc. are considered to be characters too) and deletes the Nth character.
 If a string ends the count continues from the beginning of the string.
 After deleting a character the count restarts from the character that would be the (N+1)st in the previous count.
 If the last remaining character is a questionmark ("?") then the answer to the question is "Yes". If it is a space then the answer is "No". Any other character will lead to "No comments" answer.
You should help the jury and write a program that will do a hard work of answering your questions tomorrow. The number N is secret and will not be announced even after the end of the contest. Your program should use N = 1999.
For example, taking a string "Is it a good question?" (its length is 22) the characters will be counted in the following way: "Is it a good question?Is it … quest" and "i" will be deleted. Then the count restarts from "on?Is it…" etc., until "s" will be left (thus the answer is "No comments", as usual).
*******InputConstraints*******
The input is a question, that is any text containing at least one character (end of line is not a character). Each character of the input (excepting the ends of lines) is a part of the question. You should read question from input.
The size of the input is not more than 30000.
*******OutputConstraints*******
*******IOTestCases*******
input  output 

Does the jury of this programming contest use the
algorithm described in this problem to answer my questions?
 Yes

At least, will anybody READ my question?
 No

This is
UNFAIR!
 No comments

Hint
There are no spaces in the sample inputs except for those between words in one line. Thus the first question contains 108 characters, the second contains 40 and the third contains 14.
______________________________________________________
1099true
There is certain amount of night guards that are available to protect the local junkyard
from possible junk robberies. These guards need to scheduled in pairs, so that each pair
guards at different night. The junkyard CEO ordered you to write a program which given the
guards characteristics determines the maximum amount of scheduled guards (the rest will be
fired). Please note that each guard can be scheduled with only one of his colleagues and
no guard can work alone.
*******InputConstraints*******
The first line of the input contains one number N ≤ 222 which is the amount of night guards.
Unlimited number of lines consisting of unordered pairs (i, j) follow, each such pair means
that guard #i and guard #j can work together, because it is possible to find uniforms that
suit both of them (The junkyard uses different parts of uniforms for different guards i.e. helmets, pants, jackets. It is impossible to put small helmet on a guard with a big head or big shoes on guard with small feet). The input ends with Eof.
*******OutputConstraints*******
You should output one possible optimal assignment. On the first line of the output write the even number C, the amount of scheduled guards. Then output C/2 lines, each containing 2 integers (i, j) that denote that i and j will work together.
*******IOTestCases*******
input  output 

3
1 2
2 3
1 3
 2
1 2

______________________________________________________
1100true
Old contest software uses bubble sort for generating final standings. But now, there are too many teams and that software works too slow. You are asked to write a program, which generates exactly the same final standings as old software, but fast.
*******InputConstraints*******
The first line of input contains only integer 1 < N ≤ 150000 — number of teams.
Each of the next N lines contains two integers 1 ≤ ID ≤ 10^{7} and 0 ≤ M ≤ 100.
ID — unique number of team, M — number of solved problems.
*******OutputConstraints*******
Output should contain N lines with two integers ID and M on each.
Lines should be sorted by M in descending order using bubble sort (or analog).
*******IOTestCases*******
input  output 

8
1 2
16 3
11 2
20 3
3 5
26 4
7 1
22 4
 3 5
26 4
22 4
16 3
20 3
1 2
11 2
7 1

Hint
Bubble sort works following way:
while (exists A[i] and A[i+1] such as A[i] < A[i+1]) do
Swap(A[i], A[i+1]);
______________________________________________________
1101true
There is a field [−N..N]×[−N..N].
At initial moment, robot stands at point (0, 0). It starts moving in (1, 0) direction.
Robot moves according to a program.
Program is a correct boolean expression. It contains operators NOT, AND, OR
(NOT has highest priority, OR  lowest), brackets '(', ')', constants 'TRUE' and 'FALSE',
and registers 'A', ..., 'Z'. Initially, all robot's registers are FALSE. Robot moves forward until it reaches a fork. Then, robot evaluate the expression and turns right if it is TRUE and turns left if it is FALSE. Besides, there are some points in the field, standing on which makes one of robot's registers to invert. You are asked to print robot's route until it falls out of the field.
*******InputConstraints*******
First line contains boolean expression. The length of expression ≤ 250.
Second line contains three integers 1 ≤ N ≤ 100, 0 ≤ M ≤ 100, 0 ≤ K ≤ 100.
M — number of forks, K — number of register inverting points. Then follows M lines, each of them contains two integers X, Y — coordinates of forks.
Then follows K lines, each of them contains two integers X, Y and character C — coordinates of register inverting point and name of register, which inverts. You may assume, that there is no fork at point (0, 0). You may assume, that no two objects (forks or register inverting points) coincide.
You may assume, that after some moves robot falls out of the field.
*******OutputConstraints*******
You should print robot's route to output, every pair of coordinates in separate line.
*******IOTestCases*******
input  output 

NOT((A OR NOT B) AND (A OR B)) OR NOT (A AND NOT B OR TRUE)
1 5 2
1 0
1 1
1 1
1 1
1 1
0 1 A
1 0 D
 0 0
1 0
1 1
0 1
1 1
1 0
1 1
0 1
1 1

______________________________________________________
1102true
One entity named "one" tells with his friend "puton" and their conversation is interesting. "One" can say words "out" and "output", besides he calls his friend by name. "Puton" can say words "in", "input" and "one". They understand each other perfect and even write dialogue in strings without spaces.
You have N strings. Find which of them are dialogues.
*******InputConstraints*******
In the first line of input there is one nonnegative integer N ≤ 1000. Next N lines contain nonempty strings. Each string consists of small Latin letters. Total length of all strings is no more than 10^{7} characters.
*******OutputConstraints*******
Output consists of N lines. Line contains word "YES", if string is some dialogue of "one" and "puton", otherwise "NO".
*******IOTestCases*******
input  output 

6
puton
inonputin
oneputonininputoutoutput
oneininputwooutoutput
outpu
utput
 YES
NO
YES
NO
NO
NO

______________________________________________________
1103true
One old man and one old woman sit at the table and write letters.
On the table in front of them at the coordinates (x_{i}, y_{i}) stay N pencils. Diameter of pencils is 0 and all of them stay vertically. Man and woman decide to divide pencils into two equal groups. In order to do this old man give thread and put it on the table so that thread lay in a circle. Circle must cross over three pencils. He wants one group to get into the circle and other group not to get into the circle.
*******InputConstraints*******
At the first line of the input is one odd integer 3 ≤ N ≤ 5000.
At the next N lines are coordinates of pencils.
There are no three pencils staying in one line and there are no four pencils
staying on one circle. All coordinates are integers that are not greater than 10^{8} by absolute value.
*******OutputConstraints*******
You must output 6 integers — coordinates of three pencils over which cross thread. Inside of circle must be (N−3)/2 pencils. On the circle must be these three pencils. And outside of the circle must be others (N−3)/2 pencils. If there is no solution you must output "No solution". If there are more than one solution output any of them.
*******IOTestCases*******
input  output 

7
0 0
1 0
2 1
2 1
1 1
0 2
3 1
 0 0
1 0
2 1

______________________________________________________
1104true
Mrs Little likes digits most of all. Every year she tries to make the best number of the year. She tries to become more and more intelligent and every year studies a new digit. And the number she makes is written in numeric system which base equals to her age. To make her life more beautiful she writes only numbers that are divisible by her age minus one.
Mrs Little wants to hold her age in secret.
You are given a number consisting of digits 0, …, 9 and Latin letters A, …, Z, where A equals 10, B equals 11 etc. Your task is to find the minimal number k satisfying the following condition: the given number, written in kbased system is divisible by k−1.
*******InputConstraints*******
Input consists of one string containing no more than 10^{6} digits or uppercase Latin letters.
*******OutputConstraints*******
Output the only number k, or "No solution." if for all 2 ≤ k ≤ 36 condition written above can't be satisfied. By the way, you should write your answer in decimal system.
*******IOTestCases*******
______________________________________________________
1105true
Nikifor told us that once he solved problem at mathematical tournament of S.Petersburg's secondary school N239 in 1994. Nikifor said that he solved a problem from the moment T_{0} to the moment T_{1}. He remembers that N observers appeared in the room. The ith observer entered the room at the moment t_{0, i}
and went out at the moment t_{1, i}. At every moment there was at least one observer in the room.
When the tournament was finished, Nikifor claimed that it is possible to color some observers, and the summary time when there was only one colored observer in the room is not less than 2/3 of the time when Nikifor solved problem.
You are to answer whether Nikifor right or not.
*******InputConstraints*******
The first line of input contains real numbers T_{0} and T_{1} (T_{0} < T_{1}). The second
line contains number N — number of observers (N < 10000). Next N lines
contain real numbers t_{0, i} and t_{1, i} (T_{0} ≤ t_{0, i} < t_{1, i} ≤ T_{1}).
*******OutputConstraints*******
If Nikifor is not right output should contain the only number 0. If Nikifor is right you should write to the first line the quantity of colored observers, and next lines should contain their numbers. Do not write more than one number in a line. You may write these numbers in any order. If there are more than one solution exist you may find any of them.
*******IOTestCases*******
input  output 

0.0 20.0
7
1.0 1.5
0.0 10.0
9.0 10.0
18.0 20.0
9.0 18.0
2.72 3.14
19.0 20.0
 3
2
5
7

______________________________________________________
1106true
The group of people consists of N members. Every member has one or more friends in the group. You are to write program that divides this group into two teams. Every member of each team must have friends in another team.
*******InputConstraints*******
The first line of input contains the only number N (N ≤ 100). Members are numbered from 1 to N. The second, the third,…and the (N+1)th line contain list of friends of the first, the second, …and the Nth member respectively. This list is finished by zero. Remember that friendship is always mutual in this group.
*******OutputConstraints*******
The first line of output should contain the number of people in the first team or zero if it is impossible to divide people into two teams. If the solution exists you should write the list of the first group into the second
line of output. Numbers should be divided by single space. If there are more than one solution you may find any of them.
*******IOTestCases*******
input  output 

7
2 3 0
3 1 0
1 2 4 5 0
3 0
3 0
7 0
6 0
 4
2 4 5 6

______________________________________________________
1107true
The are N different types of goods at the warehouse. Types are numbered by numbers 1…N. Employees of this warehouse made K different sets of these goods. We'll say that two sets are “similar” if one of them is obtained by deleting one good form the second set or by replacing one good to another.
E.g. Set “1 2 3 4” is similar to sets “3 2 1”, “1 2 5 3 4”, “1 2 3 4 2” and “1 5 4 3” and is not similar to “1 2”, “1 1 2 2 3 4” and “4 5 3 6”.
This warehouse serves M shops (0 < N < M < 101), sending them sets of goods. Every two sets sent to the shop should not be similar. It is possible not to send any set to one or more shops.
You are to write program that determines how to distribute all K sets to these M shops.
*******InputConstraints*******
The first line contains numbers N, K, M. Then K lines describing every set of goods follow, K ≤ 50000. Each of these lines is started with the number of goods in the set, then numbers of goods are written. Number of goods in any set is more than 0 and less than 101. All numbers in these lines are separated by exactly one space.
*******OutputConstraints*******
The first line of the output should contain word YES if the solution exists or NO contrary. If the answer is YES write the numbers of the shops where sets should be sent to. In the second line you have to write number of the shop where the first set should be sent to, the third — for the second set, etc. If there are more than one solution exist you may find any of them.
*******IOTestCases*******
input  output 

8 20 12
5 1 3 5 6 4
5 1 3 5 6 3
4 5 6 3 3
4 5 6 3 4
4 4 6 5 8
4 7 7 7 7
3 7 7 7
2 2 2
3 2 2 7
3 1 2 3
3 1 2 4
10 1 2 3 4 5 6 7 8 7 6
10 8 7 6 5 4 3 2 1 2 1
20 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 3 5 7
5 4 6 4 6 4
5 6 4 6 4 6
6 6 6 6 6 6 6
3 6 6 6
1 1
1 2
 YES
2
1
9
1
6
2
4
5
3
7
8
5
4
8
7
9
1
1
2
3

______________________________________________________
1108true
Your rich uncle died recently, and the heritage needs to be divided among your relatives and the church (your uncle insisted in his will that the church must get something). There are N relatives (N ≤ 18) that were mentioned in the will. They are sorted in descending order according to their importance (the first one is the most important). Since you are the computer scientist in the family, your relatives asked you to help them. They need help, because there are some blanks in the will left to be filled. Here is how the will looks:
Relative #1 will get 1/... of the whole heritage,
Relative #2 will get 1/... of the whole heritage,
...
Relative #N will get 1/... of the whole heritage.
The logical desire of the relatives is to fill the blanks in such way that the uncle’s will is preserved (i.e the fractions are nonascending and the church gets something) and the amount of heritage left for the church is minimized.
*******InputConstraints*******
The only line of input contains the single integer N (1 ≤ N ≤ 18).
*******OutputConstraints*******
Output the numbers that the blanks need to be filled (on separate lines), so that the heritage left for the church is minimized.
*******IOTestCases*******
______________________________________________________
1109true
On the upcoming conference were sent M representatives of country A and N representatives of country B (M and N ≤ 1000). The representatives were identified with 1, 2, …, M for country A and 1, 2, …, N for country B. Before the conference K pairs of representatives were chosen. Every such pair consists of one member of delegation A and one of delegation B. If there exists a pair in which both member #i of A and member #j of B are included then #i and #j can negotiate. Everyone attending the conference was included in at least one pair. The CEO of the congress center wants to build direct telephone connections between the rooms of the delegates, so that everyone is connected with at least one representative of the other side, and every connection is made between people that can negotiate. The CEO also wants to minimize the amount of telephone connections. Write a program which given M, N, K and K pairs of representatives, finds the minimum number of needed connections.
*******InputConstraints*******
The first line of the input contains M, N and K. The following K lines contain the choosen pairs in the form of two integers p_{1} and p_{2}, p_{1} is member of A and p_{2} is member of B.
*******OutputConstraints*******
The output should contain the minimum number of needed telephone connections.
*******IOTestCases*******
input  output 

3 2 4
1 1
2 1
3 1
3 2
 3 
______________________________________________________
1110true
You are given the whole numbers N, M and Y. Write a program that will find all whole numbers X in the interval [0, M − 1] such that X^{N} mod M = Y.
*******InputConstraints*******
The input contains a single line with N, M and Y (0 < N < 999, 1 < M < 999, 0 < Y < 999) separated with one space.
*******OutputConstraints*******
Output all numbers X separated with space on one line. The numbers must be written in ascending order. If no such numbers exist then output −1.
*******IOTestCases*******
______________________________________________________
1111true
You are given n (1 ≤ n ≤ 50) squares and point P. The distance between P and square is the shortest line segment that connects P with the contour or the internal area of the square. If P is inside the square then the distance is zero. It is possible some squares to be points i.e. to have vertices that coincide. Write a program that will sort the squares in ascending order according the distance from P.
*******InputConstraints*******
The first line contains the integer n. The following n lines contain four integers in the range (−9999, 9999). The first two numbers define the x and y coordinates of one of the vertices of the square, the next two numbers define the opposite vertex. The last line contains the x and y coordinates of P.
*******OutputConstraints*******
The output should be a line containing the ids of the squares sorted according to the distance from P. The ids are defined according to the order in which the squares are given in the input. Use ids to break ties i.e. if two squares are the same distance from P then write the square with the lowest id first. Using 10^{−14} precision when comparing the distances is accurate enough.
*******IOTestCases*******
input  output 

2
0 0 1 1
0 3 1 4
0 0
 1 2 
______________________________________________________
1112true
You are given N (0 < N < 100) line segments on a line. Every segment is defined with its endpoints A_{i} and B_{i} (A_{i} ≠ B_{i}, 1 ≤ i ≤ N). The endpoints are integer coordinates in the interval [−999, 999]. Some of the segments probably intersect. Write a program, which removes minimum number of the given segments, so that none of the left segments have common interior point.
*******InputConstraints*******
The first line of input contains the integer N. Each of the following N lines, contains two integers (A_{i} and B_{i}), separated with one space.
*******OutputConstraints*******
On the first line write the integer P, equal to the number of segments, which are left after your program removes the excess segments. The following P lines should contain the coordinates of the left and the right endpoints of the segments which are left. These coordinates must be separated with one space. Coordinates of the left endpoints must be written in their ascending order. If the problem has more the one solution, write only one of them no matter which.
*******IOTestCases*******
input  output 

3
6 3
1 3
2 5
 2
1 3
3 6

______________________________________________________
1113true
Our jeep is in the desert and must reach a point which is N kilometres away from it. The terrain is tough, the car is old, and it seems like the fuel flows out, and because of this on every kilometre travelled, one litre of fuel is spent. But the jeep has fuelcans and fuel tank with total capacity of M < N litres. On other hand, at the beginning of the road there is unlimited amount of fuel, and everywhere in the desert there are empty cisterns, in which the jeep, passing near them, can leave unlimited amount of fuel.
Write a program which calculates the minimum amount of fuel in litres which is needed to reach the destination point.
*******InputConstraints*******
Two integers N and M are written on the only line of input. It is known that 5M ≥ N > 0. (N < 32000).
*******OutputConstraints*******
The result (the minimum liters of fuel, eventually rounded up), must be written on the only line of output.
*******IOTestCases*******
______________________________________________________
1114true
N boxes are lined up in a sequence (1 ≤ N ≤ 20). You have A red balls and B blue balls (0 ≤ A ≤ 15, 0 ≤ B ≤ 15). The red balls (and the blue ones) are exactly the same. You can place the balls in the boxes. It is allowed to put in a box, balls of the two kinds, or only from one kind. You can also leave some of the boxes empty. It's not necessary to place all the balls in the boxes. Write a program, which finds the number of different ways to place the balls in the boxes in the described way.
*******InputConstraints*******
Input contains one line with three integers N, A and B separated by space.
*******OutputConstraints*******
The result of your program must be an integer written on the only line of output.
*******IOTestCases*******
______________________________________________________
1115true
The military intelligence of one country found out that N (N < 100) battle ships of neighboring enemy country are situated in M rows (1 < M < 10). The intelligence knows the lengths l_{1}, l_{2}, …, l_{N} of the battle ships which are whole numbers in the interval [1, 100], and wants to know in which rows the ships are situated. The only thing that is known about the M rows are their lengths — L_{1}, L_{2}, …, L_{M}. Assume that the ships touch their neighbours in the rows and that every row contains at least one ship. Write program that will find one possible ordering of the ships in rows.
*******InputConstraints*******
The first line of the input contains N and M. The next N lines contain the lengths of the ships. The next M lines contain the lengths of the rows.
*******OutputConstraints*******
The output should contain M pairs of lines. The first line of each pair should contain the amount of the ships in the current row, the following line should contain the lengths of the ships from the current row. The order of the M row descriptions should be the same as the order in which the rows are given in the input.
*******IOTestCases*******
input  output 

5 2
4
10
2
5
3
11
13
 3
5 4 2
2
10 3

______________________________________________________
1116true
SKB Kontur has been developing a new SKB Kontur Framework for the last three months. One of the latest wrinkles is that data will be presented with the help of piecewise constant functions. Your team is to implement an operation of "subsettraction" of the functions. A function is called piecewise constant if its domain can be divided into intervals and the function is constant on each interval. We also assume that the function value at the leftend point of each interval of constancy is equal to its value on the interval. In fig.1 there is a piecewise constant function with three intervals of constancy. Note that the function value at the point B is U and at the points C, E and on the interval (C,D)  the function value is not defined.
A result of the subsettraction operation of two piecewise constant functions
F_{1} @
F_{2} is a piecewise constant
function
F defined as follows:
 F(x) = F_{1}(x) if F_{1}
is defined and F_{2} is not defined;
 F(x) is not defined if F_{1} and F_{2}
are defined both;
 F(x) is not defined if F_{1} is not defined.
In Fig.3 there is the result of the operation of the subsettraction of the two functions from Fig.1 and Fig.2.
*******InputConstraints*******
contains two lines of the same format. Each line characterizes one piecewise
constant function. A line begins with an integer N (1 ≤ N ≤ 14999). Then characterizations of constancy intervals follow in the
ascending order with respect to their left ends. Each interval is given by three integer
numbers A, B, Y (A < 32000, B
< 32000, Y ≤ 100, A < B), where A
is the left end of an interval, B is the right end of an interval and
Y is the function value on the interval. It's known that that no two
intervals from one line intersect. If two intervals are adjacent, the function values on the intervals are different.
*******OutputConstraints*******
contains one line of the same format (see the input specification).
This line should describe a result of the operation of subsettraction of the two input
piecewise constant functions.
*******IOTestCases*******
input  output 

3 1 1 2 1 3 4 4 6 3
2 2 2 1 5 7 5
 2 2 3 4 4 5 3

______________________________________________________
1117true
During long years of work in SKB Kontur a certain hierarchy of employees has been developed. Each person except ordinary employees has exactly two direct subordinates and not more than one direct superior. There is no subordinate of ordinary employees (see figure).
Each employee has his own number. Of course, different employees have different numbers. It's known as well that either an employee has the maximal number or there is another employee whose number is greater by one. Similarly, either
an employee has a number "1" or there is another employee whose number is less by one. The number of intermediate levels of employees between an arbitrary employee who has subordinates (an ordinary employee) and the employee who has no superiors (the main superior) is the same for all ordinary employees.
The things have come round so that each employee who has subordinates
has got a number greater than the number of one of his subordinates and less than the number of the other. Moreover, if his number is greater than his superior's
then the numbers of his subordinates are also greater than the number
of his superior. And conversely, if his number is less, then his subordinates'
numbers are less too.
A special system of intracorporate message exchange has been worked out. A message from an
employee with the number i can be addressed directly only to
the employees i1 and i+1. Moreover, this is done the same day
(it takes 0 days to do that) if the employees are direct superior and
subordinate. Otherwise, the message delivery takes an amount of days that
is equal to the number of intermediate employees between the sender and recipient. For example, a message from the employee 2 to
the employee 4 is being delivered as follows. The employee 2 sends the
message to the employee 3, and the employee 3 addresses it to the employee 4.
This process takes one day because the first step (2>3) takes 0 days,
and the second one (3>4) takes 1 day.
*******InputConstraints*******
The only line contains two positive integers: the number of an employee who sends a message and the number of the recipient. Each of the numbers doesn't exceed 2^{31}−1.
*******OutputConstraints*******
You should output the only number — the number of days necessary
to deliver the message.
*******IOTestCases*******
______________________________________________________
1118true
Specialists of SKB Kontur have developed a unique cryptographic algorithm
for needs of information protection while transmitting data over the Internet.
The main advantage of the algorithm is that you needn't use big numbers
as keys; you may easily do with natural numbers not exceeding a million.
However, in order to strengthen endurance of the cryptographic system it
is recommended to use special numbers  those that psychologically seem
least "natural". We introduce a notion of triviality
in order to define and emphasize those numbers.
Triviality of a natural number N is the ratio of the
sum of all its proper divisors to the number itself. Thus, for example,
triviality of the natural number 10 is equal to 0.8 = (1 + 2 + 5) / 10
and triviality of the number 20 is equal to 1.1 = (1 + 2 + 4 + 5 + 10) /
20. Recall that a proper divisor of a natural number is the divisor
that is strictly less than the number.
Thus, it is recommended to use as nontrivial numbers as possible in
the cryptographic protection system of SKB Kontur. You are to write a
program that will find the less trivial number in a given range.
*******InputConstraints*******
The only line contains two integers I and J, 1 ≤ I ≤ J
≤ 10^{6}, separated with a space.
*******OutputConstraints*******
Output the only integer
N satisfying the following conditions:
 I ≤ N ≤ J;
 N is the least trivial number among the ones that obey the first
condition.
*******IOTestCases*******
______________________________________________________
1119true
Many of SKB Kontur programmers like to get to work by Metro because the main office is situated quite close the station Uralmash. So, since a sedentary life requires active exercises offduty, many of the staff — Nikifor among them — walk from their homes to Metro stations on foot.
Nikifor lives in a part of our city where streets form a grid of residential quarters. All the quarters are squares with side 100 meters. A Metro entrance is situated at one of the crossroads. Nikifor starts his way from another crossroad which is south and west of the Metro entrance. Naturally, Nikifor, starting from his home, walks along the streets leading either to the north or to the east. On his way he may cross some quarters diagonally from their southwestern corners to the northeastern ones. Thus, some of the
routes are shorter than others. Nikifor wonders, how long is the shortest route.
You are to write a program that will calculate the length of the shortest route from the southwestern corner of the grid to the northeastern one.
*******InputConstraints*******
There are two integers in the first line: N and M (0 < N,M ≤ 1000) — westeast and southnorth sizes of the grid. Nikifor starts his way from a crossroad which is situated southwest of the quarter with coordinates (1, 1). A Metro station is situated northeast of the quarter with coordinates (N, M). The second input line contains a number K (0 ≤ K ≤ 100) which is a number of quarters that can be crossed diagonally. Then K lines with pairs of numbers separated with a space follow — these
are the coordinates of those quarters.
*******OutputConstraints*******
Your program is to output a length of the shortest route from Nikifor's home to the Metro station in meters, rounded to the integer amount of meters.
*******IOTestCases*******
input  output 

3 2
3
1 1
3 2
1 2
 383

______________________________________________________
1120true
There is no involute formulation concerning factitiously activity of SKB Kontur in this problem. Moreover, there is no formulation at all.
*******InputConstraints*******
There is the only number N, 1 ≤ N ≤ 10^{9}.
*******OutputConstraints*******
Your program is to output two positive integers
A and
P
separated with a space such that:
 N = A + (A + 1) + … + (A + P − 1).
 You are to choose a pair with the maximal possible value of P.
*******IOTestCases*******
______________________________________________________
1121true
SKB Kontur has a lot of branches scattered all over the city. The company management decided to create a guide that will help clients to choose which of the branches they need. You are asked for help in this work.
The city is represented in the form of a grid of blocks. Each block is a square whose sides are streets and whose corners are crossroads. We suppose that all branches are located exactly at crossroads. The branches of SKB Kontur are of different types: service centers, warehouses, shops, training centers and so on.
Let's mark service centers with number 1, warehouses with number 2, shops with number 4, training centers with number 8 and so on. There are not more than 11 types of branches, and two branches of the same type cannot be located at the same crossroad. Each crossroad is assigned a number equal to the sum of numbers with which the branches located at this crossroad are marked. Crossroads at which there are no branches of SKB Kontur are assigned 0.
Let the distance between two crossroads be equal to the number of street segments
which one has to go from the first crossroad to the second (see picture).
For example, the distance from a corner of a block to the opposite corner
of this block is 2.
For each crossroad at which there are no branches of SKB Kontur
you have to find the sum of the numbers corresponding to the types of
the branches nearest to this crossroad.
For example, suppose that there are no branches at a given crossroad and at
distance 1 from it, there is a branch of type 16 at distance 2,
there are also two branches of type 8 and one of type 4 at distance 2
in other directions and there are no more branches at distance 2 from
this crossroad.
Then we should output number 28=16+8+4 for this crossroad.
We do not take into consideration branches that are at distances greater
than 5 from a given crossroad.
Thus, if a crossroad does not have branches of SKB Kontur that
are located at distances less than 6 from it then we should output
0 for this crossroad.
*******InputConstraints*******
The first line contains positive integers H and W not exceeding 150.
They are numbers of "vertical" and "horizontal" streets, correspondingly.
The next H lines contain W numbers each, the ith number in the jth line
describing types of the branches located at the crossroad of the
ith "vertical" and the jth "horizontal" street.
*******OutputConstraints*******
You should output H lines containing W numbers each,
the ith number in the jth line being equal to
the sum of the numbers corresponding to the types of
the branches nearest to the corresponding crossroad
if there are no branches at this crossroad and −1 otherwise.
*******IOTestCases*******
input  output 

5 5
0 0 2 0 2
0 0 0 0 0
0 0 0 0 0
0 0 0 5 0
1 0 0 4 0
 2 2 1 2 1
3 2 2 7 2
1 7 7 5 7
1 5 5 1 5
1 1 4 1 4

______________________________________________________
1122true
At SKB Kontur we have to work much.
So there is no sin in taking a rest and playing from time to time.
Consider for example the following famous oneplayer game.
We have a 4×4 field. There are chips with one side painted white and another side painted black on the field. Some of the chips are with their white side up and the others are with their white side down at the moment. Each move consists in turning over a chip together with all the chips that are adjacent to it vertically and horizontally (i.e. 5 chips altogether).
The aim is to come to the position in which all the chips are with the same side up.
Naturally, one is easily bored with this game
because interesting and unexpected positions become fewer as time goes on.
That is why a modified version of the game is now more popular at SKB Kontur.
In this version a move consists in turning over a fixed combination of chips
within a 3×3 square. For example, a move may consist in turning over all
the diagonal neighbors of a chosen chip.
The combination of chips is chosen arbitrarily; it may be assigned in the form of a 3×3 field in which the central cell corresponds to the cell at which a move as made. For example, in picture at the left the upper combination corresponds to a standard game and the lower combination is for the game described in the previous paragraph. Note that a combination can be asymmetrical. Each move is made at one of the cells of the playing field (i.e. the central cell of the 3×3 movedefining square is selected among the field's cells). Prescriptions to turn over chips at cells which are outside the 4×4 field are ignored.
In this game it would be nice to know if it is possible to reach a position in which all the chips are with the same side up and if it's possible to do this then in how many moves. You are to write a program which answers these questions.
*******InputConstraints*******
The first four lines describe the initial arrangement of chips.
A symbol "W" stands for a chip which lies with its white side up
and a symbol "B" stands for a chip which lies with its black side up.
The next three lines describe a move: the chips that are to be turned over
are shown by "1" and others are shown by "0".
*******OutputConstraints*******
If it is impossible to reach the aim of the game you should output
the word "Impossible", otherwise you should output the minimal number
of moves necessary to come to the final position.
*******IOTestCases*******
input  output 

WWWW
WBBW
WBWW
WWWW
101
010
101
 Impossible

______________________________________________________
1123true
All employees of SKB Kontur like to get their salaries. Often and in large quantities. But the company management is of a bit different opinion and pays out strictly once a month. After some consultations the employees decided that if one of the parameters (frequency of payment) was fixed it was possible to change the second parameter (amount of the money paid out). They contrived the following scheme. A group of employees who proudly call themselves mathematics and mechanics faculty graduates visits the management and using their mathematical authority claims that the computers in the company's accounts department will work more efficiently if salaries of all the employees take the form of palindromes. As you know, a numerical palindrome is a number that does not change when you read it from right to left. For example, 12344544321 is a palindrome and 12345543210 is not. Of course, the management had to agree with this proposal, but upon one condition: each employee had to recount his or her salary so that the salary took the form of the least possible palindrome that is greater than or equal to the original salary. You are asked to help the employees of SKB Kontur.
*******InputConstraints*******
consists of one string containing the original salary of an employee. The string is not longer than 2001 symbols.
*******OutputConstraints*******
should consist of one string containing the new salary calculated according to the above rules.
*******IOTestCases*******
input  output 

12341321
 12344321

______________________________________________________
1124true
There's no doubt that one of the most important and crucial things to do in this world is to bring up children. May be, if you study properly and reach good results at the competition you'll get a position of nanny in a kindergarten. But you are to get ready for it! Let's consider some problems that a nanny has to solve in a kindergarten.
Everyone knows the game "Mosaic". Playing the game, one is to lay out pictures of different colored pieces. Let there be M different boxes and N mosaic pieces of each of the M colors. After playing the game children rarely put the pieces back to their boxes correctly so that the color of the box and the colors of its pirces would be the same. A nanny has to do that.
Children have already put the mosaic pieces to the boxes but possibly not correctly. There are N pieces in each box. Some pieces (possibly all of them) are located in wrong boxes (i.e. boxes with pieces of a different color). Moving a hand once one can take a piece from one box to another or simply move the hand to another box. You may start from any box you like. The movement towards the first box is not taken into account. Find out the minimal number of movements one needs to put all the mosaic pieces to their boxes.
*******InputConstraints*******
The first line contains integers 2 ≤ M ≤ 500 (the number of colors) and 2 ≤ N ≤ 50 (the number of pieces of each color), Each of the next M lines contains N numbers in the range from 1 to M (the i+1st line contains colors of pieces located in the ith box). The numbers are separated with a space.
*******OutputConstraints*******
the minimal possible number of hand movements that one has to make in order to take all the pieces to their boxes.
*******IOTestCases*******
input  output 

4 3
1 3 1
2 3 3
1 2 2
4 4 4
 6

______________________________________________________
1125true
Nikifor likes to play hopscotch in the kindergarten. The playing field
is a rectangle M × N partitioned into cells 1 × 1 meter. Nikifor hops from one cell to another possibly not adjacent cell. Each cell is colored black or white. Each time Nikifor hops into a cell, all cells
whose centers are at an integer amount of meters away from Nikifor's cell center reverse their colors. You are given the final colors of the playing field cells. You also know
the number of times Nikifor has been at each cell. Your task is to restore the initial colors of the cells.
*******InputConstraints*******
The first line contains two nonnegative integers M and N that do not exceed 50. The next M lines contain a character table M × N. This table describes the final coloring of the field. Character 'W' denotes the white color of the cell, and 'B' denotes the black color. There are no other characters in the table. The next M lines contain a matrix with nonnegative integer elements. Each element shows how many times Nikifor has been at the corresponding cell. Numbers in the lines are separated with a space and do not exceed 2∙10^{9}.
*******OutputConstraints*******
should consist of M lines. The lines should contain a character table that shows the initial coloring of the playing field.
*******IOTestCases*******
input  output 

6 6
BWBBWW
BWBBWB
BBWWBW
BBBBBW
BBWWWW
BBWBBW
2 0 12 46 2 0
3 0 0 0 0 200
4 2 1 1 4 2
4 2 1 1 4 4
0 0 0 0 0 0
2 56 24 4 2 2
 WWBBWW
WBWWBW
WBBBBW
WBWWBW
WBWWBW
WBWWBW

______________________________________________________
1126true
The directory of our kindergarten decided to be attentive to the children's health and not to let them walk outdoors during magnetic storms. Special devices that measure and display magnetic intensity were ordered. If the readout exceeded some certain level the children were told to go indoors. They disliked it because they couldn't play their games up to the end. The nannies hated it because they had to dress and undress children
many times.
After a while it became clear that one could try to forecast magnetic intensity because long periods of quietude alternated with short periods of plenty of sharp peaks (this is called a magnetic storm). Hence a new modification of the devices was ordered.
The new devices were to remember the situation within several last hours and to display the maximal intensity during the period. If the intensity was low within the last 6 hours the magnetic field was regarded to be quiet; the children were let outdoors and played all the prescript time. Otherwise new peaks were probable and the children spent their time indoors.
Your task is to write a program for a new version of the device. As a matter of fact you are to solve just the main problem of modification. All the rest is already done.
You are given a number M which is length of a period (in seconds) within which peaks are to be stored and displayed. A sequence of measured magnetic intensity values is given to you as well. Each measurement is a number within the range from 0 to 100000.
Your are to output a sequence of values displayed by the device. The first number of the sequence is the maximal element of the first M input numbers, the second number is the maximal element of the 2nd, …, M+1st input numbers and so on.
We hope that the new devices with your program won't go back on nannies and children will not walk during magnetic storms.
*******InputConstraints*******
The first line contains a number M, 1 < M ≤ 14000. Then values (N integers) measured by the device follow each one in its line. There
is a number −1 in the end. M ≤ N ≤ 25000.
*******OutputConstraints*******
a sequence of readouts, each one in its line.
*******IOTestCases*******
input  output 

3
10
11
10
0
0
0
1
2
3
2
1
 11
11
10
0
1
2
3
3

______________________________________________________
1127true
There are lots of cubic bricks in the kindergarten. Children like to build toy brick towers and then to drop them. It is clear that the higher tower has been built the more interesting it is to drop it. The tower is built by placing bricks one onto another and aligning their sides. The tower is based on one brick. Thus the height of a tower is the number of the bricks it is built of. Each side of a brick is painted in one color.
So the kids build colored towers. In order to train the children's sense of beauty nannies teach them to build the towers in such a way that each side of the tower would be onecolor. Thus the kids would like to build a tower with onecolor sides as high as possible.
Every nanny can easily solve this problem. Try your best to do it as well.
*******InputConstraints*******
The first line contains a number N (1 < N ≤ 10^{3}) — the number of bricks. The next N lines contain descriptions of bricks. Each brick is described with a string of 6 capital latin letters denoting the color of the corresponding side (A — Azure, B — Blue, C — Cyan, G — Green, O — Orange, R — Red, S — Scarlet, V — Violet, W — White, Y — Yellow). The colors of the sides are given in the following order: front, right, left, rear, top, bottom. A brick never has two sides of the same color.
*******OutputConstraints*******
Output the only number — the maximal height of a toy tower that can be built of the given brick set.
*******IOTestCases*******
input  output 

4
GYVABW
AOCGYV
CABVGO
OVYWGA
 3

______________________________________________________
1128true
There are N children in the kindergarten. Unfortunately, the children quarrel though not often. Each child has not more than three adversaries. Is it possible to partition the children into two groups (possibly not equal), so that each child would have not more than one adversary in his or her group?
*******InputConstraints*******
The first line contains an integer N, 0 < N ≤ 7163. The next N lines contain lists of adversaries of each child. A line starts with the amount of the corresponding child's adversaries, then the numbers of the adversaries follow. The numbers in each line are separated with a space.
*******OutputConstraints*******
The first line contains the number of children in the smaller group. The next line contains the list of children in the group. The numbers in the second line are separated with a space. If the groups are of the same size then you are to describe the group that contains the child number one. Note that the output may contain the only number 0. If there
are several possible partitions it's sufficient to output an arbitrary one. If there's no possible partition you are to output the only string “NO SOLUTION”.
*******IOTestCases*******
input  output 

8
3 2 3 7
3 1 3 7
3 1 2 7
1 6
0
2 4 8
3 1 2 3
1 6
 4
1 2 5 6

______________________________________________________
1129true
There are many rooms, corridors and doors between them in the kindergarten. Some repairs are planned to be made soon. The doors are agreed to be painted in bright cheerful colors: green and yellow. The matron of the kindergarten wants the doors to satisfy the following condition: the sides of an arbitrary door must have the different colors. The number of green doors in each of the lodgings must differ from the number of yellow doors not more than by one. Given the plan of the kindergarten suggest your scheme of door painting.
*******InputConstraints*******
The first line contains the number of lodgings N ≤ 100 in the kindergarten.
The next N lines contain description of the door configuration (k+1st line contains a description of the kth lodging). Each of the N lines starts with the number of doors that connect this lodging with adjacent ones. Then there are numbers of adjacent lodgings separated with a space (these numbers follow in ascending order).
*******OutputConstraints*******
should contain a required painting scheme or the word “Impossible” if it is
impossible to satisfy the requirements. The colors of the Kth room doors should be put in the Kth line in the same order as they were in the input data. The green color is denoted by G, yellow — by Y.
*******IOTestCases*******
input  output 

5
3 2 3 4
3 1 3 5
4 1 2 4 5
3 1 3 5
3 2 3 4
 G Y G
Y G Y
G Y Y G
Y G G
G Y Y

______________________________________________________
1130true
Little Nikifor wouldn't stay long without movement. It's boring to run
in one direction for a long time, as well. A wise nanny knows that when
Nikifor goes playing outdoors he moves along vectors a_{1},
a_{2}, …, a_{n}; each time
his displacement is either equal to the next in turn vector or to the vector
opposite to it. A pedagogical influence
of the nanny with Nikifor is rather strong, so each time she can point
out which one of the two possible directions he should choose.
The nanny knows that length of each of the vectors a_{1},
a_{2}, …, a_{n} doesn't exceed L.
Nikifor starts his walk from the nanny and she wants him to move off her not farther
than by the square root of 2 multiplied by L (sqrt(2)L) in the end of his walk.
What directions should she point
out in order not to let the child move too far off her pedagogical influence in the end of the walk?
*******InputConstraints*******
The first line contains an integer n, 0 < n ≤ 10000. The second line contains a nonnegative integer L, L < 100. The next n lines contain coordinates of the vectors. The coordinates are integer.
*******OutputConstraints*******
The first line is to contain the word “YES” if the nanny can cope with her task, and “WRONG ANSWER” otherwise. If the answer is “YES” then the next line should consist of n symbols '+' or '−'. There is the symbol '+' at the ith position if Nikifor runs along the vector a_{i}, and there's a symbol '−' if Nikifor runs along the vector −a_{i}. If there are several solutions it's enough to output an arbitrary one.
*******IOTestCases*******
input  output 

4
5
5 0
0 5
0 0
3 4
 YES
+++

______________________________________________________
1131true
A new educating program was received by the kindergarten. Of course, children have discovered it immediately and want to play with it as soon as possible. In order to let them do it the program has to be copied to all the N computers that the kindergarten had bought just before the default of 1998. At the moment the program is installed only on one computer. Other computers do not have floppy drives and are not connected with a local network. The only way to transfer information from one computer
to another is to copy it using a nullmodem cable (a cable that connects two computers directly). So, if the program is installed on a computer, it can be copied to some other (but only one!) computer within an hour. There are only K nullmodem cables in the kindergarten. Your task is to estimate the minimal time necessary for copying the program to all the computers in the kindergarten.
*******InputConstraints*******
The only input line contains two integers separated with a space: N
and K (1 ≤ N ≤ 10^{9}; 1 ≤ K ≤ 10^{9}).
*******OutputConstraints*******
You are to output the minimal time (in hours) necessary for copying of the program to all the computers.
*******IOTestCases*******
______________________________________________________
1132true
The number x is called a square root of a modulo n (root(a,n)) if x*x = a (mod n). Write the program to find the square root of number a by given modulo n.
*******InputConstraints*******
One number K in the first line is an amount of tests (K ≤ 100000). Each next line represents separate test, which contains integers a and n (1 ≤ a, n ≤ 32767, n is prime, a and n are relatively prime).
*******OutputConstraints*******
For each input test the program must evaluate all possible values root(a,n)
in the range (0,n−1) and output them in increasing order in one separate line using spaces. If there is no square root for current test, the program must print in separate line: ‘No root’.
*******IOTestCases*******
input  output 

5
4 17
3 7
2 7
14 31
10007 20011
 2 15
No root
3 4
13 18
5382 14629

______________________________________________________
1133true
is an infinite sequence of integers that satisfies to Fibonacci condition F_{i + 2} = F_{i + 1} + F_{i} for any integer i.
Write a program, which calculates the value of F_{n} for the given values of F_{i} and F_{j}.
*******InputConstraints*******
The input contains five integers in the following order: i, F_{i}, j, F_{j}, n.
−1000 ≤ i, j, n ≤ 1000, i ≠ j,
−2·10^{9} ≤ F_{k} ≤ 2·10^{9} (k = min(i, j, n), …, max(i, j, n)).
*******OutputConstraints*******
The output consists of a single integer, which is the value of F_{n}.
*******IOTestCases*******
Hint
In the example you are given: F_{3} = 5, F_{−1} = 4; you asked to find the value of F_{5}. The following Fibonacci sequence can be reconstructed using known values:
…, F_{−1} = 4, F_{0} = −1, F_{1} = 3, F_{2} = 2, F_{3} = 5, F_{4} = 7, F_{5} = 12, …
Thus, the answer is: F_{5} = 12.
______________________________________________________
1134true
Each of the n cards has numbers written on the both sides of it. The first card has 0 and 1 on it, the second has 1 and 2, …, the nth has (n−1) and n. Firstgrade pupil Nick takes cards one by one in random order and reads the number on one of the sides. Nick is not very good with numbers, so it is possible that he makes a mistake. Your task is to find out if he was mistaken, i.e. if the given sequence of numbers is possible for some order of taking cards.
*******InputConstraints*******
The first line contains numbers n, the total number of cards, and m, the number of the cards that were taken. Starting with the second line, the m nonnegative integers are listed (the sequence read by Nick). One or more spaces or line feeds separate the numbers.
1 ≤ n ≤ 1000
*******OutputConstraints*******
Write YES if the given sequence of numbers is possible for some order of taking cards, NO otherwise.
*******IOTestCases*******
input  output 

5 4
2 0 1 2
 NO 
______________________________________________________
1135true
N recruits are standing in front of a sergeant who orders to turn left. Some of the soldiers turn left, while the others turn right. In a second each recruit seeing the face of another recruit understands that a mistake was made and turns around. This happens at the same time to each pair of soldiers facing each other. The process continues until the formation becomes stable. Write a program, which finds out the number of times when a pair of soldiers turned around. If the process is infinite then the program should write the word “NO”.
Example:
Legend:
‘<’: a recruit facing left;
‘>’: a recruit facing right.
Formation 
Comments 
Number of turns 
> > < < > < 
Initial formation 
2 
> < > < < > 
One second has passed 
2 
< > < > < > 
Two seconds have passed 
2 
< < > < > > 
Three seconds have passed 
1 
< < < > > > 
Final formation 
Total: 7 
*******InputConstraints*******
The first line contains the number of recruits (N). The rest of the input contains only ‘<’, ‘>’ and line break characters. There is exactly N ‘<’ and ‘>’ characters in the input. Each line of the input may have up to 255 characters.
1 ≤ N ≤ 30000.
*******OutputConstraints*******
Write the number of turns.
*******IOTestCases*******
______________________________________________________
1136true
A new parliament is elected in the state of MMMM. Each member of the parliament gets his unique positive integer identification number during the parliament registration. The numbers were given in a random order; gaps in the sequence of numbers were also possible. The chairs in the parliament were arranged resembling a treelike structure. When members of the parliament entered the auditorium they took seats in the following order. The first of them took the chairman’s seat. Each of the following delegates headed left if his number was less than the chairman’s, or right, otherwise. After that he took the empty seat and declared himself as a wing chairman. If the seat of the wing chairman has been already taken then the seating algorithm continued in the same way: the delegate headed left or right depending on the wing chairman’s identification number.
The figure below demonstrates an example of the seating of the members of parliament if they entered the auditorium in the following order: 10, 5, 1, 7, 20, 25, 22, 21, 27.
During its first session the parliament decided not to change the seats in the future.
The speech order was also adopted. If the number of the session was odd then the members of parliament spoke in the following order: the left wing, the right wing and the chairman. If a wing had more than one parliamentarian then their speech order was the same: the left wing, the right wing, and the wing chairman. If the number of the session was even, the speech order was different: the right wing, the left wing, and the chairman. For a given example the speech order for odd sessions will be 1, 7, 5, 21, 22, 27, 25, 20, 10; while for even sessions — 27, 21, 22, 25, 20, 7, 1, 5, 10.
Determine the speech order for an even session if the speech order for an odd session is given.
*******InputConstraints*******
The first line of the input contains N, the total number of parliamentarians. The following lines contain N integer numbers, the identification numbers of the members of parliament according to the speech order for an odd session.
The total number of the members of parliament does not exceed 3000. Identification numbers do not exceed 65535.
*******OutputConstraints*******
The output should contain the identification numbers of the members of parliament in accordance with the speech order for an even session.
*******IOTestCases*******
input  output 

9
1 7 5 21 22 27 25 20 10
 27 21 22 25 20 7 1 5 10

______________________________________________________
1137true
Several bus routes were in the city of Fishburg. None of the routes shared the same section of road, though common stops and intersections were possible. Fishburg old residents stated that it was possible to move from any stop to any other stop (probably making several transfers). The new mayor of the city decided to reform the city transportation system. He offered that there would be only one route going through all the sections where buses moved in the past. The direction of movement along the sections must be the same and no additional sections should be used.
Write a program, which creates one of the possible new routes or finds out that it is impossible.
*******InputConstraints*******
The first line of the input contains the number of old routes n. Each of the following n lines contains the description of one route: the number of stops m and the list of that stops. Bus stops are identified by positive integers not exceeding 10000. A route is represented as a sequence of m + 1 bus stop identifiers: l_{1}, l_{2}, …, l_{m}, l_{m+1} = l_{1} that are sequentially visited by a bus moving along this route. A route may be selfintersected. A route always ends at the same stop where it starts (all the routes are circular).
The number of old routes: 1 ≤ n ≤ 100.
The number of stops: 1 ≤ m ≤ 1000.
The numberidentifier of the stop: 1 ≤ l ≤ 10000.
*******OutputConstraints*******
The output contains the number of stops in the new route k and the new route itself in the same format as in the input. The last (k+1)th stop must be the same as the first. If it is impossible to make a new route according to the problem statement then write 0 (zero) to the output.
*******IOTestCases*******
input  output 

3
6 1 2 5 7 5 2 1
4 1 4 7 4 1
5 2 3 6 5 4 2
 15 2 5 4 2 3 6 5 7 4 1 2 1 4 7 5 2

Hint
Here is a picture for the example:
______________________________________________________
1138true
Applying for a new job, programmer N. Smart required that his new salary (in rubles, positive integer) would be greater than his previous salary by integer percentage. What could be the highest possible number of previous jobs for mister Smart, if his latest salary did not exceed n rubles and his first salary was exactly s rubles?
Example. Let n = 10, s = 2, then m = 5. The sequence 2, 4 (+100%), 5 (+25%), 8 (+60%), 10 (+25%) is the longest (although not unique) sequence that satisfies to the problem statement. Salary increase percentage is written inside the brackets.
*******InputConstraints*******
Two integers n and s separated by one or more spaces. 1 ≤ n, s ≤ 10000.
*******OutputConstraints*******
A single integer m — the maximum number of N. Smart’s previous jobs.
*******IOTestCases*******
Hint
if n = s, the answer is 1.
______________________________________________________
1139true
The blocks in the city of Fishburg are of square form. N avenues running south to north and M streets running east to west bound them. A helicopter took off in the most southwestern crossroads and flew along the straight line to the most northeastern crossroads. How many blocks did it fly above?
Note. A block is a square of minimum area (without its borders).
*******InputConstraints*******
The input contains N and M separated by one or more spaces.
1 < N, M < 32000.
*******OutputConstraints*******
The number of blocks the helicopter flew above.
*******IOTestCases*******
Hint
______________________________________________________
1140true
An attempt was made to count all the cranberries in the swamps located in the surroundings of Rybinsk. It appeared convenient to split the surface of the swamp into regular hexagonal cells. One of these cells was considered as the central one, where the helicopter hovered. Three directions were marked (see picture).
After that a hired student landed in the central cell and wandered around for a certain time. He counted the berries and recorded his movements as he walked. Movements were recorded as a sequence of transitions from one cell to another through their common side along one of the marked (or reverse) directions. The route consisted of linear sections determined by directions (X, Y, or Z) and lengths (signed nonzero integers). A movement in the marked direction is represented with positive numbers, in the reverse direction — with negative numbers.
Your task is to write a program, which determines a route from the last cell visited by the student back to the central cell, having the least possible number of cells in it.
*******InputConstraints*******
The first line of the input contains n — the length of the route (n > 0).
Each of the following n lines contains a letter denoting a direction (X, Y, or Z) and a signed integer l (l ≠ 0) denoting the length of the section (in cells). The letter and the number are separated by one space.
While wandering, the student moved away from the central cell for no more than 100 cells in each of marked and reverse directions. The total length of the route does not exceed 32000 linear sections.
*******OutputConstraints*******
The output must contain the description of a route from the last cell visited by the student back to the central cell, having the least possible number of cells in it.
The first line of the output must contain m — the length of the route (number of sections in the back route, m ≥ 0).
The following m lines of the output must contain the description of the sections of the back route in the same format as in the input.
*******IOTestCases*******
input  output 

4
Z 2
Y 3
Z 3
X 1
 2
Y –2
Z –2

______________________________________________________
1141true
The RSA problem is the following: given a positive integer n that is a product of two distinct odd primes p and q, a positive integer e such that gcd(e, (p1)*(q1)) = 1, and an integer c, find an integer m such that m^{e} = c (mod n).
*******InputConstraints*******
One number K (K <= 2000) in the first line is an amount of tests. Each next line represents separate test, which contains three positive integer numbers – e, n and c (e, n, c <= 32000, n = p*q, p, q – distinct odd primes, gcd(e, (p1)*(q1)) = 1, e < (p1)*(q1) ).
*******OutputConstraints*******
For each input test the program must find the encrypted integer m.
*******IOTestCases*******
input  output 

3
9 187 129
11 221 56
7 391 204
 7
23
17

______________________________________________________
1142true
Background
Consider a specific set of comparable objects. Between two objects a and b, there exits one of the following three classified relations:
Because relation '=' is symmetric, it is not repeated above.
So, with 3 objects (a, b, c), there can exist 13 classified relations:
a = b = c a = b < c c < a = b a < b = c
b = c < a a = c < b b < a = c a < b < c
a < c < b b < a < c b < c < a c < a < b
c < b < a
Problem
Given N, determine the number of different classified relations between N objects.
*******InputConstraints*******
Includes many integers N (in the range from 2 to 10), each number on one line. Ends with −1.
*******OutputConstraints*******
For each N of input, print the number of classified relations found, each number on one line.
*******IOTestCases*******
______________________________________________________
1143true
Background
At the team competition of the 10th national student informatics Olympic, which is organized at Hanoi National University, there are N teams participating. Each team is assigned to work in a camp. On the map, it can be seen that the camps are
positioned on the vertices of a convex polygon with N vertices: P_{1}, P_{2}, …, P_{N} (the vertices are enumerated around the polygon in counterclockwise order.) In order to achieve absolute safety providing electricity to the camps, besides an electric supplying system, the host organization set up a path from a reserved electricity
generator (which is placed in one of the camps) to every camp once, and the
path's total length is minimum.
Problem
Given the coordinates of the polygons' vertices (the camps' positions), determine the length of the electric path corresponding to the host organization's arrangement.
*******InputConstraints*******

The first line contains the positive integer N (1 ≤ N ≤ 200);

The i'th line of the next N lines contains two real numbers x_{i}, y_{i}, separated by a space, with no more than 3 digits after the decimal points, are vertex P_{i}'s coordinates on the plane (with i = 1, 2, …, N). The length of the path connecting two vertex (x_{i}, y_{i}) and (x_{j}, y_{j}) is computed with the formula: sqrt((x_{i} − x_{j})^{2} + (y_{i} − y_{j})^{2}).
*******OutputConstraints*******
The only line should contain real number L (written in real number format, with 3 digits after the decimal point), which is the total length of the electric path.
*******IOTestCases*******
input  output 

4
50.0 1.0
5.0 1.0
0.0 0.0
45.0 0.0
 50.211

______________________________________________________
1144true
Background
In the olden times there was a young emperor who was the bravest, wisest, richest, most handsome in the whole world. He had proven himself in endless of battles, quests, and victories but his court was not happy because he had not appointed a queen yet. However, choosing a queen was not easy because of his high status and standard, the emperor wanted a girl not only beautiful but smart and kind as well. Lightning Knight  that was the young Emperor's name  sent his most trusted knights out to seek for a girl like that; and after a long time searching, the men brought back two of the most beautiful and intelligent girls in all the lands. They were two princess sisters from a faraway land. The older sister  Van Trinh  was mysterious and beautiful like the moon, while Thuy Linh  the younger one  was bright and lovely as the sun. They were both famous for being kind, gentle, and intelligent to their people, and as many girls before them, they both fell truly, madly, deeply in
love with the handsome emperor at first sight.
Now, the Emperor had to face the hardest test of all: to pick just one in these two
sisters to become his rightful and beloved queen and lay the world under her feet. After countless sleepless nights, the Emperor sought out a just solution. He thought of a riddle and announced to the two princesses and the court that he would marry the first one who bring the right answer to his desk.
Problem
At the same time with the above event, the Emperor had just won the most important battle to unite all the lands in the world. That was two good news in such a short time. Being the rich and generous emperor he was, the Emperor wanted to reward to all the brave and loyal generals with boxes of gold. The distribution was not easy and that's why he chose it as the riddle for Van Trinh and Thuy Linh. Centuries has passed since then, the Emperor and queen might have died and their romance might have been forgotten from our world, but the riddle still remains as one of the hardest tasks in the ancient books.
The Emperor wants to reward N boxes of gold to M generals. The ith box has the value of A_{i}. Now the Emperor wants to give N boxes to M generals so that the difference of gold between the general who receives the most gold and the general who receives the least gold is as small as possible. Note: a general can receive more than one box, and he must receive the whole box (i.e.: not half or 1/3 of box).
*******InputConstraints*******
Contains two lines:
 The 1st line contains three positive
integers N, M and K (N ≤ 10000, M ≤ 1000 and N ≥ M). K is the
maximum result that the emperor accepts.
 The 2nd line contains N positive
integers 0 < A_{1}, A_{2}, …, A_{N} ≤ 1000.
*******OutputConstraints*******
 The 1st line contains one integer which is the minimum
difference your program can find.
 In the next M lines, the ith line contains the index of
boxes rewarded to the ith general.
*******IOTestCases*******
input  output 

10 3 4
12 95 16 37 59 50 47 3 41 95
 4
6 7 9 1
8 10 4 3
5 2

______________________________________________________
1145true
A labyrinth with rectangular form and size m × n is divided into square cells with sides' length 1 by lines that are parallel with the labyrinth's sides. Each cell of the net is either forbidden or free. It is possible to move from one free cell to other free cells that share a common side with the cell. One cannot move beyond the labyrinth's borders. The labyrinth is designed pretty specially: for any 2 cells, there is only one way to move from one cell to the other. At each cell's center, there is always a hook. In the labyrinth, there are 2 special free cell, such that if you can connect the hooks of those 2 cells with a rope, the labyrinth's secret door will be automatically openned. The problem is to prepare a shortest rope that can guarantee at any position in the labyrinth, you always can connect the hooks of those 2 cells with the prepared rope.
*******InputConstraints*******
 The first line contains two numbers n, m (3 ≤ n, m ≤ 820).
 The next lines describe the labyrinth. The ith line of the next m lines contains
n characters. Each character is either "#" or ".", with
"#" indicating a forbidden cell, and "." indicating a
free cell (i = 1, 2, …, m).
*******OutputConstraints*******
Print out on one line the length (measured in the number of cells) of the needed rope.
*******IOTestCases*******
input  output 

7 6
#######
#.#.###
#.#.###
#.#.#.#
#.....#
#######
 8

______________________________________________________
1146true
Given a 2dimensional array of positive and negative integers, find the subrectangle with the largest sum. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the subrectangle with the largest sum is referred to as the maximal subrectangle. A subrectangle is any contiguous subarray of size 1 × 1 or greater located within the whole array.
As an example, the maximal subrectangle of the array:
0 
−2 
−7 
0 
9 
2 
−6 
2 
−4 
1 
−4 
1 
−1 
8 
0 
−2 
is in the lowerlefthand corner and has the sum of 15.
*******InputConstraints*******
The input consists of an N × N array of integers.
The input begins with a single positive integer N on a line by itself
indicating the size of the square two dimensional array. This is followed by
N^{ 2} integers separated by whitespace (newlines and spaces).
These N^{ 2} integers make up the array in rowmajor order (i.e., all numbers on the first row, lefttoright, then all numbers on the second row, lefttoright, etc.). N may be as large as 100. The numbers in the array will be in the range [−127, 127].
*******OutputConstraints*******
The output is the sum of the maximal subrectangle.
*******IOTestCases*******
input  output 

4
0 2 7 0
9 2 6 2
4 1 4 1
1 8 0 2
 15

______________________________________________________
1147true
N opaque rectangles (1 ≤ N ≤ 1000) of various colors are placed on a white sheet of paper whose size is A wide by B long. The rectangles are put with their sides parallel to the sheet's borders. All rectangles fall within the borders of the sheet so that different figures of different colors will be seen.
The coordinate system has its origin (0, 0) at the sheet's lower left corner with axes parallel to the sheet's borders.
*******InputConstraints*******
The order of the input lines dictates the order of laying down the rectangles. The first input line is a rectangle “on the bottom”.
 First line contains A, B and N, space separated (1 ≤ A, B ≤ 10000).
 Lines 2, …, N + 1 contain five integers each: llx, lly, urx, ury,
color: the lower left coordinates and upper right coordinates of the
rectangle whose color is color (1 ≤ color ≤ 2500) to be placed
on the white sheet. The color 1 is the same color of white as the sheet
upon which the rectangles are placed.
*******OutputConstraints*******
The output should contain a list of all the colors that can be seen along with the total area of each color that can be seen (even if the regions of color are disjoint), ordered by increasing color. Do not display colors with no area.
*******IOTestCases*******
input  output 

20 20 3
2 2 18 18 2
0 8 19 19 3
8 0 10 19 4
 1 91
2 84
3 187
4 38

______________________________________________________
1148true
There are N bricks in a toy box which have 1unit height and 2unit width. The teacher organizes a towerbuilding game. The tower is built of the bricks. The tower consists of H levels. The bottom level contains M bricks, every next level must contain exactly one brick less or greater than the level just below it.
Here is an example of a tower with H=6, M=2, N=13.
The tower with H levels can be represented by the array of H integers, which are the numbers of bricks in each level from the bottom to the top. Consider all different towers with exactly H levels and exactly M bricks in the bottom level that can be built using not more than N bricks. We can number these towers in such way that corresponding arrays will be ordered lexicographically.
Your task is to find a tower with specific number in the sense of described order.
*******InputConstraints*******
The first line of the input contains positive numbers N, H and M (N ≤ 32767, H ≤ 60, M ≤ 10). Each of the following lines contains integer K, which is the interested tower number. The last line contains number 1. The towers are numbered starting from 1.
*******OutputConstraints*******
The first line of the output should contain the total number of different towers that can be built. Each following line should contain an array describing the tower with number K given in respective line of input. The numbers in the arrays should be separated by at least one space.
*******IOTestCases*******
input  output 

22 5 4
1
10
1
 10
4 3 2 1 2
4 5 4 5 4

______________________________________________________
1149true
Let A_{n} = sin(1–sin(2+sin(3–sin(4+…sin(n))…)
Let S_{n} = (…(A_{1}+n)A_{2}+n–1)A_{3}+…+2)A_{n}+1
For given N print S_{N}
*******InputConstraints*******
One integer N. 1 ≤ N ≤ 200
*******OutputConstraints*******
*******IOTestCases*******
input  output 

3  ((sin(1)+3)sin(1–sin(2))+2)sin(1–sin(2+sin(3)))+1 
______________________________________________________
1150true
John Smith has decided to number the pages in his notebook from 1 to N. Please, figure out the number of zeros, ones, twos, …, nines he might need.
*******InputConstraints*******
One number N (1 ≤ N < 10^{9}).
*******OutputConstraints*******
Output 10 lines. The first line should contain the number of zeros needed, the second line should contain the number of ones needed, …, the tenth line should contain the number of nines needed.
*******IOTestCases*******
input  output 

12  1
5
2
1
1
1
1
1
1
1

______________________________________________________
1151true
N radiobeacons are located on the plane. Their exact positions are unknown but we know that N ≤ 10 and that their coordinates are integers from 1 to 200. Each beacon produces unique signal, that distinguishes it from the other beacons.
In some different places, we should call them checkpoints, coordinates of which are well known, there were conducted measurements. As a result of these measurements distances from checkpoints to some of beacons became known. Here we should note, that the distance between points A and B equals max(A_{x} − B_{x}, A_{y} − B_{y}).
You need to get positions of all beacons basing on coordinates of the checkpoints and results of measurements, if that is possible.
*******InputConstraints*******
First line contains an integer M, the number of checkpoints. 1 ≤ M ≤ 20. Then M lines follow, each of them contains an information received from one of the checkpoints, formatted as follows:
<X_{i}>,<Y_{i}>:<ID_{1}><R_{1}>[,<ID_{2}><R_{2}>][,…]
where X_{i}, Y_{i} are coordinates of checkpoints, ID_{k} is ID of beacon k, R_{k} is a distance from checkpoint i to beacon k. Coordinates of checkpoints are integers from 1 to 200. Each checkpoint measures at least one signal. IDs of beacons are integers from 1 to 30000.
*******OutputConstraints*******
Output N lines, which should look as follows:
<ID_{k}>:<x_{k}>,<y_{k}>  UNKNOWN
Here x_{k} and y_{k} are coordinates of k'th beacon on the field. If a position of some beacon cannot be determined unambiguously, its coordinates should be replaced with a word “UNKNOWN”. All lines should be ordered by ID_{k} in an ascending order.
*******IOTestCases*******
input  output 

2
15,15:167,53
10,10:52,162
 5:12,12
16:UNKNOWN

______________________________________________________
1152true
Background
We wandered in the labyrinth for twenty minutes before finally entering the large hall. The walls were covered by mirrors here as well. Under the ceiling hung small balconies where monsters stood. I had never seen this kind before. They had big bulging eyes, long hands firmly holding riffles and scaly, humanlike bodies. The guards fired at me from the balconies, I shot back using my BFG9000. The shot shattered three mirrors filling the room with silvery smoke. Bullets drummed against my bodyarmor knocking me down to the floor. Falling down I let go a shot, and got up as fast as I fell down by rotating on my back, like I did in my youth while break dancing, all this while shooting three more times. Three mirrors, three mirrors, three mirrors…
Sergey Lukjanenko, “The Labyrinth of Reflections”
Problem
BFG9000 destroys three adjacent balconies per one shoot. (Nth balcony is adjacent to the first one). After the shoot the survival monsters inflict damage to Leonid (main hero of the novel) — one unit per monster. Further follows new shoot and so on until all monsters will perish. It is required to define the minimum amount of damage, which can take Leonid.
*******InputConstraints*******
The first line contains integer N, аmount of balconies, on which monsters have taken a circular defense. 3 ≤ N ≤ 20. The second line contains N integers, amount of monsters on each balcony (not less than 1 and no more than 100 on each).
*******OutputConstraints*******
Output minimum amount of damage.
*******IOTestCases*******
input  output 

7
3 4 2 2 1 4 1
 9

______________________________________________________
1153true
To check the speed of JCN Corporation new supercomputer it was decided to figure out the sum of first N (N < 10^{600}) positive integers. Unfortunately, by the time the calculation was finished the Chief Programmer forgot the value of N he entered. Your task is to write the program (for personal computer), which would determine the value of N by the result calculated on supercomputer.
Note: JCN Corporation manufactures only reliable computers, and its programmers write only correctly working programs.
*******InputConstraints*******
One line containing the result of calculations on the supercomputer.
*******OutputConstraints*******
Выведите N, the number entered by Chief Programmer.
*******IOTestCases*******
______________________________________________________
1154true
The Powers of Light and the Powers of Darkness had gathered the best elemental mages of the Middleearth: the Lords of Fire, Earth, Air and Water.
Sometime during 24 hours there exists the Moment of Power for each one of the elements, when the mastery of corresponding mage is in its maximum point. In contrary there exists the Moment of Weakness, when the mastery of the mage is minimum. In between these moments the mage's mastery changes linearly.
There can be several mages fighting on each side. The mages cumulative mastery is defined as sum of their individual masteries. The win is given to the side, which mages' cumulative mastery is the largest. The larger the advantage of one side over another, the easier its win is, and the smaller casualties are.
The Supreme Master, who is to declare the time of the Contest secretly wishes the Powers of Light to win, and tries to make this win as easy as possible. Assume that the Contest is held momentary, and the mastery of the mages doesn't change during it. You are to help the Supreme Master in selecting the time of the Contest.
*******InputConstraints*******
The first four lines contain information about the Moments of Weakness and the Moments of Power for mages of each of the elements. Each line contains five parameters separated by spaces: element code, the time of the Moment of Power, the mastery in the Moment of Power, the time of the Moment of Weakness, the mastery in the Moment of Weakness.
Element code is one of four capital letters: “A” for Air, “E” for Earth, “F” for Fire and “W” for Water. The time is HH:MM:SS formatted and lies between 00:00:00 and 23:59:59. The Moment of Power is not equal to the Moment of Weakness. The mastery in these moments is a positive integer less than or equal to 10000.
Then two more lines follow, which determine respectively the cast of the Powers of Light and the cast of the Powers of Darkness. Each line consists of symbols “A”, “E”, “F”, “W” representing one mage of the corresponding element. The number of the mages from each side is not less than 1 and is not greater than 1000.
*******OutputConstraints*******
The first line should contain HH:MM:SS formatted time of the Contest. In the second line there should be one number with two decimal points, which represents the advantage of the Powers of Light over the Powers of Darkness. The time of the Contest should lie between 00:00:00 and 23:59:59. If there exist several moments can be chosen as the time of the Contest, then choose the earliest one.
If there is no way the Powers of Light can win, then write “We can't win!”
*******IOTestCases*******
input  output 

A 10:00:00 130 18:00:00 40
E 14:00:00 150 21:30:00 25
F 06:00:00 105 18:00:00 70
W 23:00:00 140 02:00:00 20
A
WWW
 02:00:00
25.00

A 10:00:00 130 18:00:00 40
E 14:00:00 150 21:30:00 25
F 06:00:00 105 18:00:00 70
W 23:00:00 140 02:00:00 20
A
WWWF
 We can't win! 
______________________________________________________
1155true
Archangel of the Science is reporting:
“O, Lord! Those physicists on the Earth have discovered a new elementary particle!”
“No problem, we’ll add another parameter to the General Equation of the Universe.”
As physics develops and moves on, scientists find more and more strange elementary particles, whose properties are more than unknown. You may have heard about muons, gluons and other strange particles. Recently scientists have found new elementary particles called troubleduons. These particles are called this way because scientists can create or annihilate them only in couples. Besides, troubleduons cause trouble to scientists, and that’s why the latter want to get rid of them. You should help scientists get rid of troubleduons.
Experimental set consists of eight cameras, situated in the vertices of a cube. Cameras are named as A, B, C, …, H. It is possible to generate or annihilate two troubleduons in neighbouring cameras. You should automate the process of removing troubleduons.
*******InputConstraints*******
The only line contain eight integers ranging from 0 to 100, representing number of troubleduons in each camera of experimental set.
*******OutputConstraints*******
Output sequence of actions leading to annihilating all troubleduons or “IMPOSSIBLE”, if you cannot do it. Actions should be described one after another, each in a separate line, in the following way: name of the first camera, name of the second camera (it should be a neighborough to the first one), “+” if you create troubleduons, “” if you destroy them. Number of actions in the sequence should not exceed 1000.
*******IOTestCases*******
input  output 

1 0 1 0 3 1 0 0  EF
EA
AD+
AE
DC

0 1 0 1 2 3 2 2  IMPOSSIBLE 
______________________________________________________
1156true
There are two rounds in the Urals Championship. The competitors have to solve N problems on each round. The jury had been working hard and finally managed to prepare 2N problems for the championship. But it appeared that among those problems there were some, which have the analogous solutions. One shouldn’t assign such a problems for the same round. Please, help the jury form sets of tasks for each of the rounds.
*******InputConstraints*******
First line contains two numbers: N, the number of tasks for a round, and M, the number of pairs of tasks which should not be assigned for one round (1 ≤ N ≤ 50; 0 ≤ M ≤ 100). Then M lines follow, each of them contains two numbers of analogous tasks.
*******OutputConstraints*******
Output two lines, containing numbers of tasks assigned for each round. If there is no solution, output the only word “IMPOSSIBLE”. If there are more than one solution you may assume anyone of them.
*******IOTestCases*******
input  output 

2 3
1 3
2 1
4 3
 1 4
2 3

______________________________________________________
1157true
One young boy had manymany identical square tiles. He loved putting all his tiles to form a rectangle more, than anything in the world — he has learned the number of all rectangles he can form using his tiles. On his birthday he was presented a number of new tiles. Naturally, he started forming rectangles from these tiles — the thing he loved most of all! Soon he has learned all rectangles he could form with a new number of tiles.
Here we should notice that boy can easily count the number of rectangles, but he has difficulty counting the number of tiles — there are too much of them for such a young boy. But it will not be difficult for you to determine how many tiles he has now, knowing how many rectangles he could form before, how many rectangles he can form now, and how many tiles he got as a birthday present.
You are given numbers M, N and K. You should find the smallest number L, such as you can form N different rectangles using all L tiles, and form M rectangles using L − K tiles.
*******InputConstraints*******
One line containing three integers: M, N, K (1 ≤ M, N, K ≤ 10000).
*******OutputConstraints*******
If L is less than or equal to 10000, then print that number (if there is a number of such L, you should print the smallest one). If there is no solution or smallest L is greater than 10000, print 0.
*******IOTestCases*******
______________________________________________________
1158true
The alphabet of Freeland consists of exactly N letters. Each sentence of
Freeland language (also known as Freish) consists of exactly M letters
without word breaks. So, there exist exactly N^{M} different Freish
sentences.
But after recent election of Mr. Grass Jr. as Freeland president some words offending him were declared unprintable and all sentences containing at least one of them were forbidden. The sentence S contains a word W if W is a substring of S i.e. exists
such k >= 1 that S[k] = W[1], S[k+1] = W[2], ... , S[k+len(W)1] = W[len(W)], where k+len(W)1 <= M and len(W) denotes length of W. Everyone who uses a forbidden sentence is to be put to jail for 10 years.
Find out how many different sentences can be used now by freelanders without risk to be put to jail for using it.
*******InputConstraints*******
The first line contains three integer numbers: N  the number of letters in Freish alphabet, M  the length of all Freish sentences and P  the number of forbidden words (1 ≤ N ≤ 50, 1 ≤ M ≤ 50, 0 ≤ P ≤ 10).
The second line contains exactly N different characters  the letters of the Freish alphabet (all with ASCII code greater than 32).
The following P lines contain forbidden words, each not longer than min(M, 10) characters, all containing only letters of Freish alphabet.
*******OutputConstraints*******
Output the only integer number  the number of different sentences freelanders can safely use.
*******IOTestCases*******
input  output 

3 3 3
QWE
QQ
WEE
Q  7 
______________________________________________________
1159true
Workers are going to enclose a new working region with a fence. For their convenience the enclosed area has to be as large as possible. They have N rectangular blocks to build the fence. The length of the ith block is L_{i} meters. All blocks have the same height of 1 meter. The workers are not allowed to break blocks into parts. All blocks must be used to build the fence.
*******InputConstraints*******
The first line contains one integer N (3 ≤ N ≤ 100). The following N lines describe fence blocks. Each block is represented by its length in meters (integer number, 1 ≤ L_{i} ≤ 100).
*******OutputConstraints*******
Write one nonnegative number S  maximal possible area of the working region (in square meters). S must be written with two digits after the decimal point. If it is not possible to construct the fence from the specified blocks, write 0.00.
*******IOTestCases*******
input  output 

4
10
5
5
4  28.00 
______________________________________________________
1160true
Andrew is working as system administrator and is planning to establish a new network in his company. There will be N hubs in the company, they can be connected to each other using cables. Since each worker of the company must have access to the whole network, each hub must be accessible by cables from any other hub (with possibly some intermediate hubs).
Since cables of different types are available and shorter ones are cheaper, it is necessary to make such a plan of hub connection, that the maximum length of a single cable is minimal. There is another problem  not each hub can be connected to any other one because of compatibility problems and building geometry limitations. Of course, Andrew will provide you all necessary information about possible hub connections.
You are to help Andrew to find the way to connect hubs so that all above conditions are satisfied.
*******InputConstraints*******
The first line contains two integer: N  the number of hubs in the network (2 ≤ N ≤ 1000) and M — the number of possible hub connections (1 ≤ M ≤ 15000). All hubs are numbered from 1 to N. The following M lines contain information about possible connections  the numbers of two hubs, which can be connected and the cable length required to connect them. Length is a positive integer number that does not exceed 10^{6}. There will be no more than one way to connect two hubs. A hub cannot be connected to itself. There will always be at least one way to connect all hubs.
*******OutputConstraints*******
Output first the maximum length of a single cable in your hub connection plan (the value you should minimize). Then output your plan: first output P  the number of cables used, then output P pairs of integer numbers  numbers of hubs connected by the corresponding cable. Separate numbers by spaces and/or line breaks.
*******IOTestCases*******
input  output 

4 6
1 2 1
1 3 1
1 4 2
2 3 1
3 4 1
2 4 1  1
4
1 2
1 3
2 3
3 4 
______________________________________________________
1161true
Our chemical biologists have invented a new very useful form of life called stripies (in fact, they were first called in Russian  polosatiki, but the scientists had to invent an English name to apply for an international patent). The stripies are transparent amorphous amebiform creatures that live in flat colonies in a jellylike nutrient medium. Most of the time the stripies are moving. When two of them collide a new stripie appears instead of them. Long observations made by our scientists enabled them to establish that the weight of the new stripie isn't equal to the sum of weights of two disappeared stripies that collided; nevertheless, they soon learned that when two stripies of weights m_{1} and m_{2} collide the weight of resulting stripie equals to 2·sqrt(m_{1}m_{2}). Our chemical biologists are very anxious to know to what limits can decrease the total weight of a given colony of stripies.
You are to write a program that will help them to answer this question. You may assume that 3 or more stipies never collide together.
*******InputConstraints*******
The first line contains one integer N (1 ≤ N ≤ 100)  the number of stripies in a colony. Each of next N lines contains one integer ranging from 1 to 10000  the weight of the corresponding stripie.
*******OutputConstraints*******
The output must contain one line with the minimal possible total weight of colony with the accuracy of two decimal digits after the point.
*******IOTestCases*******
input  output 

3
72
30
50  120.00 
______________________________________________________
1162true
Several currency exchange points are working in our city. Let us suppose that each point specializes in two particular currencies and performs exchange operations only with these currencies. There can be several points specializing in the same pair of currencies. Each point has its own exchange rates, exchange rate of A to B is the quantity of B you get for 1A. Also each exchange point has some commission, the sum you have to pay for your exchange operation. Commission is always collected in source currency.
For example, if you want to exchange 100 US Dollars into Russian Rubles at the exchange point, where the exchange rate is 29.75, and the commission is 0.39 you will get (100  0.39) * 29.75 = 2963.3975RUR.
You surely know that there are N different currencies you can deal with in our city. Let us assign unique integer number from 1 to N to each currency. Then each exchange point can be described with 6 numbers: integer A and B  numbers of currencies it exchanges, and real RAB, CAB, RBA and CBA  exchange rates and commissions when exchanging A to B and B to A respectively.
Nick has some money in currency S and wonders if he can somehow, after some exchange operations, increase his capital. Of course, he wants to have his money in currency S in the end. Help him to answer this difficult question. Nick must always have nonnegative sum of money while making his operations.
*******InputConstraints*******
The first line contains four numbers: N  the number of currencies, M  the number of exchange points, S  the number of currency Nick has and V  the quantity of currency units he has. The following M lines contain 6 numbers each  the description of the corresponding exchange point  in specified above order. Numbers are separated by one or more spaces. 1 ≤ S ≤ N ≤ 100, 1 ≤ M ≤ 100, V is real number, 0 ≤ V ≤ 10^{3}.
For each point exchange rates and commissions are real, given with at most two digits after the decimal point, 10^{2} ≤ rate ≤ 10^{2}, 0 ≤ commission ≤ 10^{2}.
Let us call some sequence of the exchange operations simple if no exchange point is used more than once in this sequence. You may assume that ratio of the numeric values of the sums at the end and at the beginning of any simple sequence of the exchange operations will be less than 10^{4}.
*******OutputConstraints*******
If Nick can increase his wealth, output YES, in other case output NO.
*******IOTestCases*******
input  output 

3 2 1 20.0
1 2 1.00 1.00 1.00 1.00
2 3 1.10 1.00 1.10 1.00  YES 
______________________________________________________
1163true
Legendary divisional commander Vasiliy I. Chapaev was fond of playing this beautiful game with his aidedecamp Petka during their (scanty) spare time. The game is played as follows. There are eight white and eight red draughts on the board at the beginning of the game. The red side starts the game by making the first turn. The turn consists of selecting an arbitrary draught of player’s colour and pushing it with a flick into a certain direction. Then this draught begins to move in this direction until it completely falls off the board. If it hits or even just touches another draught of any colour during the movement, the latter is immediately removed from the board being considered killed. In any case the moving draught continues its movement without changing its speed or direction. After the moving draught has completed its movement across the board (has fallen off) the other player has to make his turn. If there are no draughts of player’s colour left he is considered to lose the game.
The historians have a record of an initial position in one of such games. Unfortunately, the result of this game is unknown. Your task is to establish the truth taking for granted that both Chapaev and Petka always used the optimal strategy.
*******InputConstraints*******
Each of two lines contains eight pairs of numbers  the coordinates of centres of red and white draughts respectively. The draughts are considered to be cylinders of radius 0.4 and height 0.15. The coordinates are calculated so that the board is a square 8x8 with vertices (0, 0), (0, 8), (8, 0) and (8, 8). There will be no draught that overlaps or touches another one. Also each piece in the initial position is completely contained within the limits of the board.
*******OutputConstraints*******
Output RED or WHITE corresponding to the winning side.
*******IOTestCases*******
input  output 

0.5 7.5 1.5 7.5 2.5 7.5 3.5 7.5 4.5 7.5 5.5 7.5 6.5 7.5 7.5 7.5
0.5 0.5 1.5 0.5 2.5 0.5 3.5 0.5 4.5 0.5 5.5 0.5 6.5 0.5 7.5 0.5  RED 
______________________________________________________
1164true
Alex likes solving fillwords. Fillword is a word game with very simple rules. The author of the fillword takes rectangular grid (M cells width, N cells height) and P words. Then he writes letters in the cells of the grid (one letter in one cell) so that each word can be found on the grid and the following conditions are met:
 no cell belongs to more than one word
 no cell belongs to any word more than once
Some word W (let us consider its length being k) is found on the grid if you can find such sequence of cells (x
_{1}, y
_{1}), (x
_{2}, y
_{2}), …, (x
_{k}, y
_{k}) that:
 (x_{i}, y_{i}) and (x_{i+1}, y_{i+1}) are neighbors (x_{i}x_{i+1} + y_{i}y_{i+1} = 1) for each i = 1, 2, …, k1
 W[i] is written in the cell with coordinates (x_{i}, y_{i}).
The task is to find all the words on the grid. After they are found, you see that the letters in some cells are not used (they do not belong to any found word). You make up a secret word using these letters and win a big prize.
Your task is to help Alex to solve fillwords. You should find out which letters will be left after he finds all the words on the grid. The most difficult task  to make up a secret word out of them  we still reserve to Alex.
*******InputConstraints*******
The first line contains three integers  N, M (2 ≤ M, N ≤ 10) and P (P ≤ 100). Next N lines contain M characters each, and represent the grid. The following P lines contain words that are to be found on the fillword grid.
Fillword will always have at least one solution. All characters occurring in fillword will be capital English letters.
*******OutputConstraints*******
Output letters from, which a secret word should be made up. Letters should be output in lexicographical order.
*******IOTestCases*******
input  output 

3 3 2
EBG
GEE
EGE
BEG
GEE  EEG 
______________________________________________________
1165true
George likes arithmetics very much. Especially he likes the integers series. His most favourite thing is the infinite sequence of digits, which results as the concatenation of all positive integers in ascending order. The beginning of this sequence is 1234567891011121314… Let us call this sequence S. Then S[1] = 1, S[2] = 2, …, S[10] = 1, S[11] = 0, …, and so on.
George takes a sequence of digits A and wants to know when it first appears in S. Help him to solve this difficult problem.
*******InputConstraints*******
The first line contains A  the given sequence of digits. The number of digits in A does not exceed 200.
*******OutputConstraints*******
Output the only number  the least k such that A[1] = S[k], A[2] = S[k+1], ... A[len(A)] = S[k + len(A) – 1], where len(A) denotes the length of A (i.e. the number of digits in it).
*******IOTestCases*******
______________________________________________________
1166true
Of course all of you want to know how to become ACM world champions. There is no exact answer to this question but it is well known that the champions of the last two ACM World Finals enjoyed playing the following funny card game. Two or more players can play this game simultaneously. It is played using a standard 54card deck. At the beginning the players sit forming a circle. One of the players shuffles the deck and then he deals the cards in clockwise order starting from the neighbour on his left. He deals the top card of the deck to the current player each time. He does it until each player gets five cards. Then he takes the top card of the deck and lays it onto the table face up and he also lays the remainder of the deck nearby (these cards are laid face down preserving their original order). The card laid by the shuffler is considered as the first turn of the game (as if it was made by the shuffler to the player on his left).
The normal game flow as following: the player should cover the last laid card with the card of the same suit or value. If he has none, he takes one card from the top of the deck and again checks this condition. If still there are no matching cards, the move will go to the next player (his left neighbour). But for some cards special rules are applied:
 If the laid card is 6, the player takes one card from the top of the deck and skips his turn
 If the laid card is 7, the player takes two cards from the top of the deck (if there is only one card in the deck, he takes just it) and skips his turn
 If the laid card is Ace the player skips his turn without taking any cards
 If the player lays Queen, he himself announces the suit of the card it should be covered with
 Eight is one of the most powerful weapons in this game. When it is laid, the next player has to cover it in any case. If he cannot cover it with his cards he has to take cards from the deck, until he is able to cover it.
 And the most important card in the game is the King of Spades. If it's laid, the next player takes 4 cards from the top of the deck (if there is not enough cards in the deck, he takes all of them) and skips his turn.
You may assume that the deck is looped and the laid cards are immediately moving to the bottom of the deck. So it can happen that the player has to cover the card by itself.
We should say some words about Jokers. Jokers can have any card value by the wish of the player who has it. If the player lays the joker, he assigns a definite card value and suit for it, so this Joker has this assigned value until another player takes it from the deck (if it ever happens). The player is free to use or not to use the Joker whenever he wants (if it is his turn to play, of course).
If the player is left without any cards in his hand, he is considered a winner and the game continues without him (his left neighbour becomes the left neighbour of his right neighbour).
If there is only one player left, he is the looser, so he is called a Japanese Fool (it is a Russian name of this game).
We are interested in the following situation. Consider the moment when only two players are left in the game. If one of them has a special combination of cards, it may happen that he can lay out all his cards in a some sequence so that the other player won't get a move (he'll just have to take cards from the deck and skip turns) and will be the loser — provided the first one finds the winning sequence.
You will be given the position of the game in which only two players are left. Your task will be to determine whether such a winning sequence for the first player exists or not.
We will consider that the first player have already taken all cards from the deck that he had to (if any), so he cannot take any cards from the deck. We will also consider that if the last laid card is a skipturn card, it was the second player who skipped the turn.
*******InputConstraints*******
The first line contains cards of the first player separated by spaces. The second line contains the last laid face up card.
The card description consists of two characters. The first of them corresponds to the card value (29 for digits, T for 10, J for Jack, Q for Queen, K for King and A for Ace). The next describes the suit of the card and may be one of the following: S for Spades, C for Clubs, D for Diamonds or H for Hearts. Joker is represented by a character '*'. If the last laid card is Queen, it is followed by a suit letter. If the last laid card is a joker, then the '*' is followed by an actual card description (the card specified by the player who laid the Joker).
*******OutputConstraints*******
The first line should contain a single word YES or NO signalling whether the winning sequence exists. If the answer is positive the second line must contain the winning sequence of cards separated by spaces. As in the input, the Joker is to be followed by a card specification and the Queen should follow a suit letter. If there is more than one solution you may output an arbitrary one.
*******IOTestCases*******
input  output 

6C QD 6S KS 7S *
*QHS
 YES
7S KS 6S 6C *6D QDS

______________________________________________________
1167true
Every day, farmer Ion (this is a Romanian name) takes out all his horses, so they may run and play. When they are done, farmer Ion has to take all the horses back to the stables. In order to do this, he places them in a straight line and they follow him to the stables. Because they are very tired, farmer Ion decides that he doesn't want to make the horses move more than they should. So he develops this algorithm: he places the 1st P_{1} horses in the first stable, the next P_{2} in the 2nd
stable and so on. Moreover, he doesn't want any of the K stables he owns to be empty, and no horse must be left outside. Now you should know that farmer Ion only has black or white horses, which don't really get along too well. If there are i black horses and j white horses in one stable, then the coefficient of unhappiness of that stable is i*j. The total coefficient of unhappiness is the
sum of the coefficients of unhappiness of every of the K stables.
Determine a way to place the N horses into the K stables, so that the total coefficient of unhappiness is minimized.
*******InputConstraints*******
On the 1st line there are 2 numbers: N (1 ≤ N ≤ 500) and K (1 ≤ K ≤ N). On the next N lines there are N numbers. The ith of these lines contains the color of the ith horse in the sequence: 1 means that the horse is black, 0 means that the horse is white.
*******OutputConstraints*******
You should only output a single number, which is the minimum possible value for the total coefficient of unhappiness.
*******IOTestCases*******
input  output 

6 3
1
1
0
1
0
1
 2

Hint
Place the first 2 horses in the first stable, the next 3 horses in the 2nd stable and the last horse in the 3rd stable.
______________________________________________________
1168true
Along the surface of Romania, there are K radio stations positioned
at different points and altitudes. Each of these radio stations has
a given broadcast radius, that is, the maximum distance it can send
its signal to. The government wants to place a radio receiver somewhere
on the map, so that it will receive the signals from all
the K radio stations: this means that the distance to every radio station
should be less or equal to the broadcast radius of that radio station.
The map of Romania is given as a M*N matrix, where the value
in row i and column j represents the altitude of the corresponding
zone. The side of a square in this matrix is 1. All the
K radio stations are placed at distinct coordinates on the map and
at the same height as the corresponding zone (plus, they are
placed exactly in the center of their square). The radio receiver
can be placed in the center of any square not occupied by a radio station,
at the same altitude of the square or it can be placed higher
with an integer number of meters. The radio receiver cannot
be placed in a square occupied by a radio station.
Your task is to decide how many possibilities to place the radio receiver
the government has. Note that if the radio receiver may be placed in row
i and column j at altitudes h1 and h2 (h1 ≠ h2), this
counts as 2 different possibilities.
*******InputConstraints*******
The first line of input contains 3 integers: M, N (1 ≤
M, N ≤ 50) and K (1 ≤ K ≤ min(M*N1, 1000)),
representing the dimensions of the map and the number of radio
stations. Next there are M lines each containing N integers, which are
the altitudes of the zones on the map (no altitude will be higher than
32000 or lower than 0). After that, there will be K lines, each containing
3 numbers: i, j and R. i and j will be the location of
the radio station on the map and R will be its broadcast radius (R
is a real number, not larger than 100000 and not less than 0).
No two radio stations will be placed on the same square.
*******OutputConstraints*******
You should output one integer number, which is the total number of
valid possibilities to place the radio receiver on the map.
*******IOTestCases*******
input  output 

5 5 3
1 2 3 4 5
6 7 8 9 10
1 2 3 4 5
6 7 8 9 10
5 4 3 2 1
1 1 4.3
5 5 4.3
5 1 4.3
 4

Hint
The radio receiver can be placed at position (3, 2), with extra height 0 and extra height 1, and at position (3, 3), with extra height 0 and extra height 1. So,
there are 4 possible ways to place the receiver.
When you compute distances,
be aware that they are distances in a 3D space.
______________________________________________________
1169true
A Romanian software company has bought N computers, which are going to be connected so that they may form a network. A connection can be made between any 2
distinct computers and is bidirectional (if the 2 computers are labeled i and j, then data can be sent both from i to j and from j to i). Your job is to determine a way to connect all the N computers, in such a way that every 2 computers will be able to send data between them (directly or using other computers as intermediate devices).
There is only one extra requirement: the network must contain exactly K critical pairs. A pair (i, j) is critical if there exists a connection which, if removed, data communication between i and j will become impossible.
*******InputConstraints*******
The input consists of 2 integer numbers: N (1 ≤ N ≤ 100), the number of computers
the network will contain and K (0 ≤ K ≤ N*(N1)/2), the number of critical pairs the network will contain.
*******OutputConstraints*******
You should output the connections which form the network, one connection per line. A connection is described by a pair (i, j), which means that i and j are directly connected. The 2 numbers of the pair should be separated by a blank. If you cannot
build a network which contains exactly K critical pairs, then you should output 1.
*******IOTestCases*******
input  output 

7 12
 1 2
1 3
2 3
3 4
4 5
4 6
4 7
5 6
5 7
6 7

______________________________________________________
1170true
Sergeant Gica (this is a Romanian name) has just been announced that he is going to be sent out in the desert for training. He will have to walk L meters away from the army's headquarters, on a straight line. Since he is a bit lazy and because he has been allowed to pick up his own route, sergeant Gica takes a look at the map of the region. On the map, the army's headquarters are at the coordinates (0, 0). There are also N rectangular regions which have strictly positive coordinates marked on the map. Each rectangle has a given "delay coefficient". This means that the time needed to cross a line segment which is contained inside the rectangle, is equal to the
product between the length of the segment and the delay coefficient of the rectangle. The total time needed to travel all the L meters is equal to the sum of the times needed to travel every segment of the straight line which lies inside the zones marked on the map (including the desert).
Note that the desert (the space between the N rectangular zones) has its own delay coefficient.
*******InputConstraints*******
The 1st line contains N (1 ≤ N ≤ 500), the number of rectangular zones marked on the map. The next N lines contain 5 numbers each: x1 y1 x2 y2 c. (x1, y1) are the coordinates of the lower left corner of the rectangle, (x2, y2) are the coordinates of the upper right corner of the rectangle and c is the delay coefficient of the rectangle. Then there is one more line which contains 2 numbers: c0 (the delay coefficient of the desert) and L (the number of meters sergeant Gica has to travel).
All numbers are positive integers not greater than 32000. L will be larger than the distance from (0, 0) (the headquarters) to any point located on the edges of the
rectangles (this means that the sergeant's "trip" will always end up in the desert and not inside any of the rectangular zones marked on the map).
*******OutputConstraints*******
On the 1st line, you should output the minimum time needed to travel L meters on a straight line, starting from (0, 0) and ending at a point with positive coordinates.
On the 2nd line you should output the coordinates of the point where sergeant Gica should go to (this point must be L meters away from (0, 0) and must have positive coordinates). If there are more solutions with the same minimum time, you may output any one of them.
You should output all 3 numbers with 6 decimal digits.
*******IOTestCases*******
input  output 

1
1 1 2 2 1
2 3
 4.585786
2.121320 2.121320

Hint
The sergeant walks a total of 1.414.. meters inside the rectangular zone and (31.414..) meters outside the zone (through the desert). Thus, the total time is: 1.414..
* 1 + (3  1.414..) * 2.
______________________________________________________
1171true
An astronaut of the RSA (Romanian Space Agency) was "forgotten" on the Nth level
of a Romanian Space Station. He wants to go down to the 1st level, where the communication devices are located, so he can call a space ship to take him home. Unfortunately, the astronaut doesn't know how long the ship will take until it gets to the space station. That's why he wants to gather as much space food as possible before he sends out the message to the ship.
Every level of the space station contains 16 rooms, arranged in 4 rows and 4 columns (numbered accordingly). Every room contains an amount of space food (a number between 1 and 255).
The astronaut may move freely inside the space station, but he is not allowed to visit the same room twice. Moreover, if he went to a lower level, he is not allowed to move back to a higher level. From every room, he could move either north, south, east or west (on the same level) or down (on the same row and column, but at the level below), if there is a door to the level below in that room. For each level, a map is given which tells which rooms have doors to the level below them.
Whenever he enters a room, the astronaut gets the amount of space food found in that room. The food ratio of the astronaut is defined as the total quantity of food
gathered during his trip inside the space station divided by the number of days he spends inside the space station before he sends out the signal to the space ship. It is considered that the astronaut spends the 1st day in the room he begins his trip, on the Nth level, and that he gets the amount of space food found in this room during this day. He is only allowed to move once per day.
You have to find a path from the Nth level to the 1st level, which has the maximum food ratio. Note that the astronaut does not have to call the ship as soon as he gets to a room on the 1st level. He may move around the level first, gather the necessary food and only then call the ship.
*******InputConstraints*******
The first line of input contains a single number: N (1 ≤ N ≤ 16), the number of levels of the space station. For each level, there will be 8 lines of input containing
its description. The first four lines will contain four integers, representing the amount of space food found in the corresponding room on that level (the number found on the jth position on the ith line represents the amount of food in the room found on row i and column j on the level). The next four lines will contain four integers, in the
range 0..1. 1 means that there is a door from that room to the level below, 0 means that there isn't one. Level 1 will have only 0s on these four lines (there is no level below level 1).
The order of the levels in the input will be from top to bottom (from level N to level 1). The last line of input will contain 2 numbers r and c, representing
the row and column of the room the astronaut is initially in, on level N.
*******OutputConstraints*******
On the 1st line, you should output the maximum possible food ratio for the astronaut, with 4 decimal digits. On the 2nd line you should output the length of his path
(print 0 if the astronaut never gets out of the room he is initially found in). If the length of his path is L, L > 0, then on the 3rd line of output you should output L characters: 'N', 'E', 'S', 'W' or 'D', each character corresponding to one direction of movement (north, east, south, west and down). If there are more solutions with the same maximum food ratio, then you may output any of them.
Note that, if L is the length of the astronaut's path, then he spends L+1 days before he calls the space ship.
Every test case is guaranteed to have at least 1 solution.
*******IOTestCases*******
input  output 

2
1 20 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0
1 1 1 1
20 1 1 1
1 1 1 1
1 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
1 1
 8.6000
4
EDSW

______________________________________________________
1172true
A Romanian tourist went on a trip to the Mediterranean Sea. He arrived to one of the cities of the 3 islands he is going to visit. Every island has exactly N
cities and they are all ports. The tourist plans to begin his journey from the city he is in, visit all the other 3*N1 cities exactly once and then return to the starting city so he may go back home after that.
Unfortunately, there are cannibals along the roads on all the 3 islands. That's why travelling on the road between 2 cities on the same island is very dangerous and,
consequently, prohibited. Hopefully, there are always ship routes. Every pair of cities which are not on the same island is connected by such a ship route. There are no routes between cities which are on the same island.
The tourist wants to know in how many ways he can plan his journey through the 3 islands.
*******InputConstraints*******
The input contains a single number: N (1 ≤ N ≤ 30), the number of cities on each of the 3 islands.
*******OutputConstraints*******
You should output a single number: the number of ways the tourist can plan his trip. Note that 2 trips are identical if the successions of the 3*N cities are identical
or if the succession of the 3*N cities of the first trip is the same as the succession of the 3*N cities of the 2nd trip, read backwards (for instance, if every island had 1 city, numbered according to the island's number, the trips 1231 and 1321 would be identical).
*******IOTestCases*******
______________________________________________________
1173true
Here, in Romania, all snails are lazy. Take Wally the Snail, for example. He has to visit N friends which are located at distinct coordinates in the plane. But since
he is so lazy, he doesn't want to leave his house. He said that he will go visit his friends if someone can show him the right path to follow.
He wants to leave his house, visit all of his friends exactly once and then return to his house. Between 2 friends' houses or between his house and a friend's house, he walks on the straight line which connects them. 'Is that all ?', someone asked. Wally realized that this would be too easy, so he added that, during his trip, no two line segments along which he travels should cross (except for every 2 consecutive segments, which cross at one end). You must find a path for Wally, so he can go visit all of his friends (although he doesn't want to).
*******InputConstraints*******
On the 1st line of input, there will be 2 real numbers: X and Y, separated by a blank, representing the coordinates of Wally's house. On the 2nd line, there will be an integer
number: N (2 ≤ N ≤ 1000), the number of friends Wally has to visit. On the next N lines, there will be 3 numbers, separated by blanks: X , Y and ID. ID will be an integer number, representing the ID of one of Wally's friends. X and Y will be 2 real numbers, representing the coordinates of Wally's friend's house (they will be given with at most 3 decimal digits and will be in the range 100000 .. 100000).
All IDs are unique, between 1 and N. No 3 friends (including Wally) have their houses on the same straight line.
*******OutputConstraints*******
You should output N+2 lines: the IDs of the friends whose houses Wally is about to visit, in the order he visits them. Start with Wally's ID, continue with the ID of
the friend he visits first and so on. Finish with Wally's ID. Wally has ID 0.
If there is no solution, then print a single line, containing the number 1.
*******IOTestCases*******
input  output 

0 0
3
3 3 1
6 0 2
6 2 3
 0
1
3
2
0

______________________________________________________
1174true
Three Romanian programmers developed this new algorithm which generates all the N! permutations with N elements in a specific order, they called the transposition order. The algorithm starts with the permutation 1 2 3 .. N. Then it chooses a
pair of two adjacent elements (that is, two elements which are located on consecutive
positions) and switches them. This way, they get a new permutation. They do the same for this new permutation and they obtain a new one and so on, until all the N! permutations are generated. You realize that the algorithm must be pretty smart in order to generate all the N! permutations exactly once (without repetitions).
Hopefully, your task will not be to write such an algorithm. In fact, you are given the files perm.pas and perm.cpp, which are two implementations of this algorithm (in Pascal and C++). They read the integer N (1 ≤ N ≤ 100) from the keyboard and print to the file perm.txt all the N! permutations, one per line, in the order in which the algorithm generates them.
What you have to do is, given a permutation, to find out its index in the list of permutations generated by the algorithm.
Perm.pas 
Perm.cpp 
const
fileout = 'perm.txt';
MAXN = 100;
var
fout :text;
n, i :integer;
permut :array [1..MAXN] of integer;
position :array [1..MAXN] of integer;
dir :array [1..MAXN] of integer;
procedure PrintPermutation;
begin
for i := 1 to n do
write(fout, ' ', permut[i]);
writeln(fout);
end;
procedure Switch(p1, p2 :integer);
var
xch :integer;
begin
xch := permut[p1];
permut[p1] := permut[p2];
permut[p2] := xch;
position[permut[p1]] := p1;
position[permut[p2]] := p2;
end;
procedure GeneratePermutation(nn :integer);
var ii :integer;
begin
if (nn = n + 1) then
PrintPermutation
else
begin
GeneratePermutation(nn + 1);
for ii := 1 to nn  1 do
begin
Switch(position[nn],
position[nn] + dir[nn]);
GeneratePermutation(nn + 1);
end;
dir[nn] := dir[nn];
end;
end;
begin
readln(n);
for i := 1 to n do
begin
permut[i] := i;
position[i] := i;
dir[i] := 1;
end;
assign(fout, fileout);
rewrite(fout);
GeneratePermutation(1);
close(fout);
end.

#include <stdio.h>
const char *fileout = "perm.txt";
const int MAXN = 100;
FILE *fout;
int n, i;
int permut[MAXN + 1];
int position[MAXN + 1];
int dir[MAXN + 1];
void PrintPermutation()
{
for (i = 1; i <= n; i++)
fprintf(fout, " %d", permut[i]);
fprintf(fout, "\n");
}
void Switch(int p1, int p2)
{
int xch = permut[p1];
permut[p1] = permut[p2];
permut[p2] = xch;
position[permut[p1]] = p1;
position[permut[p2]] = p2;
}
void GeneratePermutation(int nn)
{
int ii;
if (nn == n + 1)
PrintPermutation();
else
{
GeneratePermutation(nn + 1);
for (ii = 1; ii <= nn  1; ii++)
{
Switch(position[nn],
position[nn] + dir[nn]);
GeneratePermutation(nn + 1);
}
dir[nn] = dir[nn];
}
}
int main()
{
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
permut[i] = i;
position[i] = i;
dir[i] = 1;
}
fout = fopen(fileout, "wt");
GeneratePermutation(1);
fclose(fout);
return 0;
}

*******InputConstraints*******
The first line contains a single integer: N (1 ≤ N ≤ 100). The 2nd line contains N integers separated by blanks. They are the given permutation with N elements.
*******OutputConstraints*******
Print one single integer, which will be the index of the permutation in the list of N! permutations generated by the algorithm described above.
*******IOTestCases*******
Hint
Run the 2 given programs for N=4 and you will notice that the permutation 2 3 1 4 will be on the 17th line of the file perm.txt.
______________________________________________________
1175true
You have been asked to discover some important properties of one strange sequences set. Each sequence of the parameterized set is given by a recurrent formula:
X_{n+1} = F(X_{n1}, X_{n}),
where n > 1, and the value of F(X,Y) is evaluated by the following algorithm:
 find H = (A_{1}*X*Y + A_{2}*X + A_{3}*Y + A_{4});
 if H > B_{1} then H is decreased by C until H ≤ B_{2};
 the resulting value of H is the value of function F.
The sequence is completely defined by nonnegative constants A_{1}, A_{2}, A_{3}, A_{4}, B_{1}, B_{2} and C.
One may easily verify that such sequence possess a property that X_{p+n} = X_{p+q+n} for appropriate large enough positive integers p and q and for all n ≥ 0. You task is to find the minimal p and q for the property above to hold. Pay attention that numbers p and q are well defined and do not depend on way minimization is done.
*******InputConstraints*******
The first line contains seven integers: A_{1}, A_{2}, A_{3}, A_{4}, B_{1}, B_{2} and C. The first two members of sequence (X_{1} and X_{2}) are placed at the second line. You may assume that all intermediate values of H and all values of F fit in range [0..100000].
*******OutputConstraints*******
An output should consist of two integers (p and q) separated by a space.
*******IOTestCases*******
input  output 

0 0 2 3 20 5 7
0 1  2 3 
______________________________________________________
1176true
The Galaxy Empire consists of N planets. Hyperchannels exist between most of the planets. New Emperor urged to extend hyperchannels network in such a way, that he can move from any planet to any other using no more than one channel. One can pass through the channel only in one direction.
The last channelestablishing ship is located on the base near planet A. This ship can’t pass through the existing channel, it always establishes a new one. But presence of two channels connecting the same planets in one direction makes navigation too difficult, almost impossible. The problem is to find a route for this ship to establish all necessary channels with no excessive ones. In the end of this route ship should return to the base.
*******InputConstraints*******
First line contains integer N ≤ 1000 and number of the planet A (A ≤ N) where the base is situated.
Each of the following N lines contain N numbers, the jth number of the ith line equals to 1 if there exists channel from planet i to planet j, and equals to 0 otherwise.
It is known, that Empire can fulfill its need of hyperchannels by establishing no more than 32000 new ones.
*******OutputConstraints*******
Output should contain the sequence in which channels should be established. Each line should contain two integers — numbers of source and destination planet of channel. You may assume, that solution always exists.
*******IOTestCases*******
input  output 

4 2
0 0 1 0
0 0 1 0
1 1 0 1
0 0 1 0
 2 4
4 1
1 2
2 1
1 4
4 2

______________________________________________________
1177true
Development team of new DBMS asks you to write subroutine for the ‘like’ operator.
‘Like’ operator works as following. It returns true if text string matches specified template. Template is a text string containing any symbols or following special sequences:
% 
matches any number of any characters 
_ 
matches any single character 
[с1с2] 
matches any single character in the range c1c2 
[c1c2c3…cN] 
matches any single character of the set {c1,c2,c3,…,cN} 
[^с1с2] 
matches any single character not in the range c1c2 
[^c1c2c3…cN] 
matches any single character not in the set {c1,c2,c3,…,cN} 
*******InputConstraints*******
First line contains number of tests N ≤ 1000. Next N lines contain comparisons in the following format:
String or template may contain any symbols with ASCII codes 32255. Inner entrance of apostrophe symbol (ASCII 39) into string or template is encoded by double apostrophe symbol.
Maximal length of string or template is 100 symbols.
*******OutputConstraints*******
For each of N comparisons output single 'YES' or 'NO' at a line.
*******IOTestCases*******
input  output 

15
'abcde' like 'a'
'abcde' like 'a%'
'abcde' like '%a'
'abcde' like 'b'
'abcde' like 'b%'
'abcde' like '%b'
'25%' like '_5[%]'
'_52' like '[_]5%'
'ab' like 'a[acdf]'
'ad' like 'a[acdf]'
'ab' like 'a[acdf]'
'a' like 'a[acdf]'
'[]' like '[[]]'
'''''' like '_'''
'U' like '[^azAZ09]'
 NO
YES
NO
NO
NO
NO
YES
YES
YES
YES
NO
YES
YES
YES
NO

______________________________________________________
1178true
Great Akbardin decided to build new roads in his caliphate. He wants to build minimal number of roads so that one can travel from any town to any other using only these roads. But this problem is too difficult for him and his mathematicians. So, at first, they decided to build straight roads between towns in such a way, that every town becomes connected with only one other. Because crossroads make movement dangerous, no two roads should intersect.
You task is to make plan of the roads being given coordinates of towns.
*******InputConstraints*******
First line contains an even integer N (N ≤ 10000) — the number of towns. Each of the next N lines contains pair of integers — coordinates of ith town x_{i}, y_{i} (−10^{9} < x_{i}, y_{i} < 10^{9}).
No three towns lay on one line.
*******OutputConstraints*******
Output N/2 lines with description of one road on each. Road is identified by pair of towns it connects.
*******IOTestCases*******
input  output 

4
0 2
1 1
3 4
4 4
 1 3
2 4

______________________________________________________
1179true
During building of roads, Akbardin read many statistical reports. Each report contained a lot of numbers. But different reports contained numbers in different numeric systems. And Akbardin asks his mathematicians a question – in what numeric system text contains maximal amount of numbers. Number is a sequence of digits, with nondigits to the left and right. Capital Latin letters are used in kbased system with k > 10 ('A' = 10, 'B' = 11, …, 'Z' = 35).
You task is to help mathematicians to solve this problem and save their heads.
*******InputConstraints*******
Text consists of digits, capital Latin letters, spaces and line breaks.
Size of input doesn’t exceed 1 Mb.
*******OutputConstraints*******
Output should contain two integers: base of numeric system K (2 ≤ K ≤ 36) and amount of numbers. If more than one answer is possible, output the one with a less K.
*******IOTestCases*******
input  output 

01234B56789
AZA  11 4 
______________________________________________________
1180true
Two Nikifors play a funny game. There is a heap of N stones in front of them. Both Nikifors in turns take some stones from the heap. One may take any number of stones with the only condition that this number is a nonnegative integer power of 2 (e.g. 1, 2, 4, 8 etc.). Nikifor who takes the last stone wins.
You are to write a program that determines winner assuming each Nikifor does its best.
*******InputConstraints*******
An input contains the only positive integer number N (condition N ≤ 10^{250} holds).
*******OutputConstraints*******
The first line should contain 1 in the case the first Nikifor wins and 2 in case the second one does. If the first Nikifor wins the second line should contain the minimal number of stones he should take at the first move in order to guarantee his victory.
*******IOTestCases*******
______________________________________________________
1181true
There is a convex polygon with vertices painted in three colors: Red (R), Green (G) and Blue (B). It is known that all the colors are present and any two neighbor vertices have different colors. You are to find out whether it is possible to cut this polygon with noncrossing diagonals so that each of the obtained triangles would have all vertices of different colors: one red, one green and one blue vertex.
Point out a possible way of the cutting if the cutting is possible.
*******InputConstraints*******
The first line contains a number N of the polygon vertices (4 ≤ N ≤ 1000). There are N symbols of the set {'R', 'G', 'B'} in the second line that specify a color for the correspondent vertex.
*******OutputConstraints*******
The first line should contain either a number of drawn diagonals in case the required cutting is possible or the number 0 otherwise (cutting is impossible). In the first case the following lines should contain a description of the drawn diagonals. The description of a diagonal takes one line and consists of diagonal vertices numbers. The numbers are separated with a space.
If there are several possible cuttings that satisfy the requirements you may output any of them.
*******IOTestCases*******
input  output 

7
RBGBRGB
 4
1 3
3 7
5 7
5 3

______________________________________________________
1182true
Your task is to divide a number of persons into two teams, in such a way, that:
 everyone belongs to one of the teams;
 every team has at least one member;
 every person in the team knows every other person in his team;
 teams are as close in their sizes as possible.
This task may have many solutions. You are to find and output any solution, or to report that the solution does not exist.
*******InputConstraints*******
For simplicity, all persons are assigned a unique integer identifier
from 1 to N.
The first line contains a single integer number N (2 ≤ N ≤ 100)  the total number of persons to divide into teams, followed
by N lines  one line per person in ascending order of their identifiers. Each line contains the list of distinct numbers A_{ij} (1 ≤ A_{ij} ≤ N, A_{ij} ≠ i) separated by spaces. The list represents identifiers of persons that i^{th} person knows. The list is terminated by 0.
*******OutputConstraints*******
If the solution to the problem does not exist, then write a single
message “No solution” (without quotes). Otherwise write a solution on two lines. On the first line write the number of persons in the first team, followed by the identifiers of persons in the first team, placing one space before each identifier. On the second line describe the second team in the same way. You may write teams
and identifiers of persons in a team in any order.
*******IOTestCases*******
input  output 

5
2 3 5 0
1 4 5 3 0
1 2 5 0
1 2 3 0
4 3 2 1 0
 3 1 3 5
2 2 4

______________________________________________________
1183true
Let us define a regular brackets sequence in the following way:
 Empty sequence is a regular sequence.
 If S is a regular sequence, then (S) and [S] are both regular sequences.
 If A and B are regular sequences, then AB is a regular sequence.
For example, all of the following sequences of characters are regular
brackets sequences:
(), [], (()), ([]), ()[], ()[()]
And all of the following character sequences are not:
Some sequence of characters '(', ')', '[', and ']' is given. You are to find
the shortest possible regular brackets sequence, that contains the given
character sequence as a subsequence. Here, a string
a_{1}a_{2}...a_{n} is called a subsequence of the string
b_{1}b_{2}...b_{m}, if there exist such indices
1 ≤ i_{1} < i_{2} < ... < i_{n} ≤ m,
that a_{j}=b_{ij} for all 1 ≤ j ≤ n.
*******InputConstraints*******
The input contains at most 100 brackets (characters '(', ')', '[' and ']')
that are situated on a single line without any other characters among them.
*******OutputConstraints*******
Write a single line that contains some regular brackets sequence
that has the minimal possible length and contains the given sequence as a
subsequence.
*******IOTestCases*******
______________________________________________________
1184true
Inhabitants of the Wonderland have decided to hold a regional
programming contest. The Judging Committee has volunteered and
has promised to organize the most honest contest ever. It was decided
to connect computers for the contestants using a “star” topology  i.e. connect them all to a single central hub. To organize a truly honest contest, the Head of the Judging Committee has decreed to place all contestants evenly around the hub on an equal distance
from it.
To buy network cables, the Judging Committee has contacted a local network solutions provider with a request to sell for them a
specified number of cables with equal lengths. The Judging
Committee wants the cables to be as long as possible to sit
contestants as far from each other as possible.
The Cable Master of the company was assigned to the task. He knows the length of each cable in the stock up to a centimeter, and he can cut them with a centimeter precision being told the length of the pieces he must cut. However, this time, the length is not known
and the Cable Master is completely puzzled.
You are to help the Cable Master, by writing a program that will
determine the maximal possible length of a cable piece that can be
cut from the cables in the stock, to get the specified number of
pieces.
*******InputConstraints*******
The first line contains two integers N and K, separated by a space. N (1 ≤ N ≤ 10000) is the number of cables in the stock, and K
(1 ≤ K ≤ 10000) is the number of requested pieces. The first line is followed by N lines with one number per line, that specify the length of each cable in the stock in meters. All cables are at least 1 meter and at most 100 kilometers in length. All lengths are written with a centimeter precision, with exactly two digits after a decimal point.
*******OutputConstraints*******
Write the maximal length (in meters) of the pieces that Cable
Master may cut from the cables in the stock to get the requested number of pieces. The number must be written with a centimeter precision, with exactly two digits after a decimal point.
If it is not possible to cut the requested number of pieces each one being at least one centimeter long, then the output must contain the single number “0.00” (without quotes).
*******IOTestCases*******
input  output 

4 11
8.02
7.43
4.57
5.39  2.00 
______________________________________________________
1185true
Once upon a time there was a greedy King who ordered his
chief Architect to build a wall around the King's castle. The
King was so greedy, that he would not listen to his Architect's
proposals to build a beautiful brick wall with a perfect shape
and nice tall towers. Instead, he ordered to build the wall
around the whole castle using the least amount of stone and
labor, but demanded that the wall should not come closer to
the castle than a certain distance. If the King finds that
the Architect has used more resources to build the wall than
it was absolutely necessary to satisfy those requirements,
then the Architect will loose his head. Moreover, he demanded
Architect to introduce at once a plan of the wall listing
the exact amount of resources that are needed to build
the wall.
Your task is to help poor Architect to save his head,
by writing a program that will find the minimum possible
length of the wall that he could build around the
castle to satisfy King's requirements.
The task is somewhat simplified by the fact, that the King's
castle has a polygonal shape and is situated on a flat ground.
The Architect has already established a Cartesian coordinate
system and has precisely measured the coordinates of
all castle's vertices in feet.
*******InputConstraints*******
The first line contains two integers N and L separated by a space. N (3 ≤ N ≤ 1000) is the number of vertices in the King's castle, and L (1 ≤ L ≤ 1000) is the minimal number of feet that King allows for the wall to come close to the castle.
Next N lines describe coordinates of castle's vertices in a clockwise order. Each line contains two integers X_{i} and Y_{i} separated by a space
(10000 ≤ X_{i}, Y_{i} ≤ 10000)
that represent the coordinates of i^{th} vertex.
All vertices are different and the sides of the castle do
not intersect anywhere except for vertices.
*******OutputConstraints*******
Write the single number that represents the minimal possible length of the wall in feet that could be
built around the castle to satisfy King's requirements.
You must present the integer number of feet to the King,
because the floating numbers are not invented yet. However,
you must round the result in such a way, that it is
accurate to 8 inches (1 foot is equal to 12 inches),
since the King will not tolerate larger error in
the estimates.
*******IOTestCases*******
input  output 

9 100
200 400
300 400
300 300
400 300
400 400
500 400
500 200
350 200
200 200
 1628

______________________________________________________
1186true
Bill teaches chemistry in the school and has prepared a number
of tests for his students. Each test has a chemical formula and a number
of possible reaction outcomes that his students are to choose one
correct from. However, Bill wants to make sure that he has not
made any typos while entering his tests into a computer and that his
students won't easily throw away wrong answers simply by counting
a number of chemical elements on the left and on the right side of
the equation, which should be always equal in a valid reaction.
You are to write a program that will help Bill. The program
shall read the description of the test for the students that
consists of the given left side of the equation and a number of
possible right sides, and determines if the number of chemical
elements on each right side of the equation is equal to the
number of chemical elements on the given left side of the
equation.
To help you, poor computer folks, that are unaware of the
complex world of chemistry, Bill has formalized your task. Each side
of the equation is represented by a string of characters without
spaces, and consists of one or more chemical sequences separated
by a '+' (plus) characters. Each sequence has an optional
preceding integer multiplier that applies to the whole sequence
and a number of elements. Each element is optionally followed by an
integer multiplier that applies to it. An element in this equation
can be either distinct chemical element or a whole sequence
that is placed in round parenthesis.
Every distinct chemical element is represented by either one
capital letter or a capital letter that is followed by a small
letter.
Even more formally, using notation that is similar to BNF, we can write:
 <formula> ::= [<number>] <sequence> { '+' [<number>] <sequence> }
 <sequence> ::= <element> [<number>] { <element> [<number>] }
 <element> ::= <chem>  '(' <sequence> ')'
 <chem> ::= <uppercase_letter> [ <lowercase_letter> ]
 <uppercase_letter> ::= 'A'..'Z'
 <lowercase_letter> ::= 'a'..'z'
 <number> ::= '1'..'9' { '0'..'9' }
Every distinct chemical element is said to occur in the given formula
for some total number X, if X is the sum of all separate occurrences
of this chemical element multiplied to all numbers that apply to it.
For example, in the following chemical formula:
C2H5OH+3O2+3(SiO2)
 C occurs for a total of 2 times.
 H occurs for a total of 6 times (5 + 1).
 O occurs for a total of 13 times (1 + 3*2 + 3*2).
 Si occurs for a total of 3 times.
All multipliers in the formula are integer numbers that are at least 2 if
explicitly specified and are 1 by default. Each chemical formula is at most 100
characters long, and every distinct chemical element is guaranteed to occur
for a total of no more than 10000 times in each formula.
*******InputConstraints*******
The first line represents a chemical formula that is to
be tested as the left side of the equation. The second line contains a single integer number N (1 ≤ N ≤ 10), which is the number of right sides of the equation that are to be tested. Each one of the following
N lines represents one such formula.
*******OutputConstraints*******
You are to write N lines — one line per each possible
answer of the chemical test for Bill's students that is given in the
input. For each righthand side formula that is encountered in the
input, you should output:
<left_formula>==<right_formula>
if the total number of occurrences of each distinct chemical element on the
lefthand side equals to the total number of occurrences of this
chemical element on the righthand side.
Otherwise write:
<left_formula>!=<right_formula>
Here <left_formula> must be replaced exactly (character by
character) with the original lefthand side formula as it is given in the first line
of the input, and <right_formula> must be replaced exactly
with each righthand side formula as they are given in the input. Do not
place any spaces in the lines you write.
*******IOTestCases*******
input  output 

C2H5OH+3O2+3(SiO2)
7
2CO2+3H2O+3SiO2
2C+6H+13O+3Si
99C2H5OH+3SiO2
3SiO4+C2H5OH
C2H5OH+3O2+3(SiO2)+Ge
3(Si(O)2)+2CO+3H2O+O2
2CO+3H2O+3O2+3Si  C2H5OH+3O2+3(SiO2)==2CO2+3H2O+3SiO2
C2H5OH+3O2+3(SiO2)==2C+6H+13O+3Si
C2H5OH+3O2+3(SiO2)!=99C2H5OH+3SiO2
C2H5OH+3O2+3(SiO2)==3SiO4+C2H5OH
C2H5OH+3O2+3(SiO2)!=C2H5OH+3O2+3(SiO2)+Ge
C2H5OH+3O2+3(SiO2)==3(Si(O)2)+2CO+3H2O+O2
C2H5OH+3O2+3(SiO2)!=2CO+3H2O+3O2+3Si

______________________________________________________
1187true
Your team was hired by the international corporation ACM
(Analytical Calculation Maxims). Every year ACM creates and
conducts various surveys. Surveys themselves are simple forms
with a list of questions and a list of possible answers for
every question. Surveys are distributed around the globe,
where field agents question the target group of people.
All the answers are gathered in the ICPC
(International Computation and Processing Center), where
teams of wellpaid analysts mine raw data in
search for relevant correlations. The raw data for each
individual survey consists of lots of lines of answers.
Each line corresponds to every questioned person and
for every question lists answers that the person has
made on that particular survey.
The first step of analysis that your team was
hired to automate is to create cross tables that
correlate answers on interesting pairs of questions.
In its most simple way, given a pair of questions,
cross table has a row for every possible answer
on the first question, and has a column for every possible
answer on the second question. Each cell of the cross
table contains a number of lines in the raw data that
has both answers for the corresponding questions at
the same time.
However, your task is complicated by the fact that
you are to compute and output not only simple cross
table values, but also total values for every row and
column in the cross table (that is the sum of values in the
corresponding row and column) that are placed in an
additional last column and last row, as well as
a percentage distributions for every row and column.
Percentage distribution for a row is an additional number
in every cell in that row that shows percent ratio
of the value in that cell to the total value for that
row, unless the total value is zero (in that case
percentage distribution for this row is not defined).
The same applies to the percentage distributions of
columns. Thus, the cross table in your output will have
at most three values in every cell (the value itself,
rowwise percent, and columnwise percent).
Please note, that percentage distributions also apply
to totals. For example, in the total column for every
row the rowwise percent will be always 100%, unless
the total value for the row is zero (in that case
rowwise percents are not defined), and columnwise
percent shows percents ratio of the total value for this
row to the total number of lines in the raw data (which
is the value that can be found in the last column
of the last row).
Percents are rounded to integers on output.
Percent that has a nonzero fractional part
is rounded to either the smallest integer number greater
than the resulting percent, or the largest integer number
smaller than the resulting percent, in such a way, that
the sums of all corresponding rowwise percents by row
(without row totals) or columnwise percents by column
(without column totals) are equal to 100% unless they
are undefined. There are various rounding algorithms
that produce results satisfying the above constraints.
You are free to use any rounding algorithm as long as
the above constraints are satisfied.
*******InputConstraints*******
The input consists of 3 sections: survey description,
survey results, and cross table descriptions.
The first line of the input contains the name of the
survey, which is at most 100 characters long. Subsequent lines describe all the questions in the survey. On the first
line of every question there is a 3character question code
(capital letters and digits only) followed by a space, and followed by the question name, which is at most 80 characters long. Each subsequent line for a question describes one possible answer on the question and starts with a space, followed by a singlecharacter code for the
answer (capital letter, digit, or character '.', '*', or '@'), followed by a space and followed by an answer description, which is at most 40 characters long. The list of questions is terminated by the line with a single character '#'. All answer codes are unique within the question, and all question codes are unique within the input. There are at least 2 and at most 10 possible answers per question and at least 2 and at most 100 questions.
Next lines in the input describe survey results. Every line contains a character per question (in the order they appear in the input) that gives the answer code for the corresponding question. The characters follow one another without any delimiters. This section is terminated by the line with a single character '#'. There is at least one line with answers in the section and at most 10000 answers in total (the number of lines times the number of questions).
Next lines in the input describe cross tables that are to be created. Each cross table description occupies one line. That line contains the code for the first question, followed by a space, followed by the different code for the second question, followed by a space, and followed by the cross table name, which is at most 100 characters
long. This section is terminated by the line with a single character '#'. There are at most 100 cross table descriptions in the input.
The input has no trailing spaces on any line. All names do not start or end with a space, but may contain spaces.
*******OutputConstraints*******
Write to the output a cross table for every cross table description in the input in the order they appear in the input. On the first line of the cross table write the survey name, followed by a space, followed by a '' (dash) character, followed by a space, followed by the cross table name. Then write the description of the first question,
and the description of the second question exactly as they appear in the input and in the same format. Then write an empty line, followed by the table itself. The table contains exactly 1+3*(N1+1) lines and exactly 6*(N2+2) characters on every line, where N1 is the number of possible answers for the first question, and N2 is the number of possible answers for the second question.
The table has one line for column headings, and N1+1 rows (3 lines per row). The first N1 of these rows correspond to the answers on the first question in the order they appear in the input, and the last row is for column totals. The table also has N2+2 columns, where each column is 6 characters wide. The first column is for row headings; the subsequent N2 columns correspond to the answers on the second question in the order they appear in the input, and the last column is for row totals. All information in the cells (including headings) is aligned to the right and is padded on the left with spaces to become 6 characters wide.
The heading for the first column is empty. The headings for the subsequent N2 columns are composed from the second question code, followed by a ':' (colon) character, and followed by the corresponding answer code. The
heading for the last column is the string "TOTAL" (without quotes). The headings for the first N1 3line rows of the cross table are composed from the first question code, followed by a ':' (colon) character, and followed by the corresponding answer code. The heading for the last row is the string "TOTAL" (without quotes). Row headings are situated on the first line of the corresponding row. The subsequent 2 lines in the heading column of every row must be blank.
All nonheading cells in the table contain computed values and percents. On the first line of every cell the corresponding cross table integer value is situated. The second line contains properly rounded to integers rowwise percent, with a mandatory trailing '%' (percent) character, or a single '' (dash) character if the corresponding rowwise percent is not defined. The third line contains columnwise percent in the same format. All cross tables in the output must be separated by a single empty line.
*******IOTestCases*******
input  output 

New Year Phone Survey for ACM ICPC
Q01 Hello!
H Hello!
Y Yes!
* Uhm...
. (silence)
@ (other)
Q02 How are you?
H Hello!
Y Yes!
F Fine!
Q Who are you?
@ (other)
BYE Happy New Year!
Y You too.
* (censored)
@ (other)
. (hang up)
#
.@.
HH@
.@.
YFY
HQ*
H@.
YYY
.H@
HFY
HH@
#
Q01 Q02 Health vs greeting style
Q02 BYE Politeness matrix
#  New Year Phone Survey for ACM ICPC  Health vs greeting style
Q01 Hello!
H Hello!
Y Yes!
* Uhm...
. (silence)
@ (other)
Q02 How are you?
H Hello!
Y Yes!
F Fine!
Q Who are you?
@ (other)
Q02:H Q02:Y Q02:F Q02:Q Q02:@ TOTAL
Q01:H 2 0 1 1 1 5
40% 0% 20% 20% 20% 100%
66% 0% 50% 100% 33% 50%
Q01:Y 0 1 1 0 0 2
0% 50% 50% 0% 0% 100%
0% 100% 50% 0% 0% 20%
Q01:* 0 0 0 0 0 0
     
0% 0% 0% 0% 0% 0%
Q01:. 1 0 0 0 2 3
33% 0% 0% 0% 67% 100%
34% 0% 0% 0% 67% 30%
Q01:@ 0 0 0 0 0 0
     
0% 0% 0% 0% 0% 0%
TOTAL 3 1 2 1 3 10
30% 10% 20% 10% 30% 100%
100% 100% 100% 100% 100% 100%
New Year Phone Survey for ACM ICPC  Politeness matrix
Q02 How are you?
H Hello!
Y Yes!
F Fine!
Q Who are you?
@ (other)
BYE Happy New Year!
Y You too.
* (censored)
@ (other)
. (hang up)
BYE:Y BYE:* BYE:@ BYE:. TOTAL
Q02:H 0 0 3 0 3
0% 0% 100% 0% 100%
0% 0% 100% 0% 30%
Q02:Y 1 0 0 0 1
100% 0% 0% 0% 100%
33% 0% 0% 0% 10%
Q02:F 2 0 0 0 2
100% 0% 0% 0% 100%
67% 0% 0% 0% 20%
Q02:Q 0 1 0 0 1
0% 100% 0% 0% 100%
0% 100% 0% 0% 10%
Q02:@ 0 0 0 3 3
0% 0% 0% 100% 100%
0% 0% 0% 100% 30%
TOTAL 3 1 3 3 10
30% 10% 30% 30% 100%
100% 100% 100% 100% 100%

______________________________________________________
1188true
Castaway Robinson Crusoe is living alone on a remote island.
One day a ship carrying a royal library has wrecked nearby.
Usually Robinson brings any useful stuff from the shipwreck to his
island, and this time he has brought a big chest with books.
Robinson has decided to build a bookcase for these books to create
his own library. He cut a rectangular niche in the rock for that purpose,
hammered in wooden pegs, and placed wooden planks on every pair of pegs
that have the same height, so that all planks are situated horizontally
and suit to act as shelves.
Unfortunately, Robinson has discovered that one especially old and big
tome does not fit in his bookcase. He measured the height and width of this
tome and has decided to redesign his bookcase in such a way, as to completely
fit the tome on one of the shelves, taking into account locations of other
shelves and the dimensions of the niche. With each shelf in the bookcase,
one of the following operations should be made:
 Leave the shelf on its original place.
 Move the shelf to the left or to the right.
 Shorten the shelf by cutting off a part of the plank and optionally
move it to the left or to the right.
 Move one of the pegs to a different place at the same height and
move the shelf to the left or to the right.
 Shorten the shelf by cutting off a part of the plank, move one of the
pegs to a different place at the same height, and optionally move the
shortened shelf to the left or to the right.
 Remove the shelf from the bookcase along with both supporting pegs.
We say that the shelf is properly supported by its pegs, if exactly two
distinct pegs support the shelf and the center of the shelf is between its
pegs or coincides with one of the pegs. The original design of Robinson's
library has all the shelves properly supported by their pegs and lengths of
all shelves are integer number of inches. The Robinson may only cut an integer
number of inches from the planks, because he has no tools for more precise
measurements. All remaining shelves after the redesign must be properly
supported by their pegs.
You are to find the way to redesign Robinson's library to fit the special
old tome without changing original design too much. You have to minimize the
number of pegs that are to be removed from their original places during
the redesign (operations 4 and 5 remove one peg, and operation 6 removes
two pegs). If there are different ways to solve the problem, then you are
to find the one that minimizes the total length of planks that are to be
cut off (operations 3 and 5 involve cutting something from the planks,
and operation 6 counts as if cutting off the whole plank). Width of
planks and diameter of pegs shall be considered zero.
The tome may not be rotated. The tome should completely (to all its width)
stand on one of the shelves and may only touch other shelves, their pegs or
niche's edge.
*******InputConstraints*******
The first line contains four integers X_{N}, Y_{N}, X_{T}, and Y_{T}, separated by spaces. They are, correspondingly, width and height of the niche, and width and height of the old tome in inches (1 ≤ X_{N}, Y_{N}, X_{T}, Y_{T} ≤ 1000).
The second line contains a single integer
N (1 ≤
N ≤ 100) that represents the number of the shelves. Then
N lines follow. Each line represents a single shelf along with its two supporting pegs, and contains five integer numbers
y_{i},
x_{i},
l_{i},
x_{1i},
x_{2i}, separated by spaces, where:
 y_{i} (0 < y_{i} < Y_{N}) — the height of the i^{th} shelf above the bottom of the niche in inches.
 x_{i} (0 ≤ x_{i} < X_{N}) — the distance between
the left end of the i^{th} shelf and the left edge of the niche in inches.
 l_{i} (0 < l_{i} ≤ X_{N} − x_{i}) — the length of the i^{th} shelf in inches.
 x_{1i} (0 ≤ x_{1i} ≤ l_{i}/2) — the distance between the left end of the i^{th} shelf and its leftmost supporting peg in inches.
 x_{2i} (l_{i}/2 ≤ x_{2i} ≤ l_{i};
x_{1i} < x_{2i}) — the distance between the left end of the i^{th} shelf and its rightmost supporting peg in inches.
All shelves are situated on different heights and are properly supported by their pegs. The problem is guaranteed to have a solution for the input data.
*******OutputConstraints*******
Output two integers separated by a space. The first one is the minimal number of pegs that are to be removed by Robinson from their original locations to place the tome. The second one is the minimal total length of planks in inches that are to be cut off during the redesign that removes the least number of pegs.
*******IOTestCases*******
input  output 

11 8 4 6
4
1 1 7 1 4
4 3 7 1 6
7 2 6 3 4
2 0 3 0 3
 1 3

______________________________________________________
1189true
You are to find all pairs of integers such that their sum is equal to the given integer number N and the second number results from the first one by striking out one of its digits. The first integer always has at least two digits and starts with a nonzero digit. The second integer always has one digit less than the first integer and may start with a zero digit.
*******InputConstraints*******
The input consists of a single integer N (10 ≤ N ≤ 10^{9}).
*******OutputConstraints*******
Write the total number of different pairs of integers that satisfy the problem statement. Then write all those pairs. Write one pair on a line in ascending order of
the first integer in the pair. Each pair must be written in the following format:
Here X, Y, and N must be replaced with the corresponding integer numbers. There should
be exactly one space on both sides of '+' and '=' characters.
*******IOTestCases*******
input  output 

302
 5
251 + 51 = 302
275 + 27 = 302
276 + 26 = 302
281 + 21 = 302
301 + 01 = 302

______________________________________________________
1190true
On the wrapper of a bar of chocolate, the producer must specify all the components of the product. Strictly speaking, producers should also specify the weight fractions of all the components, but most of them do not do so because the consumers won't buy a chocolate if they read, for example, "Water 80%". However, producers prefer to specify the weight fractions of some components. For example, the inscription "Whole nuts 90%" is likely to attract buyers. But the buyer must remember that the components are always written in nonincreasing order of weight fractions. Accordingly, the beautiful inscription "Cocoabutter, Water, Cocoapowder 40%", evidently, is a lie.
Write a program that determines whether an inscription on a bar of chocolate is a lie.
*******InputConstraints*******
The first line contains the number of components N (1 ≤ N ≤ 5000). Each of the following N lines contains a description of one component. Each description starts with the name of the component, which is no longer than 16 symbols and may contain only upper or lowercase English letter, hyphens, and underline characters. All the components have different names. Then there is a space followed by the number 0 or 1; 0 means that the producer didn't specify the weight fraction of the component. If the number is 1, it is followed by a space and the weight fraction given in hundredths of percent. All specified weight fractions are given in nonincreasing order. Weight fractions, both real and specified on the wrapper, are integers from 1 to 10000 (in hundredths of percent).
*******OutputConstraints*******
Output NO if the inscription is certainly a lie; output YES if the inscription is consistent and can be true.
*******IOTestCases*******
input  output 

4
Water 0
Cocoabutter 0
Cocoapowder 1 4000
Lecithin 0
 NO 
______________________________________________________
1191true
A robber is fleeing a place of crime. A cop follows him, with a time lag of L minutes. They run equally fast, thus the lag between them remains constant. Finally, feeling tired, the robber reaches a tram stop. He wants to take a tram of a specific route; trams follow each other with an interval of exactly K_{1} minutes on this route at any time of day and night. When the tram comes, the robber boards it. The policeman comes to the same tram stop. If the robber is still there waiting for the tram to arrive, the policeman arrests him. If the robber is gone, the cop himself waits for a tram of the same route. The robber leaves his tram at some stop and starts waiting for a tram of another route (trams of that route keep an interval of exactly K_{2} minutes). When a tram arrives, the robber gets on it and continues his way. Of course, the cop leaves his tram also at this stop and, if the robber is still there, arrests him. If the robber managed to leave, the policeman waits for a tram of the same route that the robber used and follows the robber…
This process continues until either the policeman arrests the robber or the robber, having used N trams, reaches his secret cover place where he is safe.
Although the speeds of the cop and the robber remain equal all the time and the speeds of their trams are equal, it may happen that the policeman is lucky to overtake the robber. For instance, if L < K_{1}, then it may happen that the policeman reaches the first stop when the robber is still waiting for a tram there. Other situations are also possible. Write a program that determines whether the cop can catch the robber.
*******InputConstraints*******
The input consists of two lines: in the first line there are the numbers L (0 < L < 100) and N (0 < N < 100) delimited with a space. In the second line there are time intervals K_{1}, K_{2}, …, K_{N} (0 < K_{i} < 100) between trams of the corresponding routes. These numbers are also separated with spaces. All numbers in the input data are integers.
*******OutputConstraints*******
Output NO if the cop has no chance to overtake the robber before he reaches his cover place; output YES if he still has such a chance.
*******IOTestCases*******
input  output 

15 4
7 3 13 6
 YES

______________________________________________________
1192true
A little boy likes throwing balls in his dreams. He stands on the endless horizontal plane and throws a ball at an angle of a degrees to the plane. The starting speed of the ball is V m/s. The ball flies some distance, falls down, then jumps off, flies again, falls again, and so on.
As far as everything may happen in a dream, the laws of the ball's motion differ from the usual laws of physics:
 the ball moves in the gravity field with acceleration of gravity equal to 10 m/s^{2};
 the rebound angle equals the angle of fall;
 after every fall, the kinetic energy of the ball decreases by a factor of K;
 there is no air in the dream;
 "Pi" equals to 3.1415926535.
Your task is to determine the maximal distance from the point of throwing that the ball can fly.
*******InputConstraints*******
The input contains three numbers: 0 ≤ V ≤ 500000, 0 ≤ a ≤ 90, and K > 1 separated by spaces. The numbers V and a are integers; the number K is real.
*******OutputConstraints*******
The output should contain the required distance in meters rounded to two fractional digits.
*******IOTestCases*******
input  output 

5 15 2.50
 2.08

______________________________________________________
1193true
A group of students are having an oral examination. At the beginning of the exam, all students simultaneously receive their questions and start preparing for the answer. Each student needs T_{1} minutes for the preparation and T_{2} minutes for the answer itself (these parameters can be different for different students). For each student, the time T_{3} (in minutes from the planned beginning of the exam) is given when this student has to be free because she has other things to do (for example, other exams).
During the exam, a queue of students is formed as they are getting ready to speak. If a student is ready to answer and at that time moment the professor is free, then this student starts answering immediately. If the professor is busy with another person, then the student joins the queue and starts answering when the student before her in the queue finishes her examination.
It is possible that some students won't be free when they planned to be (i.e., at the time T_{3}). The professor is ready to cooperate and can shift the beginning of the exam to an earlier time. However, he doesn't want to come too early! You task is to write a program that will calculate the minimal period in minutes by which the exam should be shifted so that all the students will manage to complete the exam before their T_{3} time.
*******InputConstraints*******
The first line contains the number of students N (1 ≤ N ≤ 40). Each of the next N lines contains the corresponding numbers T_{1}, T_{2}, and T_{3}. The numbers are separated with spaces and satisfy the constraints 0 ≤ T_{1} ≤ T_{3} ≤ 600, 1 ≤ T_{2} ≤ 240.
All the numbers T_{1} are distinct.
*******OutputConstraints*******
Output the nonnegative integer that is the answer to the problem. If there is no need to shift the beginning of the exam, output 0.
*******IOTestCases*******
input  output 

3
100 10 120
70 40 150
99 15 400  15 
2
100 10 110
80 15 100  0 
______________________________________________________
1194true
A party at the "Prancing Pony" tavern was over and the hobbits were breaking up. At the first crossroad all the company fell into several groups, each of which went its own way. As a matter of courtesy, the hobbits shook each other's hands before parting (each hobbit shook the hand of each hobbit he was parting with). Each group fell at the next crossroad into several smaller groups (with handshakes of course) and so on. This process continued until single hobbits and married couples reached their homes. In other words, the groups were splitting up until there were only groups of two or one hobbits left. Your task is to calculate the number of the handshakes made.
*******InputConstraints*******
Let's numbers the groups of hobbits so that the first group (the one that left the tavern) gets number 1 and other groups get distinct positive integers greater than 1. In the first line of the input there are the total number of hobbits N and the number of married couples K. These numbers meet the following conditions:
2 < N ≤ 20000; 0 ≤ 2K ≤ N.
Each of the next lines of the input starts with the number of the group and the number of groups it fell into. After that there are several pairs of numbers representing the number and size of each new group. It is guaranteed that if a group no. Y formed as a result of splitting of a group no. X, then the description of the group no. X occurs before the description of the group no. Y. In particular, this means that the description of the group no. 1 is in the second line of the input. If the group no. Y formed as a result of splitting of the group no. X and its description is absent, then the group no. Y didn't split further.
*******OutputConstraints*******
Output the total number of the handshakes made.
*******IOTestCases*******
input  output 

3 0
1 2 2 2 3 1
2 2 4 1 5 1  3 
______________________________________________________
1195true
The Olympic Winter Games. The Ouths and Crosses on the 3×3 Board Event. The Panel of Judges received an unfinished game with 3 moves made by each player. The players couldn't continue the game because they had lost too much blood at the doping control. The Panel of Judges had to determine the outcome in the case of the optimal play of both parties.
Since there were as many crosses as oughs, the Panel of Judges wanted to decide that it was a draw. However, Head Judge observed that one player was able to win the game in one move. Your task is to determine the outcome in the case of the optimal play of both rivals. According to the International Rules, Crosses move first in the game and the winner is he who puts three of his symbols in the same row, column, or diagonal.
*******InputConstraints*******
The input contains a 3×3 table consisting of the symbols X, O (the capital English letters, which mark the moves of Crosses and Ouths), and # (this symbol denotes an empty field). The table contains exactly three Crosses and three Ouths.
It is guaranteed that the game is not finished, i.e. any row, column or diagonal contains neither three Crosses nor three Ouths.
*******OutputConstraints*******
If Crosses win the game, output “Crosses win”. If Ouths win, output “Ouths win”. In the case of a draw, output “Draw”.
*******IOTestCases*******
input  output 

XXO
#X#
#OO
 Ouths win

O#O
#X#
XOX
 Draw

______________________________________________________
1196true
Professor of history decided to simplify the examination process. At the exam, every student should write a list of historic dates she knows (she should write the years only and, of course, must be able to explain what event took place in this or that year). Professor has a list of dates that students must know. In order to decide upon the student's mark, Professor counts the number of dates in the student's list that are also present in his list. The student gets her mark according to the number of coincidences.
Your task is to automatize this process. Write a program that would count the number of dates in the student's list that also occur in Professor's list.
*******InputConstraints*******
The first line contains the number N of dates in Professor's list, 1 ≤ N ≤ 15000. The following N lines contain this list, one number per line. Each date is a positive integer not exceeding 10^{9}. Professor's list is sorted in nondescending order.
The following line contains the number M of dates in the student's list, 1 ≤ M ≤ 10^{6}. Then there is the list itself; it is unsorted. The dates here satisfy the same restriction. Both in Professor's and in the student's lists dates can appear more than once.
*******OutputConstraints*******
Output the number of dates in the student's that are also contained in Professor's list.
*******IOTestCases*******
input  output 

2
1054
1492
4
1492
65536
1492
100
 2

______________________________________________________
1197true
The statement of this problem is very simple: you are to determine how many squares of the chessboard can be attacked by a knight standing alone on the board. Recall that a knight moves two squares forward (horizontally of vertically in any direction) and then one square sideways (perpedicularly to the first direction).
*******InputConstraints*******
The first line contains the number N of test cases, 1 ≤ N ≤ 100. Each of the following N lines contains a test: two characters. The first character is a lowercase English letter from 'a' to 'h' and the second character is an integer from 1 to 8; they specify the rank and file of the square at which the knight is standing.
*******OutputConstraints*******
Output N lines. Each line should contain the number of the squares of the chessboard that are under attack by the knight.
*******IOTestCases*******
input  output 

3
a1
d4
g6
 2
8
6

______________________________________________________
1198true
Hard times came for Martian senate. Even this pride of Martian democracy can not oppose the almighty jobbery. Let's consider the procedure of typical decision making. A member of Martian senate, who needs a certain law, submits it to senate. To improve his chances that law is accepted, he makes a phone call to each of senate members on whom he has the goods in his safe. Then he kindly suggests to those senators to support the new law. Moreover, to avoid occasional rejection of this important law, he asks each of them to make the same procedure with their safes. And each of them having no choice makes a similar range of phone calls to those on whome, in turn, he has the goods. If every senator supports the new law the president has nothing to do but to approve it. Otherwise he can reject it and send back to senate for law improvements.
It is evident, that just elected president Honestman dislikes such situation. So he starts to struggle against the jobbery. And first of all he wants to put to jail the most dangerous senate members. And definitely, if senator is able to make even the harmful law approved, he is a dangerous one. So secret service of Martian president has already checked safes of each senate member, and found out on whom each of them has the goods. Martian president knows about your achievements in programming and he asks you personally for a help.
*******InputConstraints*******
The first line of input contains single integer N — the number of senate members (1 ≤ N ≤ 2000). Each senate member is uniquely identified with a number from 1 to N. Each of subsequent N lines contains information about senate members. The ith line contains list of senate members (given by numeric identifiers) on whome he has the goods. List is terminated by number 0.
*******OutputConstraints*******
Print the list of identifiers of all dangerous senate members in a single line. The numbers in the list must be present in increasing order. The list must be terminated by number 0.
*******IOTestCases*******
input  output 

5
3 2 0
0
4 5 0
1 5 0
2 0  1 3 4 0 
______________________________________________________
1199true
In the kitchen lives a mouse. There are also a cat and a piece of cheese in the kitchen. The coordinates of the cheese and the mouse are known, and the cat is sleeping. Finally, there is some furniture in the kitchen. The furniture is a set of convex polygons. The mouse wants to get to the cheese unnoticed. A point of the route is called dangerous if the distance to the nearest piece of furniture is greater than 10 cm. It is required to find the least dangerous route for the mouse, i.e., the route in which the sum of the lengths of dangerous segments is minimal.
*******InputConstraints*******
In the first line there are four numbers x_{m}, y_{m}, x_{c}, y_{c} separated with a space. They are the coordinates of the mouse (x_{m}, y_{m}) and of the cheese (x_{c}, y_{c}). In the second line there is the number of pieces of furniture N (0 ≤ N ≤ 100). The next N lines describe these pieces. Each description starts with the number of vertices of the corresponding polygon K (3 ≤ K ≤ 10), given in a separate line. Each of the next K lines contains two numbers, which are the coordinates of the corresponding vertex. It is known that the distance between any two points of different polygons is greater than 20 cm (so that it would be easier for the cat to catch the mouse). Neither the mouse nor the cheese are inside any of the polygons. All the coordinates are given in meters and have no more than three fractional digits. The absolute values of coordinates do not exceed 10^{5}.
*******OutputConstraints*******
You should give the mouse’s route in the form of a broken line. In the first line output the number of its vertices (including the initial and final ones). Then give the coordinates of the vertices, two numbers per line, accurate to 10^{4}. Each segment of the broken line must be either entirely dangerous or entirely safe (with the possible exception of its endpoints). The broken line must contain no more than 1000 vertices.
*******IOTestCases*******
input  output 

1.0 1.5 0.0 1.5
1
4
0.0 0.0
0.0 1.0
1.0 1.0
1.0 0.0
 4
1.0 1.5
1.0 1.1
0.0 1.1
0.0 1.5

______________________________________________________
1200true
The famous venturer Ostap B. decided to organize a firm "Horns & Hoofs" which will produce horns and hoofs. First of all, Ostap has studied the market, the manufacturing process, and the local conditions.
The calculations showed that each horn would give a profit of A roubles and each hoof would bring B roubles. It must be taken into account that there are similar products in the market already and that horns and hoofs are in a sense interchangeable. Therefore the total amount of produced goods must not exceed K pieces each month, otherwise the excess will not be sold.
Besides, Ostap B. knows that the local racketeers fight monopolism and collect each month for each type of goods a "tax" which is equal (in roubles) to the square of the produced amount. For example, if the firm has produced two horns and three hoofs, then they must pay 4+9=13 roubles.
Having heard about the success of students of the Department of Mathematics and Mechanics in the AllRussian finals of business game Nixdorff Delta, Ostap appealed to the dean's office. He asked to calculate the optimal production volumes for his new firm. The dean is sure that his students will cope with this task.
*******InputConstraints*******
The first line contains real numbers A and B (−10000 ≤ A,B ≤ 10000) with a two fractional digits precision. These numbers are the profits (in roubles) given by each horn and by each hoof respectively.
The next line contains an integer K which is the maximal number of goods that could be sold each month (1 ≤ K ≤ 10000).
*******OutputConstraints*******
You should output at the first line the maximal possible profit with a two fractional digits precision. The next line should contain the optimal production volumes.
If there are several possible answers, you should output the one with the least amount of horns, and if there is still a tie with the least amount of hoofs.
*******IOTestCases*******
input  output 

34.20 61.70
45
 1239.50
16 29

______________________________________________________
1201true
Sometimes it is of great importance to know which day of the week a given date will be. And we start searching for the nearest calendar. Being lucky we may find one. And find out that this one does not contain the date you need. What a pity!
Thus you are asked to create a calendar that will be able to process any given date in the years range from 1600 till 2400. Given a date, your program should print (see the examples below) a correct calendar for the month containing the date. Do not forget about the leap years. A year is considered to be leap if it is multiple of 4 except it is multiple of 100 except it is multiple of 400. For example 1996 is a leap year, 1900 is not a leap year (it is a multiple of 4 and multiple of 100) and 2000 is a leap year (it is a multiple of 4, multiple of 100 and multiple of 400 as well).
*******InputConstraints*******
The first line of input contains a date, i.e. three integer numbers: day (1–31), month (1–12) and year (1600–2400) separated by spaces.
*******OutputConstraints*******
The output should contain exactly 7 lines with the correct calendar for the month containing the given date. Format of a calendar is given by the examples below (for a reading convenience spaces in output example are replaced with dots, real output should contain spaces instead). And do not forget to highlight the given date by square brackets.
*******IOTestCases*******
input  output 

16 3 2002
 mon........4...11...18...25
tue........5...12...19...26
wed........6...13...20...27
thu........7...14...21...28
fri...1....8...15...22...29
sat...2....9..[16]..23...30
sun...3...10...17...24...31

1 3 2002
 mon........4...11...18...25
tue........5...12...19...26
wed........6...13...20...27
thu........7...14...21...28
fri.[.1]...8...15...22...29
sat...2....9...16...23...30
sun...3...10...17...24...31

______________________________________________________
1202true
On an endless sheet of checked paper there are axes of coordinates. A unit for measurement in this coordinates system is the length of the square’s edge. Also there are N rectangles on this sheet of paper. Their edges are parallel to the coordinate axis, and go through the borders between the squares. If we denote the coordinates of the lower left corner of the ith rectangle with (x_{i}, y_{i}), and the coordinates of its upper right corner with (x^{i}, y^{i}), we will see, that:
x_{1} = 0, y_{1} = 0
x^{i} = x_{i + 1}
2 ≤ x^{i} − x_{i} ≤ 100
2 ≤ y^{i} − y_{i} ≤ 100
If two rectangles with numbers i and i + 1 overlap, their common border disappears:
A traveler starts his way from the point with the coordinates (1, 1), which, as it follows from the rules above, certainly lays in the first rectangle. The traveler walks strictly along the edges of the squares. He is not allowed to walk on the borders of the rectangles. Thus, he can leave one rectangle for another only through their disappeared common border. There is an example of some beginning of his walk on the picture.
The traveler’s goal is the point (x^{n} − 1, y^{n} − 1), which is obviously situated inside the last rectangle.
*******InputConstraints*******
In the first line there is a positive integer n, 0 < n < 100000 — the number of rectangles on the plane. Then n lines follow, each one of them containing four integer numbers x_{i}, y_{i}, x^{i}, y^{i}, separated with spaces, satisfying the above rules.
*******OutputConstraints*******
You should output the length (the measurement unit is the edge of one square) of the shortest possible route for the traveler to go from the point (1, 1) to the point (x^{n} − 1, y^{n} − 1), or the number −1, if there exists no such route (the latter possibility is realized, for instance, on the picture).
*******IOTestCases*******
input  output 

2
0 0 3 5
3 1 5 7  8 
______________________________________________________
1203true
Functioning of a scientific conference is usually divided into several simultaneous sections. For example, there may be a section on parallel computing, a section on visualization, a section on data compression, and so on.
Obviously, simultaneous work of several sections is necessary in order to reduce the time for scientific program of the conference and to have more time for the banquet, teadrinking, and informal discussions. However, it is possible that interesting reports are given simultaneously at different sections.
A participant has written out the timetable of all the reports which are interesting for him. He asks you to determine the maximal number of reports he will be able to attend.
*******InputConstraints*******
The first line contains the number 1 ≤ N ≤ 100000 of interesting reports. Each of the next N lines contains two integers T_{s} and T_{e} separated with a space (1 ≤ T_{s} < T_{e} ≤ 30000). These numbers are the times a corresponding report starts and ends. Time is measured in minutes from the beginning of the conference.
*******OutputConstraints*******
You should output the maximal number of reports which the participant can attend. The participant can attend no two reports simultaneously and any two reports he attends must be separated by at least one minute. For example, if a report ends at 15, the next report which can be attended must begin at 16 or later.
*******IOTestCases*******
input  output 

5
3 4
1 5
6 7
4 5
1 3
 3 
______________________________________________________
1204true
The number x is called an idempotent modulo n if
Write the program to find all idempotents modulo n, where n is a product of two distinct primes p and q.
*******InputConstraints*******
First line contains the number k of test cases to consider (1 ≤ k ≤ 1000). Each of the following k lines contains one number n < 10^{9}.
*******OutputConstraints*******
Write on the ith line all idempotents of ith test case in increasing order. Only nonnegative solutions bounded by n should be printed.
*******IOTestCases*******
input  output 

3
6
15
910186311  0 1 3 4
0 1 6 10
0 1 303395437 606790875 
______________________________________________________
1205true
Imagine yourself in a big city. You want to get from point A to point B. To do that you may move by foot or use the underground. Moving by the underground is faster but you may enter and exit it only at the stations. To save your time you decided to write a program to find the fastest route.
*******InputConstraints*******
The first line contains two floating point numbers. First of them is the speed of traveling by foot. The second one is the speed of traveling by the underground. The second speed is always greater than the first one.
Then description of the underground follows. It starts with an integer number N in the first line. It is the number of the underground stations. You may assume that N is not greater than 200. The following N lines contain two floating point numbers each (ith line contains the coordinates of ith station). Then the description of the connections between stations follows. Each connection is determined by the pair of integers, i.e. by the numbers of connected stations. The list of connections is terminates with a pair of zeroes. We assume that all the connections are straight. So the time we need to travel between stations is equal to the distance between stations divided by the speed of traveling by the underground.
It should be mentioned also that entering and exiting the underground and changing trains are possible at the stations only and takes no time.
At last the coordinates of the points A and B are given, tha pair of coordinates in a line.
*******OutputConstraints*******
The first line should contain the minimal time needed to get from the point A to the point B. Time should be given with the precision of 10^{−6}. The second line describes the use of the underground while traveling. It starts with the number of visited stations with tha following list of visited stations in the order they should be visited.
*******IOTestCases*******
input  output 

1 100
4
0 0
1 0
9 0
9 9
1 2
1 3
2 4
0 0
10 10
10 0
 2.6346295
4 4 2 1 3

______________________________________________________
1206true
Let us denote the sum of digits of the number N by S(N). In this problem, we want you to determine, how often the following equality holds:
*******InputConstraints*******
The input contains a single integer K, 2 ≤ K ≤ 50.
*******OutputConstraints*******
You should output the number of pairs of
Kdigit numbers
A and
B to satisfy the above equality. Counting that number you should be aware of the following:
 numbers A and B should not have leading zeroes;
 while counting the total number of pairs, the order of numbers A and B matters, thus, for instance, (12, 26) and (26, 12) are different pairs that satisfy the conditions of the problem.
*******IOTestCases*******
______________________________________________________
1207true
The are N points on the plane (N is even). No three points belong to the same strait line.
Your task is to select two points in such a way, that strait line they belong to divides the set of points into two equalsized parts.
*******InputConstraints*******
First line contains one integer N (2 ≤ N ≤ 10000).
Each of next N lines contains pair of integers x_{i}, y_{i} (−10^{9} ≤ x_{i}, y_{i} ≤ 10^{9}), the coordinates of
ith point.
*******OutputConstraints*******
Print the numbers of selected points.
*******IOTestCases*******
input  output 

4
0 0
1 0
0 1
1 1
 1 4

______________________________________________________
1208true
Nothing makes as old as years. A lot of cool contests are gone, a lot of programmers are not students anymore and are not allowed to take part at the contests. Though their spirit is fresh and young as it was years ago! And so once they decided to make a contest at the Ural State University among the veteran teams…
To make the contest interesting, they decided to invite as much "legendary" teams as possible. The jury has made a short list of teams, which have shown the best results in the old good times, thus being worthy to hold the name of "legendary". All those teams were invited to take part of the contest, and all of them accepted the invitations. But they have forgotten one important thing at the jury: during the long history of the contests at the university, the teams happened to change and some programmers managed to contest in different "legendary" teams. Though, the jury decided not to give up the initial idea and to form as much legendary teams as possible to participate at the contest — and your program should help the jury!
*******InputConstraints*******
The first line contains a positive integer K, 1 ≤ K ≤ 18. It is the number of all the legendary teams. There follow the descriptions of the teams in K lines. Each of those lines contains three names of the team members of the respective team. All names are written with not more than 20 small Latin letters.
*******OutputConstraints*******
You should output the maximal possible number of legendary teams of veterans, that could simultaneously participate at the contest.
*******IOTestCases*******
input  output 

7
gerostratos scorpio shamgshamg
zaitsev silverberg cousteau
zaitsev petersen shamgshamg
clipper petersen shamgshamg
clipper bakirelli vasiliadi
silverberg atn dolly
knuth dijkstra bellman  4 
______________________________________________________
1209true
Let's consider an infinite sequence of digits constructed of ascending
powers of 10 written one after another. Here is the beginning of the sequence: 110100100010000… You are to find out what digit is located at the definite position of the sequence.
*******InputConstraints*******
There is the only integer N in the first line (1 ≤ N ≤ 65535).
The ith of N left lines contains the integer K_{i} — the number of position in the sequence (1 ≤ K_{i} ≤ 2^{31} − 1).
*******OutputConstraints*******
You are to output N digits 0 or 1 separated
with a space. More precisely, the ith digit of output is to be equal to the
K_{i}th digit of described above sequence.
*******IOTestCases*******
input  output 

4
3
14
7
6
 0 0 1 0

______________________________________________________
1210true
Ivanushka the Fool lives at the planet of 0level. It's very unpleasant
to live there. An awful climate, 80 hours working week, ugly girls… He, as well as every
inhabitant of his planet, dreams to get to a planet of Nth level. To the paradise.
At each of the ith level planets there are several
hyperspace transfers to some of the (i+1)st level planets (but there are no
reverse ways). Every transfer is guarded by a spirit. The spirits are
usually evil: they demand many galactic banknotes for each transfer. You know, everyone wants to go to a higher level planet. And one has to pay for the pleasure. More than Ivanushka can even imagine. However, extraordinary situations like a lack of a laborforce at one of the higher level planets sometimes happen, and then the spirits  the guards of the transfers — become kind. Sometimes they give galactic banknotes themselves if only someone goes to their planets.
In order to embody his dream of heavenly planet
Ivanushka has done two things. First of all,
he has borrowed a complete map of the Universe. It's written on the map
how much the spirits demand or give for a transfer from this or that planet to another one of the next higher level. Secondly, he has hired a staff of young talanted
programmers in order that they will help him to draw the way on the map from
his planet to the one of Nth level so that he would spend for the
spirits as little money or even earn as much as it is possible.
*******InputConstraints*******
The first line contains an integer N
(0 < N < 30) — an amount of levels of the planets on Ivanushka's
map. Then follow N blocks of information that describe interlevel
transfers. More precisely, the ith informative block describes the
scheme of transfers from (i−1)st level planets to the ones of
ith level. Those blocks are separated with a line that contains the
only symbol "*". Planets of each level are numbered with sequential positive
integers starting from 1. Each level contains not more than 30 planets. There
is the only planet of 0level: the one that Ivanushka lives at. The first
line of a block contains a number K_{i} — an amount of planets
of the ith level. THen follow K_{i} lines — one for each
planet of the ith level. Every line consists of numbers of planets
separated with a space of the previous (i−1)st level that one can get
from them to the current planet, and the corresponding fees. A fee for each
transfer is an integer number from −32768 to 32767; a negative fee means that
the kind spirit is ready to pay for such a transfer. Each description line
is ended by zero.
*******OutputConstraints*******
should contain the only number — the minimal fee that Ivanushka
might pay for a transfer to some planet of the Nth level. The answer
may be negative: it means that Ivanushka will not only get to a heavenly
planet, but will earn some galactic banknotes. It's known that there exists
if only one way from Ivanushka's planet to the one of Nth level.
*******IOTestCases*******
input  output 

3
2
1 15 0
1 5 0
*
3
1 5 2 10 0
1 3 0
2 40 0
*
2
1 1 2 5 3 5 0
2 19 3 20 0
 1

______________________________________________________
1211true
Somebody of N boys and girls broke mummy's favourite cup. Mummy became angry and numbered the children with positive integers from 1 to N. Then she approached the child number 1 and asked: "Who has broken the cup?" "Me," — he (or she) answered and was punished.
You, of course, understand that the story is idealized. Practically (we don't know if it was true or not) the boy or the girl number 1 said: "It wasn't me! It was the child number K_{1}!" Then mummy approached number 2 and asked him (or her) the same question…
Some children tried to answer the truth. Others replied in order to say something. But some children had agreed not to give away a juvenile to mummy: each one of them pointed someone else from the group — in a circle. As a result — mummy was racked. She was despaired to remember what every child had told her about the cup and she wrote down all thier "evidences" on a sheet of paper. Now she's willing to investigate the cause. First of all she decided to find out if there is a "collective guarantee"
between some of the children so that it was described above. You are to write a program that would help mummy in such a case — to all appearences it was not the first and not the lsat cup.
*******InputConstraints*******
The first lines contains a positive integer T (1 ≤ T ≤ 16) — the number of input tests. Each test consists of two lines: the first one contains a number N (1 ≤ N ≤ 25000) — and amount of children. The second line contains N numbers separated with a space — that are the evidences of the children. Mummy has written down at ith position of the line the number of a child that the ith child pointed to, or 0 if the ith child suddenly confessed.
*******OutputConstraints*******
You should write one line for each test. It should contain "YES", if the evidences of the children at least seem to be noncontradictory: exactly one child has confessed the he (or she) had broken the cup, and there is no group of children that point to each other in a circle. Otherwise you are to output "NO".
*******IOTestCases*******
input  output 

4
4
2 0 2 2
4
2 0 2 1
5
2 3 4 1 3
3
0 3 2
 YES
YES
NO
NO

______________________________________________________
1212true
Once two friends Petya and Vasya decided to play “Battleship” at the lesson of computer science at school. Finishing place his ships on the field Petya fell to thinking how many ways of placing his last Kdeck ship exist. He tried to calculate it quickly but soon lost a count. Then Petya looked around and suddenly saw computers (there's no surprise: the children played at the lesson of computer science, but by the
moment Patya was carried away by the game so much that he didn't notice the computers). He thaught a bit and decided to write a program that would solve his problem. But so far as he was backward (it wasn't the first time that he played “Battleship” during the lesson) he didn't succeed. Please, help Petya with his problem.
*******InputConstraints*******
The first line contains three numbers separated with a space — the vertical size of the playing field N (1 ≤ N ≤ 30000), the horizontal size of the field M (1 ≤ M ≤ 30000) and a number of already placed ships on the field L (0 ≤ L ≤ 30). Then follow L lines describing the ships location. Each description consists of three numbers and a letter
separated with a space. The numbers are the coordinates of upperleft cell
of a ship (the coordinates of upperleft cell of the playing field are (1,1))
and a number of ship decks. The letter defines the ship orientation (“V” —
if it stands vertically, “H” — if horizontally). The last line contains the
only positive integer K — the number of decks of the last ship that Petya wants to place.
We'll explain to those who has never played the “Battleship” that a ideck ship is the rectangular of i × 1 cells. Ships may have from one to four decks.
According to the standard rules of the game, no two ships may contact each other neither by their edges nor by the vertices.
*******OutputConstraints*******
You should output the only number — an amount of different ways of placing the Petya's last Kdeck ship.
*******IOTestCases*******
input  output 

4 4 2
1 2 2 V
3 1 2 H
2  4 
______________________________________________________
1213true
It's wellknown that the most tenacious of life
species on the Earth are cockroaches. They live everywhere if only there
in food. And as far as they are unpretentious in food you can find them
absolutely everywhere.
A little Lyosha studies at school on a Space station.
During one of the school competitions his class has reached the final.
A task of the final contest is to exterminate all the cockroaches in the
cargo module within minimal time.
Within the long history of the competitions a unified
tactics was worked out. The tactics is as follows: a poison gas is let
in one of the module compartments and after that the baffle that separates
the compartment from one of the adjacent ones is opened. Cockroaches
can't stand the smell of the gas and run to the other compartment. When
there's no cockroaches in the treated compartment the baffle is closed.
Afterwards analogously the next compartment is treated, and so on. The
goal is to move all the cockroaches to the floodgate of the cargo module.
Then the outward door is opened and all the cockroaches are engulfed by
an open Space.
Lyosha is responsible for programming the control
board of the baffles in his team. The baffles are opened slowly, so it's
very important to make do with minimal number of baffle openings in order
to win in the contest. Your task is to help Lyosha to compute this number.
*******InputConstraints*******
The first line contains a name of the floodgate
compartment. Each of the next lines contains description of one of the
baffles — the names of two compartments separated with a dash (). The last
line contains the only symbol "#". There are cockroaches in all the compartments
of the module at first. It's possible to get to the floodgate from every
compartment of the module passing several baffles. The total number of
compartments doesn't exceed 30. The name of a compartment consists of no
more than 20 Latin letters and digits. The large and the small letters
should be distinguished.
*******OutputConstraints*******
Your program is to output the only number — the
minimal amount of baffles that should be opened (and then closed) in order
to move all the cockroaches to the floodgate.
*******IOTestCases*******
input  output 

Gateway
MachineryGateway
MachineryControl
ControlCentral
ControlEngine
CentralEngine
StorageGateway
StorageWaste
CentralWaste
#  6 
______________________________________________________
1214true
It's often happens in programming that one has to test and debug an existing program code. Imagine that your colleague has passed you fragment of program code of his because he is to work at another program.
Here follows the fragment of the program code — a function with two inputoutput parameters:
Pascal 
C++ 
procedure P(var x, y: longint);
var
i, j: longint;
begin
if (x>0) and (y>0) then
begin
for i := 1 to x+y do
begin
y := x*x+y;
x := x*x+y;
y := round(sqrt(x+(y/abs(y))*(abs(y))));
for j := 1 to 2*y do
x := xy;
end;
end;
end;

#include <math.h>
void P(long& x, long& y)
{
int i, j;
if (x>0 && y>0)
{
for (i = 1; i <= x+y; i++)
{
y = x*x+y;
x = x*x+y;
y = sqrt(x+(y/labs(y))*(labs(y)));
for (j = 1; j <= 2*y; j++)
x = xy;
}
}
}

Your task is unusual: in order to debug the function it's necessary to
work out a program that would restore input parameters given output data
of the function. It's guaranteed that no variable has left its type during
the processing of the function.
*******InputConstraints*******
contains two numbers x and y separated with a space — those are output parameters of the function.
*******OutputConstraints*******
should contain two numbers x and y separated
with a space that were given to the function as input parameters.
*******IOTestCases*******
______________________________________________________
1215true
Inexactness of projectile hit may be compensated
by increasing of the projectile diameter.
Sergey Sizy
In the problem you are to determine the minimal diameter that may compensate
inexactness of projectile hit in each concrete case. Assume that all the
targets are convex polygons. A hit is the situation when the circle crater
that the projectile leaves (the crater diameter equals to the one of the
projectile) covers if only one point of the target.
*******InputConstraints*******
The first line contains three numbers — coordinates of the hit point of the projectile center and the number of polygon sides N (3 ≤ N ≤ 100). The next N lines contain the vertices coordinates in counterclockwise order. All the coordinates are integers from [−2000,2000].
*******OutputConstraints*******
You are to output the only number which is the minimal diameter of a projectile that will cover the target rounded with three digits after the decimal point.
*******IOTestCases*******
input  output 

2 1 8
0 1
1 0
2 0
3 1
3 2
2 3
1 3
0 2
 2.000

______________________________________________________
1216true
Somewhere on the N × N chessboard, there are one white pawn, one black pawn, and the black King as well. A game is being played according to the usual chess rules* (except the absence of the white King). White is supposed to win, when it manages to promote its pawn to the Queen (even in the case when this queen would be immediately beaten by the next black’s move). Otherwise, Black is considered to be the winner (even if in some position White has no possibilities to move its pawn). Given an initial position, your program is to determine the winner.
* Usual chess rules mean exactly the following:
 White moves first.
 In the initial position, pawns are not on the first or the Nth horizontal row.
 White pawn is allowed to move to the fourth horizontal from the second, and black pawn is allowed to move to the (N−3)rd horizontal row from the (N−1)st. Pawns can't jump over other pieces.
 Just after the white pawn makes a move from x2 to x4, the black pawn may beat the white pawn en passant, moving from y4 to x3, if y is a vertical line, neighboring to the xvertical.
 In all other cases, pawns move one field along the vertical and beat one field along the diagonal. King moves one field in any direction.
 If it is not Black’s turn to move, the black King should not be under check, i.e. in the position, when the white pawn could beat it.
 When a black pawn reaches the first horizontal, it should be promoted to the Queen, Rook, Knight or Bishop, according to the wish of the Black player. (But when a white pawn reaches the Nth horizontal, it should be promoted to the Queen and our game immediately finishes).
*******InputConstraints*******
The first line contains a single integer N, 6 ≤ N ≤ 26. In the second line, the positions of the white pawn, black pawn and black King (in this very order!) are given, separated by one or several white spaces. A description of a position consists of a small Latin letter, which denotes the vertical, and (without a space) an integer number (from 1 to N) denoting the horizontal.
*******OutputConstraints*******
Output a message "WHITE WINS", when White can win the game according to the above described rules, and "BLACK WINS" otherwise.
*******IOTestCases*******
input  output 

10
h5 i5 b3
 WHITE WINS

8
d5 h6 b6
 BLACK WINS

______________________________________________________
1217true
Strange people live in Moscow! Each time in the bus, getting a ticket with a 6digit number, they try to sum up the first three and the last three digits. If these two sums are equal, they suppose such a ticket to be a lucky one. A person, who owns the lucky ticket, should dream about something, eat the ticket (no, it’s not made of chocolate, it’s made of paper!) and the dream will come true… At least, they believe it!
Strange people live in St.Petersburg! Each time in the bus, getting a ticket with a 6digit number, they try to sum up the three digits on the odd and the three digits on the even positions. If these two sums are equal, they suppose such a ticket to be a lucky one. A person, who owns the lucky ticket, should dream about something, eat the ticket (no, even in St. Petersburg lucky tickets are not made of chocolate, they’re made of paper!) and the dream will come true… At least, they believe it!
In the "third Russian capital" — Yekaterinburg — we laugh about such strange ideas. We are practical. We are not superstitious, even a little bit. But we understand that too much luck cannot be good. Thus we consider every ticket, which is lucky both in "Moscow sense" and "St. Petersburg sense" to be unlucky. If we get an unlucky ticket in the bus, we throw it away and leave the bus immediately! Two examples of unlucky tickets are 472175 and 810513.
You are to write a program, which calculates the total number of unlucky Ndigit tickets.
*******InputConstraints*******
The input contains a single even positive integer N (2 ≤ N ≤ 20) — the number of digits in the ticket. Please note, that, for example 00742544 is a valid 8digit ticket (by the way, it is a St.Petersburgstyle lucky ticket).
*******OutputConstraints*******
Your program should output a single integer number — the total number of unlucky Ndigit tickets.
*******IOTestCases*******
______________________________________________________
1218true
Decided several Jedi Knights to organize a tournament once. To know, accumulates who the largest amount of Force. Brought each Jedi his lightsaber with him to the tournament. Are different the lightsaber, and Jedi different are. Three parameters there are: length of the saber, Force of the Jedi and how good the Light side of the Force the Jedi can use. If in at least two parameters one Jedi than the other one stronger is, wins he. Is not possible a draw, because no Jedi any equal parameter may have. If looses a Jedi, must leave the tournament he.
To determine, which Jedi the tournament can win, your program is. Can win the tournament a Jedi, if at least one schedule for the tournament possible is, when the last one remains he on the tournament, not looses any match. For example, if Anakin stronger than Luke by some two parameters is, and Luke stronger than Yoda by some two parameters is, and Yoda stronger than Anakin, exists in this case a schedule for every Jedi to win the tournament.
*******InputConstraints*******
In the first line there is a positive integer N ≤ 200, the total number of Jedi. After that follow N lines, each line containing the name of the Jedi and three parameters (length of the lightsaber, Force, Light side in this order) separated with a space. The parameters are different integers, not greater than 100000 by the absolute value. All names are sequences of not more than 30 small and capital letters.
*******OutputConstraints*******
Your program is to output the names of those Jedi, which have a possibility to win the tournament. Each name of the possible winner should be written in a separate line. The order of the names in the output should correspond to the order of their appearance in the input data.
*******IOTestCases*******
input  output 

5
Solo 0 0 0
Anakin 20 18 30
Luke 40 12 25
Kenobi 15 3 2
Yoda 35 9 125  Anakin
Luke
Yoda 
______________________________________________________
1219false
Your program is to output a sequence of 1 000 000 lowercase Latin letters. This sequence should satisfy the following restrictions:
 Every letter occurs not more than 40 000 times in the sequence;
 Every possible subsequence with two letters length occurs not more than 2 000 times;
 Every possible subsequence with three letters length occurs not more than 100 times;
Input
For this problem no input is provided.
Output
In a single line of the output write some sequence, which satisfies the properties described above.
______________________________________________________
1220true
Imagine, that you are employed by a software development company. You work now on the famous "D++ project", which is devoted to the creation of a new generation programming language. Your particular task is quite prosaic, though. You are to develop the memory manager being able to work with a large number of stacks.
*******InputConstraints*******
The first line of the input contains the total number of stack operations N, 0 < N ≤ 100000. Each of the next N lines contains a description of a stack operation, either in the form PUSH A B (meaning to push B into stack A), or in the form POP A (meaning to pop an element from stack A), where A is the number of stack (1 ≤ A ≤ 1000), and B is an integer (0 ≤ B ≤ 10^{9}). You may assume, that every operation is correct (i.e., before each POP operation, the respective stack is not empty).
*******OutputConstraints*******
For each POP operation, described in the input, output the value, which this POP operation gets from the top of that stack, to which it is applied. Numbers should appear according to the order of the POP operations in the input. Each number should be output in a separate line.
*******IOTestCases*******
input  output 

7
PUSH 1 100
PUSH 1 200
PUSH 2 300
PUSH 2 400
POP 2
POP 1
POP 2  400
200
300 
______________________________________________________
1221true
After the greatest success of Malevich's "Black Square" the famous artist decided to create a new masterpiece. He took a large sheet of checked paper and filled some cells with black. After that he realized the picture to be too complicated. He was afraid, that people would not understand the sense of the painting. Thus, Malevich decided to cut out a smaller picture of the special form. It should be a black square with its sides parallel to the sides of the list. A white square rotated by 45 degrees should be placed inside the black square. The corners of the white square should lay on the sides of the black square. You can see an example of such picture on the figure.
The original paper size is N × N, 0 < N ≤ 100. Your program should help Malevich to find the largest figure corresponding to the pattern described above.
*******InputConstraints*******
The input contains several test cases. Each test case starts with the size of paper N. The following N lines of the test case describe the original painting: "1" denotes a black and "0" denotes a white cell. End of the input is marked by a zero value for N.
*******OutputConstraints*******
Your program should output the size (i.e. the maximum width or height) of the largest figure, which Malevich would like to cut out. If no such figure exists, output "No solution".
*******IOTestCases*******
input  output 

6
1 1 0 1 1 0
1 0 0 0 1 1
0 0 0 0 0 0
1 0 0 0 1 1
1 1 0 1 1 1
0 1 1 1 1 1
4
1 0 0 1
0 0 0 0
0 0 0 0
1 0 0 1
0  5
No solution 
______________________________________________________
1222true
A Chernobyl’ eagle has several heads (for example, the eagle on the Russian National Emblem is a very typical one, having two heads; there exist Chernobyl’ eagles having twentysix, one and even zero heads). As all eagles, Chernobyl’ eagles are very intelligent. Moreover, IQ of a Chernobyl’ eagle is exactly equal to the number of its heads. These eagles can also enormously enlarge their IQ, when they form a group for a brainstorm. IQ of a group of Chernobyl’ eagles equals to the product of IQ’s of eagles in the group. So for example, the IQ of a group, consisting of two 4headed eagles and one 7headed is 4*4*7=112. The question is, how large can be an IQ of a group of eagles with a given total amount of heads.
*******InputConstraints*******
There is one positive integer N in the input, N ≤ 3000 — the total number of heads of Chernobyl’ eagles in a group.
*******OutputConstraints*******
Your program should output a single number — a maximal IQ, which could have a group of Chernobyl’ eagles, with the total amount of heads equal to N.
*******IOTestCases*******
______________________________________________________
1223true
Once upon a time an Eagle made a nest on the roof of a very large building. Time went by and some eggs appeared in the nest. There was a sunny day, and Niels Bohr was walking on the roof. He suddenly said: “Oops! All eggs surely have the same solidity, thus there is such nonnegative number E that if one drops an egg from the floor number E, it will not be broken (and so for all the floors below the Eth), but if one drops it from the floor number E+1, the egg will be broken (and the same for every floor higher, than the Eth).” Now Professor Bohr is going to organize a series of experiments (i.e. drops). The goal of the experiments is to determine the constant E. It is evident that number E may be found by dropping eggs sequentially floor by floor from the lowest one. But there are other strategies to find E for sure with much less amount of experiments. You are to find the least number of eggs droppings, which is sufficient to find number E for sure, even in the worst case. Note that dropped eggs that are not broken can be used again in following experiments.
The floors are numbered with positive integers starting from 1. If an egg has been broken being dropped from the first floor, you should consider that E is equal to zero. If an egg hasn’t been broken even being dropped from the highest floor, consider that E is also determined and equal to the total number of floors.
*******InputConstraints*******
Input contains multiple (up to 1000) test cases. Each line is a test case. Each test case consists of two numbers separated with a space: the number of eggs, and the number of floors. Both numbers are positive and do not exceed 1000. Tests will end with the line containing two zeroes.
*******OutputConstraints*******
For each test case output in a separate line the minimal number of experiments, which Niels Bohr will have to make even in the worst case.
*******IOTestCases*******
input  output 

1 10
2 5
0 0
 10
3

______________________________________________________
1224true
A brand new sapper robot is able to neutralize mines in a rectangular region having integer height and width (N and M respectively). Before the robot begins its work it is placed near the top leftmost cell of the rectangle heading right. Then the robot starts moving and neutralizing mines making a clockwise spiral way (see picture). The spiral twists towards the inside of the region, covering all the cells. The region is considered safe when all the cells are visited and checked by the robot.
Your task is to determine the number of the turns the robot has to make during its work.
*******InputConstraints*******
The input contains two integers in the following order: N, M (1 ≤ N, M ≤ 2^{31} − 1).
*******OutputConstraints*******
The output consists of a single integer value — the number of the turns.
*******IOTestCases*******
______________________________________________________
1225true
On the Day of the Flag of Russia a shopowner decided to decorate the showwindow of his shop with textile stripes of white, blue and red colors. He wants to satisfy the following conditions:
 Stripes of the same color cannot be placed next to each other.
 A blue stripe must always be placed between a white and a red or between a red and a white one.
Determine the number of the ways to fulfill his wish.
Example. For N = 3 result is following:
*******InputConstraints*******
N, the number of the stripes, 1 ≤ N ≤ 45.
*******OutputConstraints*******
M, the number of the ways to decorate the shopwindow.
*******IOTestCases*******
______________________________________________________
1226true
This task is quite unconventional. We do not describe the way you must transform the input, which is a plain text containing Latin letters and other possible characters (numeric digits, punctuation marks etc.) We only say that the word being a subject to transformations is considered to be a sequence of Latin letters (both uppercase and lowercase) that is followed by the end of line, or the end of file, or a character which is not a Latin letter.
So, write a program to convert this "scrambled" text into a readable form.
*******InputConstraints*******
The input contains some ciphered text. The input contains no more than 1000 lines. The length of each line does not exceed 255 characters. The text may contain any printable characters.
*******OutputConstraints*******
The output must contain the deciphered text from the input.
*******IOTestCases*******
input 

This is an example of a simple test. If you did not
understand the ciphering algorithm yet, then write the
letters of each word in the reverse order. By the way,
"reversing" the text twice restores the original text. 
output 

sihT si na elpmaxe fo a elpmis tset. fI uoy did ton
dnatsrednu eht gnirehpic mhtirogla tey, neht etirw eht
srettel fo hcae drow ni eht esrever redro. yB eht yaw,
"gnisrever" eht txet eciwt serotser eht lanigiro txet. 
______________________________________________________
1227true
A highlevel international rally championship is about to be held. The rules of the race state that the race is held on ordinary roads and the route has a fixed length. You are given a map of the cities and twoway roads connecting it. To make the race safer it is held on oneway roads. The race may start and finish anyplace on the road. Determine if it is possible to make a route having a given length S.
*******InputConstraints*******
The first line of the input contains the number of cities M, the number of roads N and the length S of the route. 1 ≤ M ≤ 100; 1 ≤ N ≤ 10000; 1 ≤ S ≤ 10^{6}. S is integer.
The following N lines describe the roads as triples of integers: P, Q, R. Here P and Q are cities connected with a road, and R is the length of this road. All numbers satisfy the following restrictions: 1 ≤ P, Q ≤ M; 1 ≤ R ≤ 32000.
*******OutputConstraints*******
Write YES to the output if it is possible to make a required route and NO otherwise. Note that answer must be written in capital Latin letters.
*******IOTestCases*******
input  output 

3 2 20
1 2 10
2 3 5
 NO

3 3 1000
1 2 1
2 3 1
1 3 1
 YES

______________________________________________________
1228true
Imperative programming languages allow the use of both linear and multidimensional arrays. E.g. in Pascal for an array named X the expression array[0..2, 0..1, 0..3] declares a threedimensional array having the following boundaries for each dimension: 0..2, 0..1, 0..3. (We consider only zerobased arrays here though other values are possible in Pascal for lower bounds of each dimension.)
It is always possible to determine the order in which the items of the array are enumerated. Consider that this order is determined by the principle "righthand indices change faster". This means that the last (rightmost) index iterates through all possible values, then the index that is next to it (second from the right) changes its value by 1, and the last index iterates between the lower and upper boundaries again, and so on.
Example. The items of the array mentioned above are enumerated in the following order: X[0,0,0], X[0,0,1], X[0,0,2], X[0,0,3], X[0,1,0], X[0,1,1], X[0,1,2], X[0,1,3], X[1,0,0], X[1,0,1], X[1,0,2], X[1,0,3], X[1,1,0], X[1,1,1], X[1,1,2], X[1,1,3], X[2,0,0], X[2,0,1], X[2,0,2], X[2,0,3], X[2,1,0], X[2,1,1], X[2,1,2], X[2,1,3].
Let an nary array X is declared as array[0..k_{1}, 0..k_{2}, …, 0..k_{n}]. The theory says that the order P of any item X[i_{1}, i_{2}, …, i_{n}] is calculated as P(i_{1}, i_{2}, …, i_{n}) = 1 + D_{1}*i_{1}+D_{2}*i_{2}+… D_{n}*i_{n}, if we use the enumeration described above. Here D_{1}, D_{2}, …, D_{n} are socalled index multipliers.
Example. For the array in discussion the index multipliers are D_{1} = 8, D_{2} = 4, D_{3} = 1. Then, for example, the order of X[1,0,3] will be P(1,0,3) = 1+8*1+4*0+1*3 = 12.
Your task is to calculate the unknown upper boundaries (k_{1}, k_{2}, …, k_{n}) for given index multipliers D_{1}, D_{2}, …, D_{n} and total number of items s in the array.
*******InputConstraints*******
The first line of the input contains n — the number of dimensions (1 ≤ n ≤ 20) and s — the total number of items in the array (1 ≤ s < 2^{31}−1). The following n lines contain the index multipliers D_{1}, D_{2}, …, D_{n}.
*******OutputConstraints*******
Determine the upper boundaries for each dimension of the array in order: k_{1}, k_{2}, …, k_{n} (0 < k_{i} ≤ 1000). The numbers in the output may be delimited with spaces and/or line breaks.
*******IOTestCases*******
input  output 

3 24
8
4
1
 2 1 3

______________________________________________________
1229true
The builders must cover a rectangular area of size M × N (M and N are even numbers) with two layers of bricks that are rectangles of size 1 × 2. The first layer of the bricks has been already completed. The second layer (in an effort to make the brickwork really strong) must be done so, that no brick in it rests on a brick from the first layer.
Given the layout of the bricks in the first layer, determine the possible layout for the second one, or show that it is impossible to make the second layer.
Example. The two pictures show the layout of the two layers respectively. The size of the area is 2 × 4. Each brick is marked with its number on both halves.
*******InputConstraints*******
N, M — dimensions of the area. Then N lines follow having M numbers each that describe the layout of the first layer. Each brick is marked with two equal numbers written in the squares of the area that are covered by this brick. All bricks are marked with whole numbers ranging from 1 to the total number of the bricks. M and N are even numbers not exceeding 100.
*******OutputConstraints*******
If there is no solution, then write −1. If the solution exists, write N lines with M numbers each that describe the layout of the second layer in the way shown above.
*******IOTestCases*******
input  output 

2 4
1 1 2 2
3 3 4 4  2 1 1 4
2 3 3 4 
______________________________________________________
1230false
There is probably no programmer that had not heard of a famous problem set by Norbert Wiener. The problem is to write a program that, being run, sends its source code to the output device. Note, that it is not allowed to use the files containing the source code, or systemdependent features (e.g. knowing the address of a memory area that could possibly contain the source code). Such a program is called an introspective one. A theorem is well known, which states that it is possible to write an introspective program in almost any programming language.
It would be unfair to demand writing an introspective program in a language known to a different degree by different participants. Therefore we describe a formal syntax for a new language called PIBAS. And your task is to write a program that writes an introspective PIBAS program to the output.
Testing this PIBAS program includes a syntax check and a test run. A program is considered correct if it outputs a string equal to its source code.
PIBAS description:
 A PIBAS program consists of one or more operators separated with ";" (semicolon). A program is written in one line that is no longer than 32000 characters.
 Two types of operators exist: string assignment operator and output operator.
 Assignment operator is used as follows: <String variable>=<String expression>
 String variable is denoted with a single capital Latin letter.
 String expression is either a string variable, or a string constant, or a substring function, or a concatenation of string expressions with the use of "+" (plus) character.
 String constant is a sequence of any printable characters enclosed in double (") or single (') quotes. This sequence cannot contain the quote character it is enclosed in. Examples: 'Rybinsk', "O key!", "I don't know solution."
 A substring function is used in the following way: $(<string variable>,<unsigned integer>,<unsigned integer>). The second parameter sets the starting character of the substring and the third one sets its length. Character numeration is onebased.
 Output operator: ?<string expression>.
The total length of all strings sent to output may not exceed 32000 characters.
PIBAS program 
Output 
?"Hello, "+'World!' 
Hello, World! 
A='World, Hello!';?$(A,8,5);?", ";B=$(A,1,5)+'!';?B 
Hello, World! 
Input
Output
The output must contain an introspective PIBAS program.
______________________________________________________
1231true
A Turing machine used for computability research is well known to computer scientists. We will give a brief description of this abstraction. Turing machine is an automatic device that works on a tape (1) of potentially unlimited length. The tape is divided into cells each containing a character. One of the cells is called a viewed, or current, one (2). At any point of time the Turing machine has a condition that is stored in the control unit (4). Besides, the read/write head (3) of the control unit is pointing to the current cell.
The control unit can execute one action per time interval (step). The action includes a state change, a possible change of the character in the current cell, and a possible movement to the adjacent cell. These actions are defined in a special table, called a control table. We will denote the movements along the tape with the following symbols: "<" — to the left, ">" — to the right, "=" — no movement.
The control table is actually a program for the Turing machine. The work of the Turing machine is considered to be done if no line in the control table contains the combination of the current character and condition.
Current condition 
Current character 
New condition 
New character 
Movement 
1 
 
2 
 
> 
2 
 
3 
+ 
> 
3 
# 
4 
# 
< 
4 
+ 
4 
+ 
< 
4 
 
5 
 
= 
Notice. This example only illustrates the definition of the table.
The input data for the Turing Machine are placed beforehand in the cells of the tape. The result is written to the same tape. Assume that the initial condition for the Turing machine is equal to 1 and the input data on the tape are bounded on both ends with '#' characters. (All tape cells except those that filled with minuses are filled with '#' character.) The control block is placed at the leftmost '' character of the input data. The input tape contains '' (minus) character repeated n times (1 ≤ n ≤ 200), and the input contains an integer k.
Imagine that the minuses are placed in circle. Starting with the first one each kth uncrossed minus is crossed, i.e. it turns into a '+' (plus). The execution stops when there is only one uncrossed minus is left. Your task is to describe the control table for the Turing machine that will cross all minuses except one (it's position defined according to the above algorithm, but you may use any method) for the given k. For example, for n = 10 and k = 3 the fourth minus will remain uncrossed.
You may place the following characters on the tape: '+', '#', 'A'..'Z'. The cells initially filled with minuses may only contain '' and '+' characters. After the execution the read/write head must point to the uncrossed minus. The number of the steps s must not exceed 1 000 000. The number of the line in the control table p must not exceed 10000. Tape size limited with 10001 cells (5000 both side from the initial read/write head position).
*******InputConstraints*******
The input contains an integer number k (1 ≤ k ≤ 200).
*******OutputConstraints*******
The output describes the control table for the Turing machine for the given k. The first line of the output contains the number of rows p in the table (1 < p < 10000). Then p lines follow describing the table itself. Each row of the table contains five items: current condition (an integer number), current character (a character), new condition (an integer number), new character (a character), moving direction (a character). The items are separated with a single space characters. The condition numbers may range from 1 to 30000.
*******IOTestCases*******
input  output 

2
 5
1  2  >
2  3 + >
3 # 4 # <
4 + 4 + <
4  5  =

Hint
Note, that this example is correct only for n = 2. It just shows output format.
______________________________________________________
1232true
A guided probe is launched from the space station located at the distance of h from the surface of a large asteroid. The probe must land at the asteroid. The probe moves straight forward for a fixed distance d, after that it receives a new command from the station. The command defines the new direction for the movement. Each movement of the probe must help it to get closer to the surface. The control signals from the station are transmitted only within a cone having a vertex angle of α.
So, the trajectory of the probe is a broken line with segments of equal length, which is lying inside the cone described above. The last segment of the trajectory must also be of length d, lie inside the transmission cone and end at the surface of the asteroid.
Your task is to determine if it is possible to perform the landing of the probe taking into consideration the above conditions. If the landing is possible, then find the trajectory of minimal length including the coordinates of the ends of each segment. The landing point must be found, too.
The coordinates of the points are Cartesian. Ox and Oy lie on the surface of the asteroid, and Oz passes through the space station.
*******InputConstraints*******
h (0 < h < 100), d (h/1000 ≤ d ≤ 10*h), α (the angle is in radians, 0.1 ≤ α ≤ 3). All numbers are float.
*******OutputConstraints*******
n — the number of segments in the trajectory, or −1, if landing is impossible
x_{1} y_{1} z_{1}
x_{2} y_{2} z_{2}
…
x_{n} y_{n} z_{n} — the coordinates of the points where the probe receives control signals, and the landing point. All coordinates must be calculated to within 0.0001.
*******IOTestCases*******
input  output 

11 5 2  3
0 3 7
3 3 3
3 –1 0 
______________________________________________________
1233true
Let us consider the set of integer numbers between 1 and N inclusive. Let us
order them lexicographically (i. e. like in the vocabulary), for example, for
N = 11 the order would be: 1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9.
Let us denote the position of the number K in this ordering as Q_{N,K}.
For example, Q_{11,2} = 4. Given numbers K and M find the
smallest N such that Q_{N,K} = M.
*******InputConstraints*******
Input contains two integer numbers K and M
(1 ≤ K, M ≤ 10^{9})
separated by a space.
*******OutputConstraints*******
If such N that Q_{N,K} = M exists then write the smallest such N, otherwise write 0.
*******IOTestCases*******
input  output 

2 4
 11

2 1
 0

100000001 1000000000
 100000000888888879

1000000000 11
 0

______________________________________________________
1234true
The prisoner of the "IF" castle has decided to run away by disassembling
the brick wall in his prison cell. To hide his work from his jailors he
shall get rid of the bricks that he removes from the wall. All bricks have
a shape of rectangular parallelepiped with the size of A × B × C inches and
are so strong that they are impossible to break. However, there's a small
rectangular sewer hole in the cell's floor with the size of D × E inches that
goes deep down as a rectangular well of the same size (so deep it is, that
its depth could not be measured and can be neglected).
The prisoner have precisely (up to a tenth of an inch!) measured all the sizes
A, B, C, D, E and wants to know if it is possible to dispose of the castle's
bricks through the hole in the floor. Please, answer this question for him.
*******InputConstraints*******
The only line contains numbers A, B, C, D, and E separated by spaces. A, B, C are the lengths of brick's sides, and D, E are
the lengths of hole's sides. All lengths are at least 1 and at most 10 inches and have at most 1 digit after decimal point.
*******OutputConstraints*******
Write a single word YES if it is possible to dispose of the bricks through the hole or NO otherwise.
*******IOTestCases*******
input  output 

1.0 2.0 1.5 1.4 1.0
 NO

1.0 2.0 1.5 1.5 1.0
 YES

______________________________________________________
1235true
Once upon a time there was a greedy King who ordered his chief Architect to
build a field for royal cricket inside his park. The King was so greedy, that he
would not listen to his Architect's proposals to build a field right in the
park center with pleasant patterns of trees specially planted around and beautiful walks
inside tree alleys for spectators. Instead, he ordered neither to cut nor to plant
even a single tree in his park, but demanded to build the largest possible cricket
field for his pleasure. If the Kind finds that the Architect has dared to touch even
a single tree in his park or designed a smaller field that it was possible, then
the Architect will loose his head. Moreover, he demanded his Architect to introduce
at once a plan of the field with its exact location and size.
Your task is to help poor Architect to save his head, by writing a program that
will find the maximum possible size of the cricket field and its location inside
the park to satisfy King's requirements.
The task is somewhat simplified by the fact, that King's park has a rectangular shape
and is situated on a flat ground. Moreover, park's borders are perfectly aligned with
NorthSouth and EastWest lines. At the same time, royal cricket is always played on a
square field that is also aligned with NorthSouth and EastWest lines. Architect has
already established a Cartesian coordinate system and has precisely measured the
coordinates of every tree. This coordinate system is, of course, aligned with
NorthSouth and EastWest lines. Southwestern corner of the park has coordinates
(0, 0) and Northeastern corner of the part has coordinates (W, H), where W and H
are the park width and height in feet respectively.
For this task, you may neglect the diameter of the trees. Trees cannot be
inside the cricket field, but may be situated on its side. The cricket field may
also touch park's border, but shall not lie outside the park.
*******InputConstraints*******
The first line contains three integer numbers N, W, and H,
separated by spaces. N (0 ≤ N ≤ 100) is the number of
trees in the park. W and H (1 ≤ W, H ≤ 10000)
are the park width and height in feet respectively.
Next N lines describe coordinates of trees in the park. Each line contains
two integer numbers X_{i} and Y_{i} separated by a space
(0 ≤ X_{i} ≤ W,
0 ≤ Y_{i} ≤ H) that represent
coordinates of i^{th} tree. All trees are located at different
coordinates.
*******OutputConstraints*******
Write a single line with three integer numbers P, Q, and L
separated by spaces, where (P, Q) are coordinates of the cricket field Southwestern
corner, and L is a length of its sides. If there are multiple possible field
locations with a maximum size, then output any one.
*******IOTestCases*******
input  output 

7 10 7
3 2
4 2
7 0
7 3
4 5
2 4
1 7
 4 3 4

______________________________________________________
1236true
In the near future any research and publications about cryptography are
outlawed throughout the world on the grounds of national security concerns.
The reasoning for this is clear and widely accepted by all governments 
if cryptography literature is public like in the old times, then everybody
(even criminals and terrorists) could easily use it to hide their
malicious plans from the national and international security forces.
Consequently, public cryptographic algorithms and systems have ceased to
exist, and everybody who needs strong protection for their secrets is forced
to invent proprietary algorithms.
The ACM Corporation has lots of competitors who are eager to learn its
trade secrets. Moreover, the job to protect their secrets is complicated by
the fact, that they are forced to use intercontinental communication lines
which are easy to eavesdrop on, unlike internal lines of the ACM Corporation
which are well guarded. Therefore, the ACM Corporation have invented the
Intercontinental Cryptographic Protection Code (ICPC) which they are very
proud of, and which is considered unbreakable  nobody has even tried to
break it yet, but that is about to change.
The group of hackers was hired by the rival company, which does not disclose
its name to them, to break ICPC. As the first step, they have bribed one of the
programmers who implemented the software for ICPC and have learned how ICPC works.
It turns out, the ICPC uses very long key which is a sequence of bytes generated
by some sophisticated and random physical process. This key is changed weekly and
is used to encrypt all messages that are sent over intercontinental communication
lines during the week. This programmer has also proudly told them, that ICPC is
the fastest code in the world, because (having the benefit of highly sophisticated
code generation) they simply perform bitwise exclusive OR (XOR) operation between
the bytes of the message and the key. That is, the i^{th} byte of the encrypted
message E_{i} = K_{i} XOR C_{i}, where K_{i} is the
i^{th} byte of the key and C_{i} is the i^{th} byte of the
original cleartext message.
Having learned how ICPC works, they have started to look for the way to reliably
obtain the key every week, which is the only thing that is still missing to
listen for all intercontinental communications of the ACM Corporation
(eavesdropping on the intercontinental lines themselves has indeed turned out to
be an easy task). An attempt to bribe the security officers who guard and
distribute the key has failed, because the security officers (having the
profession with one the highest salaries of that time) have turned out to be
too expensive to bribe.
During the search for alternative solutions, they have stumbled upon a clerk,
who sends weekly newsletters to various employees and departments. Fortunately,
these newsletters are being sent just after the change of the key and the messages
are usually long enough to recover sufficient portions of the key by studying
original newsletters and their encoded forms. However, they could not
covertly find anyone who will disclose the newsletter contents on a weekly basis,
because all the employees were bound by a NonDisclosure Agreement (NDA) and the
penalty for the disclosure of any corporate message according to this NDA is death.
Yet they were able to convince this clerk (for a small reward) to do a seemingly
innocent thing. That is, while sending the copies of newsletter throughout the
corporation, he was instructed to insert an extra space character in the beginning
of some messages but send other copies in their original form. Now the task to
recover the key is straightforward and it is you, who shall create a program
for this. The program is given two ICPCed messages where the first message
is N bytes, and the second one is N+1 bytes and is the result of encoding the
same cleartext messages as the first one, but with one extra space character
(represented by the byte with the decimal value of 32) in the beginning. The
program shall find the first N+1 bytes of the key that was used to encode
the messages.
*******InputConstraints*******
The input consists of two lines. The first line consists of 2N characters and
represents the encoded message N bytes long. The second line consists of 2N+2 characters
and represents the encoded message N+1 bytes long.
Here 1 ≤ N ≤ 10000. Each message is written
on a single line in a hexadecimal form byte by byte without spaces.
Each byte of the message is represented by two characters '0''9', 'A''F'
that represent the hexadecimal value of the corresponding byte.
*******OutputConstraints*******
Write a single line that represents N+1 bytes of the
recovered key in the same hexadecimal format as in the input.
*******IOTestCases*******
input  output 

05262C5269143F314C2A69651A264B
610728413B63072C52222169720B425E
 41434D2049435043204E454552432732

______________________________________________________
1237true
The City has a number of municipal buildings and a number of fallout
shelters that were build specially to hide municipal workers in case of
a nuclear war. Each fallout shelter has a limited capacity in terms of
a number of people it can accommodate, and there's almost no excess
capacity in The City's fallout shelters. Ideally, all workers from a
given municipal building shall run to the nearest fallout shelter.
However, this will lead to overcrowding of some fallout shelters, while
others will be halfempty at the same time.
To address this problem, The City Council has developed a special evacuation plan. Instead of assigning every worker to a fallout shelter individually (which will be a huge amount of information to keep), they allocated fallout shelters to municipal buildings, listing the number of workers from every building that shall use a given fallout shelter, and left the task of individual assignments to the buildings' management. The plan takes into account a number of workers in every building  all of them are assigned to fallout shelters, and a limited capacity of each fallout shelter  every fallout shelter is assigned to no more workers then it can accommodate, though some fallout shelters may be not used completely.
The City Council claims that their evacuation plan is optimal, in the sense that it minimizes the total time to reach fallout shelters
for all workers in The City, which is the sum for all workers of the time to go from the worker's municipal building to the fallout shelter assigned
to this worker.
The City Mayor, well known for his constant confrontation with The City
Council, does not buy their claim and hires you as an independent consultant to verify the evacuation plan. Your task is to either ensure that the evacuation plan is indeed optimal, or to prove otherwise by presenting another evacuation plan with the smaller total time to reach fallout shelters, thus clearly exposing The City Council's incompetence.
During initial requirements gathering phase of your project, you have found that The City is represented by a rectangular grid. The location of municipal buildings and fallout shelters is specified by two integer numbers and the time to go between municipal building at the location
(X_{i}, Y_{i}) and the fallout shelter at the location (P_{j}, Q_{j}) is D_{i,j} = X_{i}  P_{j} + Y_{i}  Q_{j} + 1
minutes.
*******InputConstraints*******
The input consists of The City description and the evacuation plan description. The first line consists of two numbers N and M separated by a space. N (1 ≤ N ≤ 100) is a number of municipal buildings in The City (all municipal buildings are numbered from 1 to N). M (1 ≤ M ≤ 100) is a number of fallout shelters in The City (all fallout shelters are numbered from 1 to M).
The following N lines describe municipal buildings. Each line contains there integer numbers X_{i}, Y_{i}, and B_{i} separated by spaces, where X_{i}, Y_{i} (1000 ≤ X_{i}, Y_{i} ≤ 1000) are the coordinates of the building, and B_{i}
(1 ≤ B_{i} ≤ 1000) is the number of workers in this building.
The description of municipal buildings is followed by M lines that describe fallout shelters. Each line contains three integer numbers P_{j}, Q_{j}, and C_{j} separated by spaces, where P_{i}, Q_{i} (1000 ≤ P_{j}, Q_{j} ≤ 1000) are the coordinates of the fallout shelter, and C_{j}
(1 ≤ C_{j} ≤ 1000) is the capacity
of this shelter.
The description of The City Council's evacuation plan follows on the next N lines. Each line represents an evacuation plan for a single building (in the order they are given in The City description). The evacuation plan of i^{th} municipal building consists of M integer numbers E_{i,j} separated by spaces. E_{i,j} (0 ≤ E_{i,j} ≤ 1000) is a number
of workers that shall evacuate from the i^{th} municipal building to the j^{th} fallout shelter.
The plan is guaranteed to be valid. Namely, it calls for an evacuation of the exact number of workers that are actually working in any given municipal building according to The City description and does not exceed the capacity of any given fallout shelter.
*******OutputConstraints*******
If The City Council's plan is optimal, then write the
single word OPTIMAL. Otherwise, write the word SUBOPTIMAL on the first line, followed by N lines that describe your plan in the same format as in the input. Your plan need not be optimal itself, but must be valid and better than The City Council's one.
*******IOTestCases*******
input  output 

3 4
3 3 5
2 2 6
2 2 5
1 1 3
1 1 4
2 2 7
0 1 3
3 1 1 0
0 0 6 0
0 3 0 2
 SUBOPTIMAL
3 0 1 1
0 0 6 0
0 4 0 1

3 4
3 3 5
2 2 6
2 2 5
1 1 3
1 1 4
2 2 7
0 1 3
3 0 1 1
0 0 6 0
0 4 0 1
 OPTIMAL

______________________________________________________
1238true
Bill is trying to compactly represent sequences of capital alphabetic
characters from 'A' to 'Z' by folding repeating subsequences inside them. For example, one way to represent a sequence AAAAAAAAAABABABCCD is 10(A)2(BA)B2(C)D. He formally defines folded sequences of characters along with the unfolding transformation for them in the following way:
 A sequence that contains a single character from 'A' to 'Z' is
considered to be a folded sequence. Unfolding of this sequence
produces the same sequence of a single character itself.
 If S and Q are folded sequences, then SQ is also a folded sequence. If S unfolds to S' and Q unfolds to Q', then SQ unfolds to S'Q'.
 If S is a folded sequence, then X(S) is also a folded sequence,
where X is a decimal representation of an integer number greater than 1. If S unfolds to S', then X(S) unfolds to S' repeated X times.
According to this definition it is easy to unfold any given folded
sequence. However, Bill is much more interested in the reverse
transformation. He wants to fold the given sequence in such a way that the resulting folded sequence contains the least possible number of characters.
*******InputConstraints*******
The input contains a single line of characters from 'A' to 'Z'
with at least 1 and at most 100 characters.
*******OutputConstraints*******
Write a single line that contains the shortest possible folded sequence that unfolds to the sequence that is given in the input. If there are many such sequences then write any one of them.
*******IOTestCases*******
input  output 

AAAAAAAAAABABABCCD
 9(A)3(AB)CCD

NEERCYESYESYESNEERCYESYESYES
 2(NEERC3(YES))

______________________________________________________
1239true
The famous Ghost Busters team has decided to upgrade their Ectomobile
(aka Ecto1) with a powerful proton gun and an advanced targeting system.
Egon has designed and built all the hardware which consists of ectoplasmic
scanner and a proton gun that has two degrees of freedom and can automatically
rotate and fire in a 90 degrees trihedral angle. You have been hired to
write a prototype for the targeting software.
Ghosts are detected by ectoplasmic scanner and are represented as
floating spheres. The coordinates of their centers and radii are
delivered from the ectoplasmic scanner to the targeting software. The
coordinate system is aligned is such a way, that the proton gun fires
from the point (0, 0, 0) anywhere into
X ≥ 0, Y ≥ 0, Z ≥ 0
trihedral angle. The gun fires a proton ray in a straight line
and is so powerful, that even a touch of its ray is enough to kill
a ghost. The ray of the proton gun is able to kill a virtually unlimited
number of ghosts on its way.
For the first prototype for the targeting software, you are asked to
write a program that determines the maximal number of ghosts that can
be killed with a single shot of the proton gun.
*******InputConstraints*******
The first line contains a single integer N (0 ≤ N ≤ 100)  the number of ghosts detected by the ectoplasmic scanner of Ecto1. The following N lines describe detected ghosts  one ghost per line. The description of i^{th} ghost (ghosts are
numbered from 1 to N) consists of 4 integer numbers X_{i},
Y_{i}, Z_{i}, and R_{i}, separated by spaces.
X_{i}, Y_{i}, Z_{i}
(1 ≤ X_{i}, Y_{i}, Z_{i} ≤ 10000)
are the coordinates of the ghost's center, and R_{i}
(1 ≤ R_{i} ≤ min(X_{i}, Y_{i}, Z_{i}))
is the ghost's radius.
Because ghosts are ectoplasmic, they can be arbitrarily placed in respect
to each others. They can intersect, fit inside each other, coincide with each
other, etc.
*******OutputConstraints*******
On the first line write a single integer number  the maximal number of ghosts that can be killed with a single shot of the proton gun. On the second line write the identifying numbers of the ghosts to be killed in an arbitrary order separated by spaces. If there are multiple ways to kill this number of ghosts then write any one.
*******IOTestCases*******
input  output 

2
1200 1200 3900 300
160 160 820 60
 2
1 2

13
1200 1200 3900 300
160 160 820 60
100 10 10 10
10 100 10 10
10 10 100 10
10 10 10 10
50 50 50 10
100 100 75 20
100 75 100 20
75 100 100 20
3000 4000 7000 2600
100 1000 1000 50
1000 100 1000 100
 5
6 7 9 10 11

Hint
It is possible to kill both ghosts in sample #1 only because the
proton gun is so powerful that it kills ghosts by mere touch.
Sample #2 has 11 more ghosts (for a total of 13). Picture shows the
view of these ghosts through the ectoplasmic scope sight that
Egon has attached to proton gun to calibrate it and to debug your
targeting software. Outlines show ghosts as seen through the scope.
______________________________________________________
1240true
In the new version of the famous game “Heroes of Might and Magic” heroes themselves take active part in battles. More of that, hero can defeat some monsters alone, without any supporting army. In this problem you are asked to develop the program which would find the strategy for a mage hero fighting face to face with a pack of monsters.
Each hero initially has HP_{H} hit points and MP_{H} mana points. Heroes can use different spells. Your hero knows three spells: Lighting Bolt, Teleport and Heal. Each spell costs one mana point.
Each monster has HP_{M} hit points. Pack of monsters is a single group of several monsters who act as one. Therefore if initially the pack consists of N_{M} monsters, they have N_{M} × HP_{M} hit points. As the battle proceeds, monsters' number of hit points decreases. If monsters have H hit points, that means that the group consists of ceiling(H / HP_{M}) monsters (ceiling is a function that
returns the smallest integer number not less its argument).
The battle runs on a onedimensional battlefield consisting of N + 1 squares, numbered starting from 0. Your hero resides on the square number 0 and does not move. Monsters initially reside on N^{th} square and can move. Monsters can move at most V squares a turn.
The battle consists of turns. First your hero makes a turn, then the monsters, and so on. Monsters' strategy is very easy  they move in the direction of your hero min(V, P  1) squares where P is the square number where they were in the beginning of their turn. If the monsters are on the square number 1 in the end of the movement, then they strike your hero. If there are K monsters left in a pack, their strike decreases hit points of the hero by K. If your hero has nonpositive hit points, then the hero is defeated.
Your hero's turn is always the casting of some spell. Lighting Bolt spell removes L_{P} hit points from a pack of monsters, where P is the square number on which the monsters reside. Teleport spell moves monsters to any desired square (except 0 where your hero resides). Heal spell adds dH hit points to hero. However, his hit points never exceed HP_{H}, so if after using Heal spell his hit points are greater then HP_{H}, they are decreased to HP_{H}. If your hero has zero mana points and there is at least one monster left in the pack, then the hero is defeated.
Find the strategy which would allow your hero to defeat monsters. Monsters are defeated if their hit points are nonpositive.
*******InputConstraints*******
The first line contains positive integers separated by spaces in the following order: N, HP_{H}, MP_{H}, HP_{M}, N_{M}, V, dH.
(1 ≤ N ≤ 10,
2 ≤ HP_{H} ≤ 100,
1 ≤ MP_{H} ≤ 50,
1 ≤ HP_{M} ≤ 10,
1 ≤ N_{M} ≤ 10,
1 ≤ V ≤ N,
1 ≤ dH < HP_{H}).
The second line contains N integer numbers
L_{1}, L_{2}, …, L_{N}
(1 ≤ L_{P} ≤ 10), separated by spaces.
*******OutputConstraints*******
If the hero cannot win the battle, write the word DEFEATED. In the other case write the word VICTORIOUS on the first line and then write any sequence of hero's actions that leads to victory, where each line starting from the second one must correspond to one hero's turn. The first character of the line must be one of the following:
 L  Cast Lighting Bolt spell.
 T  Cast Teleport spell.
 H  Cast Heal spell.
If the hero casts Teleport spell then T character must be
followed by a space and an integer number from 1 to N  the square number where the monsters should be teleported to.
*******IOTestCases*******
input  output 

2 3 2 1 2 1 1
1 1
 VICTORIOUS
L
L

2 3 2 3 1 1 1
1 1
 DEFEATED

4 4 3 1 4 1 1
3 1 1 1
 VICTORIOUS
L
T 2
L

1 6 5 1 4 1 3
1
 VICTORIOUS
L
L
H
L
L

______________________________________________________
1241true
The factory cuts rectangular M × N granite plates into pieces using a special machine that is able to perform cuts in 4 different directions: vertically, horizontally, and diagonally at the angle of 45 degrees to the sides of the plate. Every cut is a straight line that starts and ends on the side of the plate.
The factory has been ordered to produce tiles for the inlay, each tile
of which is a 45 degrees right triangle. To reduce the time to deliver
the tiles it was decided to take all triangles from the already cut plates. Information about all performed cuts is available and your task is to compute the number of triangles of any size that were produced.
*******InputConstraints*******
The input describes the cuts that were performed on a single
rectangular plate. The first line contains three integers M, N, and K, separated by spaces. M and N
(1 ≤ M, N ≤ 50) are the dimensions
of the plate, and K (0 ≤ K ≤ 296) is
the number of cuts. Next K lines describe the cuts. i^{th} cut is described by four integer numbers X_{i,1}, Y_{i,1}, X_{i,2}, and Y_{i,2},
separated by spaces, that represent the starting and ending point
of the cut. Both starting (X_{i,1}, Y_{i,1}) and
ending (X_{i,2}, Y_{i,2}) points of the cut are
situated on the plate's border. Both points of the cut are different
and the cut goes through the plate. Here, the coordinates by the X axis run from 0 to M, and the coordinates by the Y axis run from 0 to N. All cuts are different.
*******OutputConstraints*******
Write the number of triangles that were produced by the cuts.
*******IOTestCases*******
input  output 

4 4 4
1 4 1 0
0 4 4 0
0 0 4 4
0 2 4 2
 6

7 4 6
6 0 7 1
1 4 1 0
0 4 4 0
0 0 4 4
0 2 7 2
7 0 3 4
 8

______________________________________________________
1242true
Knife. Moonlit night. Rotten stump with a short blackhandled knife in it. Those who know will understand. Disaster in the village. Werewolf.
There are no so many residents in the village. Many of them are each other's relatives. Only this may help to find the werewolf. The werewolf is merciless, but his descendants never become his victims. The werewolf can drown the village in blood, but he never kills his ancestors.
It is known about all the villagers who is the child of whom. Also, the sad list of the werewolf's victims is known. Your program should help to determine the suspects. It would be a hard task, if a very special condition would not hold. Namely, citizens of the village are not used to leave it. If some ancestor of some citizen lives in the village, then also his immediate ancestor does. It means, that, for example, if the father of the mother of some citizen still lives in the village, than also his mother still lives.
*******InputConstraints*******
The first line contains an integer N, 1 < N ≤ 1000, which is the number of the villagers. The villagers are assigned numbers from 1 to N. Further is the description of the relation "childparent": a sequence of strings, each of which contains two numbers separated with a space; the first number in each string is the number of a child and the second number is the number of the child's parent. The data is correct: for each of the residents there are no more than two parents, and there are no cycles. The list is followed by the word "BLOOD" written with capital letters in a separate string. After this word there is the list of the werewolf's victims, one number in each string.
*******OutputConstraints*******
The output should contain the numbers of the residents who may be the werewolf. The numbers must be in the ascending order and separated with a space. If there are no suspects, the output should contain the only number 0.
*******IOTestCases*******
input  output 

8
1 3
3 6
4 5
6 2
4 6
8 1
BLOOD
3
8
 4 5 7

6
1 2
3 2
1 4
3 4
2 6
5 2
5 4
BLOOD
2
5
 0

______________________________________________________
1243true
After the Snow White with her bridegroom had left the house of the seven dwarfs, their peaceful and prosperous life has come to an end. Each dwarf blames others to be the reason of the Snow White's leave. To stop everlasting quarrels, the dwarfs decided to part. According to an ancient law, their common possessions should be divided in the most fair way, which means that all the dwarfs should get equal parts. Everything that the dwarfs cannot divide in a fair way they give to the Snow White. For example, after dividing 26 old boots, each dwarf got 3 old boots, and the Snow White got the remaining 5 old boots. Some of the numbers are very large, for example, the dwarfs have 123456123456 poppy seeds, so it is not easy to calculate that the Snow White gets only one seed. To speed up the divorce, help the dwarfs to determine quickly the Snow White's part.
*******InputConstraints*******
The only line contains an integer N that represents the number of similar items that the dwarfs want to divide (1 ≤ N ≤ 10^{50}).
*******OutputConstraints*******
You should output the number of items that pass into the possession of the Snow White.
*******IOTestCases*******
input  output 

123456123456
 1

______________________________________________________
1244true
Let's remember one old joke:
Once a gentleman said to another gentleman:
— What if we play cards?
— You know, I haven't played cards for ten years…
— And I haven't played for fifteen years…
So, little by little, they decided to resurrect their youth. The first gentleman asked a servant to bring a pack of cards, and before starting playing out weighed in his hand the pack.
— It seems to me, one card is missing from the pack… — he said and gave the pack to the other gentleman.
— Yes, the nine of spades, — the man agreed.
An incomplete pack of cards is given. The program should determine which cards are missing.
*******InputConstraints*******
The first line contains a positive integer, which is the weight in milligrams of the given incomplete pack. The second line contains an integer N, 2 ≤ N ≤ 100 — the number of cards in the complete pack. In the next N lines there are integers from 1 to 1000, which are the weights of the cards in milligrams.
It's guaranteed that the total weight of all cards in the complete pack is strictly greater than the weight of the incomplete pack.
*******OutputConstraints*******
If there is no solution, then output the single number 0. If there are more than one solutions, then you should write −1. Finally, if it is possible to determine unambiguously which cards are missing in the incomplete pack as compared to the complete one, then output the numbers of the missing cards separated with a space in ascending order.
*******IOTestCases*******
input  output 

270
4
100
110
170
200
 2 4

270
4
100
110
160
170
 1

270
4
100
120
160
180
 0

______________________________________________________
1245true
Artist Ivanov (not the famous Ivanov who painted "Christ's apparition to people", but one of the many namesakes) once managed to rent inexpensively an excellent studio. Alas, as he soon discovered, the inexpensiveness was caused by objective reasons. A murder happened long ago in the house where he rented the room, and now the ghost living in the house each night renews blood spots on the walls of all the rooms. Ivanov's studio did not escape this damnation.
Nevertheless, being a creative person, Ivanov quickly found a simple solution to the problem. He decided to paint one or two pictures and hang them on the (single) wall where the spots appear each night so that the spots would be covered by the pictures. Of course, he does not want to spend too much time doing this work. That is why he plans to use not more than two pictures and wants the total square of the pictures to be minimal.
All the blood spots are circles. Each picture has a rectangular form with sides parallel to the axes, and the minimally possible size of a picture in each of the dimensions is 100 millimeters. If it is necessary to paint two pictures, then they should be hanged to the wall without overlaying. Each spot must be covered by exactly one picture.
*******InputConstraints*******
The first line contains the number of the spots N, 0 < N ≤ 1000. Each of the next N lines contains the description of the corresponding spot. A spot is described by three positive integers; they are the radius of the spot and the Cartesian coordinates of the center of the spot. Everything is measured in millimeters and all these numbers do not exceed 10000.
*******OutputConstraints*******
Output the minimal total square (in square millimeters) of the pictures (not more than two) necessary to cover all the spots.
*******IOTestCases*******
input  output 

3
50 50 50
50 250 50
10 150 250  40000 
______________________________________________________
1246true
A dog is tethered to a pole with a rope. The pole is located inside a fenced polygon (not necessarily convex) with nonzero area. The fence has no selfcrosses. The Olympian runs along the fence bypassing the vertices of the polygon in a certain order which is not broken during the jog. A dog pursues him inside the fenced territory and barks. Your program is to determine how (clockwise or counterclockwise) the rope will wind after several rounds of the Olympian's jog.
*******InputConstraints*******
The first input line contains a number N that is the number of the polygon vertices. It’s known that 3 ≤ N ≤ 200000. The next N lines consist of the vertices plane coordinates, given in an order of Olympian’s dog. The coordinates are a pair of integers separated with a space. The absolute value of each coordinate doesn’t exceed 50000.
*******OutputConstraints*******
You are to output "cw", if the rope is winded in a clockwise order and "ccw" otherwise.
*******IOTestCases*******
input  output 

4
0 0
0 1
1 1
1 0  cw 
______________________________________________________
1247true
There is a sequence of integer numbers A_{1}, A_{2}, …, A_{S}, and a positive integer N. It's known that all elements of the sequence {A_{i}} satisfy the restriction 0 ≤ A_{i} ≤ 100. Moreover, it's known that the sum of all elements of the sequence is equal to S + N. You are to write a program that given a sequence {A_{i}} and a number N will answer the question: is it true that for all 1 ≤ i ≤ j ≤ S the following inequality holds:
A_{i} + A_{i+1} + … + A_{j} ≤ (j – i + 1) + N ?
*******InputConstraints*******
The first input line contains two separated with a space positive numbers S and N that do not exceed 30000. Then follow S lines with one number in a line that are elements of the sequence {A_{i}}.
*******OutputConstraints*******
Output "YES", if the mentioned above inequality holds for all the values of the parameters i and j, and "NO" otherwise.
*******IOTestCases*******
input  output 

4 3
2
3
0
2
 YES

4 5
1
0
5
3
 NO

______________________________________________________
1248true
You are given a sequence of real numbers. And you ought to sum them all. And don’t forget to output the result.
*******InputConstraints*******
The first input line contains a number of the sequence elements N (N ≤ 1000). The next N lines contain the elements in exponential notation with 19 significant digits in mantissa. All the numbers are contained in a range from 10^{−100} to 10^{100}.
*******OutputConstraints*******
You are to output the only number which is the sum of all the input numbers. This number is to be presented in an exponential notation with 19 correct digits in mantissa.
*******IOTestCases*******
input  output 

2
1.5e3
1.5e3  1.500001500000000000e3 
______________________________________________________
1249true
Aerophotography data provide a bitmap picture of a hardtoreach region. According to the suggestions of scientists, this region is a cemetery of an extinct civilization. Indeed, the picture, having been converted to a binary form, shows distinctly visible areas, dark (marked with symbols 1) and light (marked with 0). It seems that the dark areas are tombstones. It's easy to either confirm or reject the hypothesis since the race that lived in the region knew astronomy, so tombstones were always oriented along the Earth's parallels and meridians. That is why the dark areas in the picture should have the form of rectangles with the sides parallel to the axes. If it is so, then we indeed have a picture of a cemetery of an extinct race. Otherwise, new hypotheses should be suggested.
*******InputConstraints*******
The first input line contains two integers N and M, which are the dimensions of the picture provided by the aerophotography. Each of the next N lines contains M zeros or ones separated with a space. The numbers N and М do not exceed 3000.
*******OutputConstraints*******
Output "Yes" if all connected dark areas in the picture are rectangles and "No" otherwise.
*******IOTestCases*******
input  output 

2 2
0 1
1 1
 No

3 3
0 0 1
1 1 0
1 1 0
 Yes

______________________________________________________
1250true
There is Archipelago in the middle of a shoreless ocean. An ancient tribe of cannibals lives there. Shamans of this race have been communicating with gods and admonishing people for ages. They could generate a rain during a drought and clear the sky in a raining season. A long time ago the first shaman of the tribe jumped into one of the seas and drowned while being in a sacred trance. Since then all the land inside this sea is regarded as sacred. According to an ancient law, all shamans must be buried on a sacred land. However, souls of dead shamans cannot get on with each other, so each shaman must be buried on a separate island. An old prophecy says that if two shamans are buried on the same land, then a dreadful time will come and the tribe will perish.
How many shamans will the tribe outlive? This problem bothered all the chiefs of the tribe who were coming into power. So one of the chiefs ordered to compile a map of Archipelago. The cannibals toiled for a whole year and coped with the task. But the map was too large and complicated to count all the sacred islands. So the tribe's shaman appealed to gods and asked them to help with counting the islands. And the tribe was blessed with a Programmer and a Computer, which came down to earth in a cloud of light and fire. Yes, you are this Programmer, and you are destined to live with these cannibals until you have counted the islands; then you'll be transferred back home. Remember that there may be seas inside islands, and islands inside those seas.
*******InputConstraints*******
The first input line contains four integers W, H, X and Y, separated with one or several spaces. 1 ≤ W, H ≤ 500 are respectively the width and the height of the map. 1 ≤ X ≤ W and 1 ≤ Y ≤ H are the coordinates of the point where the first shaman drowned. The next H lines contain description of the map. Each line contains W symbols describing correspondent fragments of the map. Symbol "." stands for a sea fragment and symbol "#" stands for a land fragment. Two fragments belong to the same sea if they are adjacent horizontally, vertically, or diagonally. Two fragments belong to the same island if they are adjacent horizontally or vertically (but not diagonally). Land fragments that are adjacent to the map's border are not considered as islands. Coordinates are counted from the left upper corner.
*******OutputConstraints*******
The output should contain a single integer, which is the number of the islands inside the sacred sea.
*******IOTestCases*******
input  output 

9 7 1 1
........#
.#######.
.#.....#.
.#.#.#.#.
.#.....#.
.#######.
#........
 3

9 7 3 3
........#
.#######.
.#.....#.
.#.#.#.#.
.#.....#.
.#######.
#........
 2

______________________________________________________
1251true
There is a tradition at the USU championships to call the most hardtosolve problems coffins. But to distribute coffins is also a very difficult problem. Consider a cemetery with places arranged in the form of a rectangle having N rows and M columns (1 ≤ N, M ≤ 100). At the initial moment of time (t = 0) the cemetery is empty. Incoming coffins are put in the row with empty places that has a minimal number; if there are several empty spaces in this row, then the column with the minimal number is chosen. From time to time the cemetery's clients are visited by their living friends and relatives; it is considered to be a pleasure for the clients. But it's only a headache for the cemetery manager, since because of these visitors he cannot give to new clients places that have been used. Happily, visitors are not perfect, so after some time they forget where their friends have been lying. That is why if a client was not visited for more than successive 1000 days, then on the 1001st day the manager regards the grave as empty. However, relatives of the adjacent clients (of those for whom the differences in the numbers of rows and columns are not greater than 1) may notice strange changes, so the manager puts a new client on a used place only if all the neighboring graves have not been visited for the last 100 days (this is a period of time sufficient for a neighbor's friends to forget who was lying next to him or her). If, notwithstanding all the efforts of the manager, there is no place where he can put a new client, then the client is sent to a crematorium.
We have a complete list of arriving clients and coming visitors for some period starting from the foundation of the cemetery. Basing on this information, you should determine how many clients have been sent to a crematorium.
*******InputConstraints*******
The first input line contains numbers N and M that describe the size of the cemetery. Each of the next lines describes an event. A description starts with the time of the event measured in days from the foundation of the cemetery. Then the type of the event is given: either d (arrival of a new client) or v (a visit of friends or relatives) followed with the number of the client who has visitors. The events are ordered according to their time. The input contains not more than 15000 events, and not more than 10000 of them describe arrivals of new clients.
*******OutputConstraints*******
The program should find the number of clients that have been sent to a crematorium.
*******IOTestCases*******
input  output 

2 2
1 d
1 d
1 d
1 d
300 d
500 v 2
1001 d
1002 d
1002 d
1003 v 3
1003 d
1003 d
1236 v 2
2032 v 2
2033 d  3 
Hint
 Each tomb has 2 to 8 neighbors.
 If a client was buried on day T then the tomb may be dug over on day T+1001 and may not be dug over on day T+1000.
 If a tomb was visited on day T then its neighbors may be dug over on day T+101 and may not be dug over on day T+100.
 A tomb is dug over as soon as there is an opportunity (see items 2 and 3).
 During a funeral relatives notice nothing including the neighbors.
 The clients are numbered in the the order that they arrive (including those who was sent to crematorium).
 If there is already no tomb or the client has been sent to the crematorium immediately or there is no client with the required number then a visit affects nothing.
 The next in turn client may be always burried in an empty tomb inspite of the neighbor tombs visits (the neighbors' relatives wouldn't be surprised having found out that the adjacent empty tomb is already occupied).
______________________________________________________
1252true
There is time to throw stones and there is time to sort stones…
An old desolate cemetery is a long dismal row of nameless tombstones There are N tombstones of various shapes. The weights of all the stones are different. People have decided to make the cemetery look more presentable, sorting the tombstone according to their weight. The local custom allows to transpose stones if there are exactly K other stones between them.
*******InputConstraints*******
The first input line contains an integer N (1 ≤ N ≤ 130000). Each of the next N lines contains an integer X, the weight of a stone in grams (1 ≤ X ≤ 130000).
*******OutputConstraints*******
The output should contain the single integer — the maximal value of K (0 ≤ K < N), that makes possible the sorting of the stones according to their weights.
*******IOTestCases*******
input  output 

5
30
21
56
40
17
 1

______________________________________________________
1253true
You know that many necrologues even the most heartfelt are very similar. Our partners from the ACM Company (Advanced Cemetery Management), which is a sponsor of today's thematic problem set, decided to disclose some secrets of skill. As soon as we got into the workshop of the wordpainters we found out that:
 there are N (1 ≤ N ≤ 9) sample necrologues;
 each sample necrologue has not more than 1000 symbols (capital and small Latin letters, digits, punctuation marks, spaces and carriage return marks);
 each sample may contain not more than 10 references to other samples (the reference is marked by *, which is followed by a number of a sample that is referred to; the *mark is used in the samples in no other way but as a reference mark).
A reference may be activated at a client's pleasure: the sequence *M is substituted with the sample necrologue number M (with all its references).
This system worked properly up to the moment that a very rich client entered the workshop. He wanted to add a stone to his mother'sinlaw cairn and wished a necrologue according to the sample number 1 with all the references activated (including the ones that can appear after activating the references in the first sample, and so on).
It's necessary to write a program in order to understand if it's possible to fulfill the wishes of the client and what will appear in this necrologue.
*******InputConstraints*******
The first input line contains a number N, an amount of the necrologues samples. Than follow the samples texts. Each samples starts from a new line and ends with the # symbol.
*******OutputConstraints*******
Consider the necrologue forming procedure that starts from the first sample, activates all the references than activates all the references in the result of the previous step and so on ad infinitum. If such a procedure leads to the text not longer than 10^{6} symbols (spaces and line feeds are considered as symbols) you should output the necrologue text. You should output # otherwise.
*******IOTestCases*******
input  output 

7
She w*7s *7 *2 wom*7n.
*3#
wonderful#
Everyone loved her *5.
We will miss her *5.#
Some text *6#
very much#
Another text *4#
a#  She was a wonderful woman.
Everyone loved her very much.
We will miss her very much. 
______________________________________________________
1254true
There is a city with a grid of square blocks of the N × M size. There are buildings in some blocks, some blocks are blank. John is in the block (x_{0}, y_{0}). He may move from a block to an adjacent one in horizontal, vertical or diagonal direction with velocity V. He is told over the radio the list of points where bombs are located. John is to disarm them in the same order that they follow in the list or he will die hard with a vengeance. If he can't reach some bomb he moves to the next one. All the bombs are located outside the buildings.
What minimal time will John need to finish his job if he disarms a bomb immediately?
*******InputConstraints*******
The first line contains numbers N, M, K (an amount of bombs) and V, separated with a space, satisfying the restrictions 1 ≤ N, M ≤ 75; 1 ≤ K ≤ 1000; 0.01 < V < 10.00. Then a city map follows: M lines of N symbols. The symbol '.' means a blank block, '#' stands for a building. Then follow the line that contains coordinates (x_{0}, y_{0}). The input is ended by K lines with bombs coordinates in that very order that John passed them.
*******OutputConstraints*******
You should output the single number which is the minimal time necessary to do the job. The time should be printed with two digits after a decimal point.
*******IOTestCases*******
input  output 

4 3 3 1.23
....
##..
....
1 1
1 3
4 1
4 3
 8.66

______________________________________________________
1255true
There is a custom among the Ural Mafiosi — a big Mafioso’s coffin is to be carried by all his subordinates. The length of the coffin (in meters) equals to the number of the Mafioso’s subordinates in order not to let the carriers to encumber each other. As it happens, according to the ancient custom the width of a coffin is equal to 1 meter. So, the length of a coffin shows a dead man’s authority. By the way, the Ural Mafiosi are very scrupulous in matters of authority and will not bear neighborhood with less authoritative Mafioso. So, at one cemetery it’s possible to bury Mafiosi with equal authority. According to the Mafiosi’s custom a cemetery must be square. A cemetery length must be an integer number of meters.
You are to count how many Mafiosi can be buried on the cemetery of the given size. Coffins must be parallel to cemetery borders, coffins mustn’t overlap each other and get off the cemetery.
*******InputConstraints*******
Contains two numbers — a length of the cemetery N (1 < N < 10000) and a length of a coffin K (1 < K < 10000).
*******OutputConstraints*******
The single integer number — the most amount of the coffins of the size 1×K that may be buried at the cemetery of the size N×N.
*******IOTestCases*******
______________________________________________________
1256true
In some blackblack wood at the blackblack cemetery there was a golden gravestone. This gravestone was guarded by two blackblack dogs. Each dog sits enchained near a blackblack pole and nearby in the wood there is a blackblack guard’s house. Every morning the guard leaves the house to bring the dogs plates with food. He places the plates so that the dogs may eat remaining enchained to their poles.
Compute the shortest way that the guard is to walk in order to feed both dogs (the guard may easily carry food to both dogs at the same time and may feed them in an arbitrary order).
*******InputConstraints*******
The first line contains three numbers: the distance in meters from the guard’s house to the first pole R_{1}, from the guard’s house to the second pole R_{2} and the distance between the poles R_{3}. The second line consists of one integer which is the length of each dog’s chain R_{4} (the chains of the dogs are identical). The numbers R_{i} (i = 1, 2, 3) satisfy the restriction 0 ≤ R_{i} ≤ 10000; 1 ≤ R_{4} ≤ 10000.
*******OutputConstraints*******
Output the single number which is the length of the shortest guard’s way in meters within three digits after a decimal point.
*******IOTestCases*******
input  output 

1000 2000 1000
250
 3500.000

______________________________________________________
1257true
Programmers are strange people. They don’t want to rejoice in life's pleasures, to read books, to listen to the music, to write letters to each other. The code, debug, rebuild something all the time. So our acquaintance programmer Vasechkin is not pleased with the existing software. This time he rages against the text editor. This editor can’t carry words over to the next line. What can a man do? Artemy Sidorovich, seemingly, is to teach this editor do this.
*******InputConstraints*******
The first line contains integer N (0 ≤ N ≤ 100) — an amount of hyphenation rules. Then there are N lines with the rules description. Each rule looks like “string_{1}string_{2}”, where string_{1} and string_{2} are not empty and contain only small and capital Latin letters. Summary length of string_{1} and string_{2} does not exceed 40 symbols. This record means that if a word is ended with a substring string_{1}string_{2}, then string_{2} may be carried to the next line and after string_{1} appears a hyphenmark ‘‘. Then there is a text typed by Artemy Sidorovich. A word is a sequence of small and capital Latin letters.
Any other symbols are word separators. Each line is not longer than 250 symbols. The text consists of not more than 450 lines. Each word is not longer than 40 symbols.
*******OutputConstraints*******
Output a text formatted according to the hyphenation rules with respect to the fact that the paper width is 40 symbols. Each output line can’t be wider than 40 symbols (including the hyphen ‘‘ and excluding the line feed). If there are several rules that can be used the the word is to be carried to the next line according to the rule that provides the minimal length of the carried part of the word. If a word can’t be carried to the next line so that the length of the line wouldn’t exceed 40 the word should be carried to the next line wholly. The hyphenation rules are not case sensitive (the rule “mIng” can be used in the word “SwImMiNg”). The existing line feeds, spaces and stops must be saved.
*******IOTestCases*******
input 

12
unusual
forced
real
summer
NED
homework
secret
holidays
Wizard
thEr
Lso
Holidays
Harry Potter was a highly unusual boy in many ways.
For one thing, he hated the summer holidays more than any
other time of year. For another, he really
wanted to do his homework but was forced to do it in
secret, in the dead of night. And he also happened
to be a wizard.

output 

Harry Potter was a highly unusual boy in
many ways.
For one thing, he hated the summer holi
days more than any
other time of year. For another, he
really
wanted to do his homework but was for
ced to do it in
secret, in the dead of night. And he al
so happened
to be a wizard.

______________________________________________________
1258true
During the lunchbreak the programmer Vasechkin likes to hack around his rectangular room. His way starts at his workplace and ends at the point where the thought to continue the work comes to his mind. We know that when Vasechkin runs against a wall he bounds according to the law “the angle of incidence equals to the angle of reflection”. Besides being a very straight person Vasechkin moves from wall to wall in the direct line segment. The baleful front office decided to find out how much time Vasechkin wastes during his promenades. It’s very easy to find out the time by dividing the length of the way that Vasechkin has passed over his average speed (that was measured by the front office beforehand). So it’s necessary to find out the way length! And since Vasechkin’s bumps are wellheard it’s sufficient to know the order of Vasechin’s collisions with walls. May be there is a more simple way to calculate the time wasted by the programmer but he front office believes that its solution of the problem is the most correct.
*******InputConstraints*******
The first line consists of two integers W and D — they are the width and the depth of Vasechkin’s room in meters (2 ≤ W, D ≤ 1000). The second line contains the initial Vasechkin’s position coordinates (0 < x_{0} < W; 0 < y_{0} < D), measuring from the frontleft corner of the room. The third line — the final position coordinates (0 < x_{1} < W; 0 < y_{1} < D), measuring from the frontleft corner of the room. All coordinates are integers. The fourth line contains the sequence of letters L, R, F, B, denoting the sequential Vasechkin collisions with walls — the left, right, front and back one respectively. An amount of collisions doesn’t exceed 1000. The programmer never collides a corner of his room and his initial and final positions don’t lie on walls.
*******OutputConstraints*******
Output the length of Vasechkin’s way from the initial point to the final one rounded to four decimals after the point.
*******IOTestCases*******
input  output 

10 20
9 1
1 19
FLRLRB  52.8015 
______________________________________________________
1259true
The people think about this problem for several centuries. The programmer Vasechkin’s front office decided to find it out. But the front office is the front office, so the task to find out the answer to the question "How to become a star?" was given to its subordinate Vasechkin.
It’s often happens that account’s and programmer’s notion of the problem much differ. So this time it came off not exactly how the front office has thought. Vasechkin formalized the problem as follows.
Definition. A
star is the closed broken line built by the final amount of steps of the following algorithm:
 Fix and arbitrary angle α (0 < α < π).
 The first link is (0, 0) — (1, 0).
 The second link is the resultant of the turn by the angle α counterclockwise with respect to the point (1, 0) of the first one.
 The (i + 2)nd link is the resultant of the turn by the angle α counterclockwise of the (i + 1)st one with respect to the free end (the opposite to the one that is connected to the ith link) of the (i + 1)st link.
 The algorithm stops immediately when the broken line is closed.
Definition. A number of the vertices of the star is the number of the broken line’s links.
*******InputConstraints*******
The only integer N (3 ≤ N ≤ 100000).
*******OutputConstraints*******
Output an amount of different stars with N vertices.
*******IOTestCases*******
______________________________________________________
1260true
If two people were born one after another with one second difference and one of them is a child,
then the other one is a child too. We get by induction that all the people are children.
Everyone knows that the mathematical department of the Ural State University is a big family of N persons, 1, 2, 3, …, N years old respectively.
Once the dean of the department ordered a photo if his big family. There were to be present all the students of the department arranged in one row. At first the dean wanted to arrange them by their age starting from the youngest student, but than he decided that it would look unnatural. Than he advised to arrange the students as follows:
 The 1 year old student is to sit at the left end of the row.
 The difference in ages of every two neighbors mustn’t exceed 2 years.
The dean decided that thereby the students would seem look as they were arranged by their ages (one can hardly see the difference in ages of 25 and 27 years old people). There exist several arrangements satisfying to the requirements. Photographer didn’t want to thwart dean’s desire and made the photos of all the possible mathematical department students’ arrangements.
*******InputConstraints*******
There is the integer number N, 1 ≤ N ≤ 55.
*******OutputConstraints*******
the number of photos made by the photographer.
*******IOTestCases*******
Hint
If N = 4 then there are following possible arrangements: (1,2,3,4), (1,2,4,3), (1,3,2,4) and (1,3,4,2).
______________________________________________________
1261true
The favorite resting place of the Ural programmers is Threenland island. There is only one tribulation: dollars and euro don’t go about here. So the tourists are to exchange their money into threets (the currency of Threenland). There go about 1 threet, 3 threets, 9 threets, 27 threets, …, 3^{k} threets, … Once programmer Vasechkin, after the Nthreets bill was given to him found out, that he’d got one paper of each denomination. Waiters in Threenland have a custom to keep the change. Waiters like to get the sum of money that can be presented by a set of papers in which paper of each denomination appears not more than once. Otherwise their feelings are hurt. They have a peeve on a client f they don’t get tips at all. Help please Vasechkin to pay for the dinner and not to hurt the waiter.
*******InputConstraints*******
consists of an integer N. 1 ≤ N ≤ 10^{7}.
*******OutputConstraints*******
Output two integers separated with a space – that is the sum that Vasechkin is to pay and an amount of tips. If there are several solutions choose any of them. If there is no solution output 0. Remember that Ural programmers are not rich, so Vasechkin can’t pay more than 4294967291 threets.
*******IOTestCases*******
______________________________________________________
1262true
We can’t say that all the programmers are absentminded people but it is usual to some of them… Once Artemy Sidorovich tested his program. Particularly it was to be able to define a day of the week by the date. Artemy Sidorovich inputted "October 11, 2003" and got the answer "Saturday". "Aha!" — thought Artmy Sidorovich and started to search for a mistake (the calendar that was hung in his room said that October 11th, 2003 is Monday).
After an hour Artemy Sidorovich glances up and saw big digits in the calendar: 1999. Swearing under his breath and promising to through away the old calendar he looked at the clock. The hour hand was at the mark IIII. The day was almost finished.
— It’s interesting, — thought Artermy Sidorovich, — I’ve seen many times that the number 4 is written down by the Roman numerals as IV. It turns out that a decimal number can’t be represented by the Roman number unambiguously. He looked again at the calendar and thought so:
— Let the numbers 1, 5, 10, 50, 100, 500, 1000 be denoted by the Roman numerals I, V, X, L, C, D, M. Then the number 1999 may be represented as MDCCCCLXXXXVIIII or simply MIM. Or may be MCMXCIX. It’s evident that the record MIM is the shortest. But which one is correct?
In order to adjust differences Artemy Sidorovich decided:
We'll call a pseoudoroman number the sequence of numerals: A_{1}A_{2}…A_{n}, where:
 Every numeral denotes on of the numbers 1, 5, 10, 50, 100, 500, 1000, … The different digits correspond to the different numbers. Let’s denote the number according to the numeral A as [A].
 There may be not more than 3 identical numerals one after another, if the numerals denote a power of 10 and not more than 2 identical numerals otherwise.
 In the number A_{1}A_{2}…A_{n} the following two statements are correct:
 [A_{i}] ≥ [A_{i+1}] or
 ([A_{i}] < [A_{i+1}] ≤ 10[A_{i}] and [A_{i}] = 10^{k}), where i < n.
 Before a numeral there may not be more than one lower numeral.
 [A_{i}] ≥ [A_{i+1}] ≥ [A_{i+2}], or [A_{i+2}] < [A_{i}] < [A_{i+1}], or [A_{i+1}] < [A_{i+2}] ≤ [A_{i}], where i < n − 1
 A_{1} = [A_{1}].
A_{1}A_{2}…A_{n} = A_{2}…A_{n} − [A_{1}], if [A_{1}] < [A_{2}].
A_{1}A_{2}…A_{n} = A_{2}…A_{n} + [A_{1}], if [A_{1}] > [A_{2}].
Then the number 4 will be written down as IV, and not as IIII (according to the rule 2). The number 1999 will be written down as MCMXCIX. It’s not the shortest way but every number is represented unambiguously.
*******InputConstraints*******
There is a decimal integer number N, 1 ≤ N ≤ 10^{2003}.
*******OutputConstraints*******
Output the integer K — that is an amount of numerals in pseudoroman notation of the number N.
*******IOTestCases*******
Hint
______________________________________________________
1263true
The next in turn elections are to come soon. All the fences are postered with leaflets and the mail boxes are full of throwaways. Cheeky guys are looking at us from TV’s and promise to make our life better… And programmer Vasechkin is kneedeep in work. He is to write a program that would calculate the results of voting.
*******InputConstraints*******
The first line contains a number of candidates N (1 ≤ N ≤ 10000) and a number of electors M (1 ≤ M ≤ 10000). Then M lines follow, each one contains a number of candidate that the elector voted for. The candidates are numbered with integers from 1 to N.
*******OutputConstraints*******
Output N lines. The ith line should contain the percent of electors that voted for the ith candidate (to within 2 decimals).
*******IOTestCases*******
input  output 

3 6
1
2
3
2
1
1  50.00%
33.33%
16.67% 
______________________________________________________
1264true
After a success of the previous Vasechkin’s program that allowed to calculate the results of the elections in cause of two days Artemy Sidorovich was placed at the head of the department. At the moment Artemy Sidorovich prepares a task for his subordinate — programmer Petechkin. The task is to write a very useful function that would ease the life of all the department programmers. For each integer from 0 to M the function would calculate how many times this number appears in the Nelement array. Artemy Sidorovich deems that the function should work as follows (the sample code for N = 3, M = 1):
C 
Pascal 
if (arr[0]==0) ++count[0];
if (arr[0]==1) ++count[1];
if (arr[1]==0) ++count[0];
if (arr[1]==1) ++count[1];
if (arr[2]==0) ++count[0];
if (arr[2]==1) ++count[1];

if arr[0]=0 then count[0] := count[0] + 1;
if arr[0]=1 then count[1] := count[1] + 1;
if arr[1]=0 then count[0] := count[0] + 1;
if arr[1]=1 then count[1] := count[1] + 1;
if arr[2]=0 then count[0] := count[0] + 1;
if arr[2]=1 then count[1] := count[1] + 1;

Artemy Sidorovich wants to estimate the time that Petechkin will need to execute the task. We know that Petechkin needs one second to write a line of the code (he’s fast, isn’t he?). Artemy Sidorovich doesn’t know exactly bounds for M and N. Your task is to write program that would calculate a number of seconds that Petechkin will write the code.
*******InputConstraints*******
The only line contains integers N (0 ≤ N ≤ 40000) and M (0 ≤ M ≤ 40000).
*******OutputConstraints*******
Output an amount of seconds that Petechkin needs to write the program.
*******IOTestCases*******
______________________________________________________
1265true
Riiiiing… Riiiiing…
— Wwhat the hell!!!??? — cursed major Pronin, hardly opening his eyes and looking at the watch on the bedside table. — Who wants me on Sunday at 5 a.m.?
Major took his pistol, pointed it at the telephone and squinted his left eye. The image blurred and he couldn’t aim. The yesterday party told on him.
Riiiiing… Riiiiing… — crackled the telephoneset busily.
Had overcome a great temptation, Pronin put his pistol away, reached the telephone and and took a receiver. “Whoever it is, he won’t be alive by the next morning,” — he thought at that minute. Major imagined the caller lying in the mass of blood and himself, standing next to the corpse with the fuming pistol with a smile on his face.
— Major Pronin? — he heard from the receiver.
Had listened a familiar voice, major stood at attention.
— Yes sir! Mister general, sir!
— You have an assignment. A car is waiting for you near your doorway. See you in the office in 20 minutes.
Pronin entered the general’s office after 19 minutes and 50 seconds after the call.
— A very important investigation, — said the general after a short salutation. — Possibly, a murder. Yesterday’s night a famous banker Kozlov A. E. knocked down a pedestrian. It seemed an ordinary case but the victim appeared to be his opponent at the legal process that our… “client” has won. The detained suspect claims that he didn’t notice the pedestrian in the rearview mirror while driving out of his garage. He lays stress that it was an accident. We’d better verify it. Here are the documents. You are to give a report to me personally immediately after your investigation ends. As you know our Kozlov A. E. is a mayor contender. There mustn’t be a mistake!
— Yes, sir! — bawled the major. — May I go?
Pronin looked through the onsite review protocol. Meticulous officers of the criminal investigation department worked out a very exact description of the situation. In particular, he found the metering results of the car mirror and the location of the body.
— Stop! — said the major. I can determine with the help of this data if our banker lies or not saying that he didn’t see the pedestrian!
He took all the data and left to the analytical department to his acquainted programmer. He reached the door and…
Knock, knock, Contestant!
Major has you.
*******InputConstraints*******
There are 8 real numbers within 6 digits after a decimal point, separated with one or several spaces and/or linefeeds — (−1000 ≤ x_{1}, y_{1}, x_{2}, y_{2}, x_{m1}, y_{m1}, x_{m2}, y_{m2} ≤ 1000). Those are the banker’s eyes coordinates (major calculated them by the deductive method according to the situation description worked out by the criminal investigation department officers), the victim body at the moment of blow (calculated the same way) and both ends of the mirror coordinates, respectively. It’s guaranteed that that the points (x_{1}, y_{1}) and (x_{2}, y_{2}) don’t lie on one straight line, passing through the points (x_{m1}, y_{m1}) and (x_{m2}, y_{m2}). It’s also guaranteed that the points (x_{m1}, y_{m1}) and (x_{m2}, y_{m2}) are not the same.
*******OutputConstraints*******
You are to output "VISIBLE" , if one can see the point (x_{2}, y_{2}) from the point (x1, y1) in the rearview mirror with the ends coordinates (x_{m1}, y_{m1}) and (x_{m2}, y_{m2}), or "INVISIBLE", otherwise.
*******IOTestCases*******
input  output 

1 0 0 1 0 0 1 1
 VISIBLE

0.000001 0
0 0.000001
0.000001 0.000001
0.000001 0.000001
 INVISIBLE

Hint
We must say that the rearview mirror in the banker’s car is doublesided but it reflects the light as all the mirrors (the angle of incidence equals to the angle of reflection).
______________________________________________________
1266true
Vasya’s dad, as you know, is good in math but the son instead of following his father’s steps, studies physics at school. Once Vasya asked his father to help him to solve a simple problem — to find out the resistance of the resistors system. Dad answered him: “Here is nothing to think about. You are to numerate the conductors nodes, to write the I=U/R law for each conductor. Then remember that the sum of currents at each of the nodes except the first and the last equals to zero, you may assume potential in the first node equal to one and in the last node — zero. Then you get a simple system of linear equations. Hence you find potentials in the intermediate nodes and currents between all the nodes. It’s left only to divide the voltage by the total current from the first node and…
But Vasya is not good in math, so his dad was to write the system of equations himself and to solve it. Vasya looks at the end of the book of problems and says that there is another answer. Dad tried to solve the problem again and got another answer. Vasya looked at the answer and said again: “Wrong”. Dad resolves the problem for the third time and Vasya holds his own. Dad got tired to solve the problem manually and he decided to use a computer seeing that the students of mathematical department of the Ural State university are ready to write the required program.
*******InputConstraints*******
The first line contains integers N and M; N is a number of nodes in the circuit (2 < N ≤ 20), M is the number of resistors (0 ≤ M < 1000). Each of the next M lines consists of three integers A_{i}, B_{i} и R_{i} — description of a resistor that has resistance R_{i} connecting the nodes
A_{i} and B_{i} (1 ≤ A_{i} < B_{i} ≤ N; 1 ≤ R_{i} ≤ 1000). There may be many resistors between two nodes.
*******OutputConstraints*******
Your task is to output the total resistance between the nodes 1 and N rounded within two digits after a decimal points.
*******IOTestCases*******
input  output 

4 5
1 2 15
2 4 5
1 3 10
3 4 10
2 3 1
 9.40

______________________________________________________
1267true
There is only one branchline of Yekaterinburg subway. But what a branchline! Each station is an architectural masterpiece. It is no wonder that all the guests of our city try to have time to observe our subway in detail. And, as usual, the tourists try to manage in the minimal possible time – they have much to see! In an effort to make Yekaterinburg more attractive the city administration decided to work out a program that would calculate the optimal, in respect to the time, route passing all the stations. Of course, the turn of speech “the city administration decided to work out a program” doesn’t represent the facts exactly – the administration decided and this is your team who is to work it out.
The subway contains one branchline. The trains run here with a definite interval that is evaluated by the integer number of minutes, intervals between the stations are known as well (they are evaluated by the integer number of minutes, too). You may assume that train stops at each station are instant. A tourist leaves a train instantly and it takes one second to board a train. A tourist needs 58 seconds to admire at a station. At the end of the sight seeing a tourist is to return to the starting station of his trip. He has already seen the station in the very beginning and so you are not to add the time of seeing it to the total trip time. A tourist may start his observation any time he likes, so the total trip time is to be counted out from the moment that he enters the train at the departure station.
*******InputConstraints*******
The first line contains the number of stations N (1 ≤ N ≤ 16). The stations are numbered from 1 to N. The second line consists of N − 1 nonnegative number of minutes that doesn’t exceed 10^{5}—the time that a train runs from the first station to the second. From the second to the third, and so on (surely a train runs from the ith to (i+1)st station and from the (i+1)st to the ith the same time). The third line contains the number of station that is the initial point of the trip. The fourth consists of three numbers: an interval between the trains, the departure time of the first train from the first station and the departure time of the first train from the Nth station;. all the numbers are nonnegative integers and measure minutes. The interval between the trains is nonzero and doesn’t exceed 10^{5}, and the departure time from the terminal stations doesn’t exceed the interval.
*******OutputConstraints*******
should contain the duration of the shortest possible observation of all the stations in minutes.
*******IOTestCases*******
input  output 

3
5 7
2
4 0 1  28 
______________________________________________________
1268true
The favorite occupation of Little Chu is to sleep. Strictly speaking, he is busy with nothing but sleeping. Sometimes he wakes up and than the mankind makes some Great Discovery. For the first time Little Chu woke up K days after his birth. For the second time he woke up K^{2} after his birth. For the third time — K^{3} days after his birth. This rule still holds true.
Each time whem Little Chu wakes up he looks at the calendar and remembers what day of week is today. They say that if the day of week will be repeated, than Litle Chu will start crying and his tears will flood the world.
Your task is to make the largest number of the Great Discoveries and maximally to delay the doomsday. Determine when should Little Chu be awaken for the first time if it is known that he can’t sleep more than one week after his birth.
*******InputConstraints*******
The first line contains integer T (1 ≤ T ≤ 6553) — the number of tests. Each of the next T lines contains integer N (2 < N < 65536) — the number of days in the week. N is prime.
*******OutputConstraints*******
*******IOTestCases*******
input  output 

4
3
5
7
11  2
3
5
8 
______________________________________________________
1269true
There is a problem to check messages of webboard visitors for the obscene words. Your elder colleagues commit this problem to you. You are to write a program, which check if there is at least one obscene word from the given list in the given text as a substring.
*******InputConstraints*******
The first line consists of integer n (1 ≤ n ≤ 10000) — an amount of words. The next n lines contain the list of words that we can’t allow to use in our welleducated society. A word may contain any symbol but the ones with codes 0, 10 and 13. The length of each word doesn’t exceed 10000 symbols. The total list of words doesn’t exceed 100 KB. Then there is an integer m — the number of lines of the text. A size of the text doesn’t exceed 900 KB.
*******OutputConstraints*******
the number of line and the number of position separated with a space, where an obscene word occurs for the first time. If there are no obscene words, output “Passed”.
*******IOTestCases*******
input  output 

5
dear
sweetie
angel
dream
baby
8
Had I the heavens' embroidered cloths,
Enwrought with golden and silver light,
The blue and the dim and the dark cloths
Of night and light and the halflight,
I would spread the cloths under your feet:
But I, being poor, have only my dreams;
I have spread my dreams under your feet;
Tread softly because you tread on my dreams.
 6 33 
______________________________________________________
1270true
Unicube is a remarkable set of toybricks developed by B. P. Nikitin especially for the children. Vasya’s dad made such a set to his son. Nothing special — a set of 27 colored toybricks — each edge is colored red, blue or yellow. But the coloring allows to build the cube 3×3×3 with outer surface of any of the colors. Moreover, it allows (but not easily) to build a 3×3×3 cube with chess coloring not only of the outer edges, but of all the 6 (and taking into account two sides of each section, all the 12) sections of the cube. In short this toy is for the children up to 10 years and Vasya played it with his father.
When they had built all the figures suggested in the book (which could be built) Vasya began to bother his father with the question if it was possible to build suchandsuch a figure with suchandsuch a coloring. At first father tried to build Vasya’s figures. Sometimes he succeeded and sometimes not. At the end father made a request to the students of the Ural State University to automate his distressing toil. Of course, the students equipped with computers would easily implement his request.
Your task is to write a program that given n information about the set of toybricks and the figure that is to be built, would suggest how to arrange the toybricks in order to build the figure. All the figures in the problem are the located in the threedimensional space cells cubes such that some of the edges must be of a definite color.
*******InputConstraints*******
The first line consists of one number 0 < N < 31 — the number of toybricks in the set. Then there are N lines with the toybricks description: for each toybrick in the order “front, upper, right, lower, left, back” pointed out the color of the edge number — integer from 1 to 30. Then in a new line there is an integer M — the total number of toybricks in the figure to be built (0 < M < 31). At last there are M lines with the figure description in the following format: <X> <Y> <Z> <F> <U> <R> <D> <L> <B>, where X, Y, Z — a cell coordinates (all of them from 0 to 30), F, U, R, D, L, B — demand to the colors of the toybrick in this cell in the same order as in description of the available toybricks colors (from 1 to 30, if there is 0 — then there might be an arbitrary color). Here is accepted the left coordinate system (e.g. OX axis looks right, OY — straight and OZ — up) — this is natural for Vasya building the figure on the floor.
*******OutputConstraints*******
If there is at least one solution of the problem then your program is to output an arbitrary solution in the form of M lines. The ith line is to contain the number of toybrick (in the order given in the input starting from 1) for a cell number i (in the same order as in the input starting from 1). If there is no solution, then you are to output 0.
*******IOTestCases*******
input  output 

1
6 1 3 4 5 2
1
0 0 0 1 2 3 6 5 4  1 
______________________________________________________
1271true
Attention, attention! Moscow is speaking! All the radio stations are on air. We broadcast the urgent announcement.
Today the sea trials of the new supertanker “Oil industry worker” will take place. The new development of our scientists — the system “Sailing Directions” — will be worldwide demonstrated. This system provides an optimal control of the ship without a human in a square harbor. A ship (and all the ships have a triangle form) may move from the given start position to the final one among the other ships anchored in the harbor along the shortest distance. Everything necessary for the safe test was stipulated on the “Oil industry worker”: a thick steel sheeting; electronic control system; satellite communications with the complex of coordinates determination; and sensitive radar. But as usual meddled in a human element. Vovochka, the captain’s son, secretly stole to the ship just before the presentation, set down at the computer and decided to while away the time playing his favorite computer game. As a result a computer virus penetrated into the computer and it spoilt several functions of the program “Sailing Directions”. Now the ship can’t turn around its axis. You are to write a program that provides the shortest tanker route length to the given point.
*******InputConstraints*******
The first line consists of two integer numbers DX and DY — the dimensions of the harbor (0 < DX, DY < 10^{8}). Each of the lines 24 contain two integers — the tanker coordinates (remember that the “Oil industry worker” is triangle as all the ships). The fifth line contains a point where the tanker is to come in the end (namely its vertex described in the second input line). The sixth line consists of the integer N (the number of other ships in the harbor, 0 ≤ N ≤ 40). The next 3N lines contain those ships coordinates. All the coordinates are within the harbor. The harbor corner is the point of origin. The ships don’t intersect.
*******OutputConstraints*******
the minimal length of the route rounded to three digits after a decimal point, or −1, if the “Oil industry worker” won’t be able to reach the final point because of the injuries in the navigation program.
*******IOTestCases*******
input  output 

2003 2003
20 50
10 30
30 30
140 60
1
80 1000
100 20
60 20  146.569 
Hint
 Harbor is rectangle with coordinates of corners (0,0), (DX,0), (DX,DY), (0,DY).
 Ship may not sail through harbor borders.
 Ships may touch each other and harbor borders.
______________________________________________________
1272true
A little town started to construct a subway. The peculiarity of the town is that it is located on small islands, some of them are connected with tunnels or bridges. The mayor is sure that the subway is to be under the ground, that’s why the project must use the less bridges the better. The only request for the subway is that the townsmen could get by metro (may be with changes) from every island to every island. Fortunately, we know that there is enough tunnels and bridges for it. It was decided to construct as less passages from island to island as possible to save money.
Your task given a town plan to determine the minimal possible number of bridges that is necessary to use in the subway construction.
*******InputConstraints*******
The first line contains three integers separated with a space: N (the number of islands, 1 ≤ N ≤ 10000), K (the number of tunnels, 0 ≤ K ≤ 12000) and M (the number of bridges, 0 ≤ M ≤ 12000). Then there are K lines; each line consists of two integers — the numbers of islands, connected with the corresponding tunnel. The last M lines define bridges in the same format.
*******OutputConstraints*******
the minimal number of bridges necessary for the subway construction.
*******IOTestCases*******
input  output 

6 3 4
1 2
2 3
4 5
1 3
3 4
4 6
5 6  2 
______________________________________________________
1273true
The subway constructors are not angels. The work under the ground and… Well, they are not angels. And where have you seen angels? It is all in a lifetime! Show me first somebody who has never… and then… all of us are people. And Vasya and me, too. May be we’ve overdrunked ourselves. But a little. And the ties lie crookedly… At that time they seemed to lie straight. No, we can’t say that it must be so — crisscross, but not all of them crisscross! Some of the ties lie almost properly… Crookedly you say? And I’d say normally… After the yesterday’s party? May be, may be… The ties that lie crisscross we’ll take away and it’ll be OK, the train will pass on term, not by this New Year but by the next one. There’s not much to disjoint. We’ll pull out this tie and may be that one. Next to nothing! One, two, three…
Rails are two parallel straight lines that are for the users’ accommodation parallel to the Y axis and have the coordinates X=0 and X=1. The “pellmell” ties are arbitrary segments with the vertices on the rails in the integer points of the coordinate scale. At the first elimination of defects step you are to remove several ties that would disappear all the crossings. And, of course, after the yesterday’s party the less you work the better, so you are to remove the minimal possible number of ties.
*******InputConstraints*******
The first line contains integer K (0 ≤ K ≤ 100) — the number of laid ties. Then there are K lines, each of them contains two integers Y_{1} and Y_{2} that describe the location of the next in turn tie — the tie described by the pair Y_{1} and Y_{2} connects the points (0, Y_{1}) и (1, Y_{2}). The absolute values of the numbers Y_{1} and Y_{2} don’t exceed 1000. There are no identical among the numbers Y_{1} and among the numbers Y_{2}.
*******OutputConstraints*******
the minimal number of ties that are to be removed in order to eliminate crossings.
*******IOTestCases*******
input  output 

3
0 1
3 0
1 2  1 
______________________________________________________
1274true
Your task is to write a program, which implements addition, subtraction, multiplication and division operations on fractions.
Input and output fraction format is as follows:
 the sign of a number (must be written only if its absence may lead to misrepresentation of the number),
 the integer part of a number (the integer part that equals zero must be omitted if the numerator and the denominator are present),
 a space character (must be omitted if the integer or fractional part is absent),
 the numerator (if it is not equal to zero),
 the “/” sign (written only if there is a numerator),
 the denominator (must be omitted if there is no numerator),
 the denominator cannot be equal to zero.
Samples of fractional number representation: “7 3/4”, “8 1/2”, “7/11”, “0”, “11”.
Limitations
All limitations apply for both input and output data.
The sign of a fraction: if the fraction is positive, the sign is not written; if the fraction is negative, the “” sign must be present.
The integer part and the numerator may have values ranging from 0 to 30000, the denominator may have values from 1 to 30000.
The operation sign may be one of the four possible symbols: “+” (addition), “” (subtraction), “*” (multiplication), “/” (division).
The expression is always correct, so the second operand in the division operation cannot be zero.
*******InputConstraints*******
The first line – a fraction (the first operand);
The second line – the sign of an operation;
The third line – a fraction (the second operand).
Both fractions may be reducible. The numerator is always less than the denominator.
*******OutputConstraints*******
A single line that contains an irreducible proper fraction (result) in the format described above.
*******IOTestCases*******
input  output 

3 1/6
+
2/4
 2 2/3

______________________________________________________
1275true
N knights gathered at the King Arthur’s round table. Each of them has several goblets near him. It is possible that knights have different number of goblets. The goblets are brought (and also carried away) by a servant who can carry only two goblets at a time (one for each hand). When the servant comes he can either bring two goblets, or carry them away. Note that he can serve exactly two knights that sit at a fixed distance K from each other.
For example, if K=1 then the knights who sit side by side are served.
By the end of the feast each of the knights should have an equal predefined number of goblets near him. The number of the times the servant has to come must be minimized.
Your task is to write a program, which plans the servant’s work during the feast.
Limitations
2 <= N <= 1000
1 <= K <= N1
Initial and final number of goblets near each knight is not greater than 1000 and it is always nonnegative.
The total number of servant’s visits is not greater than 30000.
*******InputConstraints*******
The first number contains three numbers separated with whitespace.
N – the number of knights,
K – “armspan” of the servant,
F – the final number of goblets each of the knights must have by the end of the feast.
The following N numbers separated with spaces or EOL characters describe the initial number of goblets near each knight. It is assumed that the knights are numbered in a cyclic manner, i.e. the first knight sits after the Nth one.
*******OutputConstraints*******
If it is impossible to reach the goal, write “–1” (without quotes) to the output. If the solution exists then the first line must contain a single integer M – the number of the servant’s visits. The following M lines must carry triples: two numbers (the numbers of knights being served) and “+” (plus) character if the goblets are brought or “–” (minus) if they are carried away. The data on each of these lines must be separated with a whitespace character.
*******IOTestCases*******
input  output 

3 1 4
1 2 3  3
1 2 +
1 2 +
3 1 + 
______________________________________________________
1276true
Train Ltd., a company that is in for railroad transportation received an order to form a train having a certain number of carriages. The problem is that Train Ltd. has carriages built in different years, therefore each of the carriages may have one of the two kinds of coupling at each side. The company also has one locomotive at its disposal.
The coupling systems for both the locomotive and the carriages are labeled as “A” or “B”. It is impossible to turn either the locomotive or a carriage in the opposite direction.
You are given information about the carriages and the locomotive. Your task is to determine the number of ways to form different trains using the given carriages. The additional requirement is that the coupling systems at each of the ends of the train must correspond to those of the locomotive.
The trains are considered different if there is at least one mismatch when they are compared from one end to another.
Example 1. Let the company possess the following carriages: “AA”, “AA”, “AB”, “BA”, “BA” and the locomotive “AB”. The train must have four carriages.
Then it is possible to form only two different trains having these carriages: “BAAAABBA” and “BAABBAAA”. It is possible to connect the locomotive at the left end of this train (using coupling “B”) or at the right one (using coupling “A”).
Example 2. Let the company now have only one carriage of each type: “AA”, “AB”, “BA”, “BB”, and the locomotive is “AA”. The train must have three carriages now.
There are three ways to form a train: “AAABBA”, “ABBAAA” and “ABBBBA”.
*******InputConstraints*******
The first line of the input contains two integers separated with whitespace character: N (0 < N ≤ 40) — the number of carriages the company has at its disposal, and K (0 < K ≤ N) — the required length of the train (measured in carriages). The following N + 1 lines describe the coupling systems for the locomotive (line 2) and the carriages. These descriptions are given as “AB”, “AA”, “BB” or “BA” (without quotes).
*******OutputConstraints*******
Write the word “YES” if it is possible to form one (or more) trains according to the given parameters, or “NO” otherwise.
If it is possible to form a train then write the number of different ways of doing so to the second line.
*******IOTestCases*******
input  output 

4 4
AB
AA
AB
BA
BA
 YES
2

4 4
BA
AA
AB
BA
BA
 NO

______________________________________________________
1277true
The Galaxy Police (Galaxpol) found out that a notorious gang of thieves has plans for stealing an extremely valuable exhibit from the Earth Planetary Museum — an ancient microprocessor. The police chiefs decided to intercept the criminals on the way from their refuge to the museum. A problem arose while planning the police operation: would it be possible for the Galaxpol staff to control all the possible routes of the criminals?
The galaxy transport system is designed as follows. Each planet has a transport station that is connected to some of the other stations via twoway teleportation channels. Transport stations vary in their sizes, so different numbers of policemen may be required to take control over different stations. In order not to upset the operation, it was decided to leave the planets that are next to the museum or the refuge without any police control.
Help the Galaxpol to place their staff at the stations in order to block all possible routes of the thieves.
*******InputConstraints*******
The first line of the input contains a single integer 0 < K ≤ 10000 — the number of policemen engaged to control the stations.
The second line has four integers: N, M, S and F delimited with whitespace character.
N is the number of stations in the galaxy (the stations are numbered from 1 to N); 2 < N ≤ 100.
M is the number of teleportation channels; 1 < M ≤ 10000.
S is the number of the planet (and the station) where the museum is; 1 ≤ S ≤ N.
F is the number of the planet (and the station) where the thieves’ refuge is; 1 ≤ F ≤ N.
The next line contains N integers (x_{1}, …, x_{N}) separated with whitespace character — the number of policemen required to control each of the stations (∑_{i=1}^{N}x_{i} ≤ 10000).
Then M lines follow that describe the teleportation channels. Each of these lines contains a pair of spacedelimited integers — the numbers of stations being connected by a channel. The channel system is designed so that it is possible to reach any station from any other one (probably it would require several channel transitions).
*******OutputConstraints*******
Write “YES” if it is possible to block all the possible routes within given limitations, and “NO” otherwise.
*******IOTestCases*******
input  output 

10
5 5 1 5
1 6 6 11 1
1 2
1 3
2 4
3 4
4 5
 NO

10
5 5 1 5
1 4 4 11 1
1 2
1 3
2 4
3 4
4 5
 YES

______________________________________________________
1278true
A new model of a mobile phone is powered by a special sound generation processor, developed expressly for this purpose.
The processor has a sound generator, an instruction pointer (IP), command memory (100 cells) and a stack (100 cells).
The instruction set of this processor consists of the two commands only:
CALL X – a subroutine call command – pushes the incremented current value of the IP (the return address) on the top of the stack and sets the IP to X;
BELL&RET – the combined command “bellreturn” – emits a sound of a fixed (unit) duration and performs control return (pops a value from the top of the stack and assigns it to the IP) or stops the execution of the program (if the stack is empty).
Any command (together with its operand) occupies exactly one memory cell.
The return address occupies only one cell on the stack, too.
The work cycle of the processor starts when it is necessary to emit a sound. At this moment the IP points to the zero memory cell. The processor stops its work if the stack is empty after emitting a sound (when BELL&RET command has been executed).
The manufacturers of the processor affirm that by using of this processor may be emitted sound of rather long duration.
Your task is to write a program, which accepts K as input and produces a program for this processor to emit a sound of duration K.
Limitations
The resulting program may have no more than 100 commands including exactly one BELL&RET command, being always the last one.
Unused memory cells following the BELL&RET command are considered free.
*******InputConstraints*******
There will be one integer number K in the input (0 < K ≤ 10^{9}) – sound duration.
*******OutputConstraints*******
Output a program for the processor described above. The execution of this program leads to emission of the sound of duration K. The first line should correspond to the zero cell of the memory, the second line – to the first cell, the third – to the second one etc. All lines, with exception for the last one, may contain only CALL commands. The operand of the CALL command is an integer (from 1 to 99) and must be separated from the command by a whitespace character.
The last line must contain the BELL&RET command.
*******IOTestCases*******
input  output 

1
 BELL&RET

4
 CALL 3
CALL 3
CALL 3
BELL&RET

______________________________________________________
1279true
A warehouse is an N×M meter sized rectangle, which is divided into sections of 1×1 meter. The warehouse is served by a roofmounted crane. 1×1 meter sized containers may be stacked one atop another in each section.
A new lot of K containers of the same kind arrived to the warehouse. It was decided to place the new containers so that the sections having less containers would be filled first.
For example, let N=3, M=3, K=10 and the number of containers in each section is represented in the table below.
In this case the new containers will be sequentially placed in sections: x1, x1, x2, x1, x2, x3, x1, x2, x3, y1. After that the heights of the sections will be as follows:
Your task is to write a program, which determines the minimum height of the sections after placing new containers.
*******InputConstraints*******
The first line contains three integer numbers N, M, K (0 < N, M ≤ 100, 0 < K ≤ 10^{7}), where N and M are dimensions of the warehouse, and K is the number of new containers.
Each of the following N lines contains M spaceseparated integer numbers ranging from 1 to 1000. These numbers are the heights of the corresponding sections.
*******OutputConstraints*******
Output the minimum height of the warehouse sections after the placement of new containers.
*******IOTestCases*******
input  output 

2 2 3
1 3
2 4
 3

3 3 10
1 2 3
4 5 6
7 8 9
 5

______________________________________________________
1280true
Michael wants to win the world championship in programming and decided to study N subjects (for convenience we will number these subjects from 1 to N). Michael has worked out a study plan for this purpose. But it turned out that certain subjects may be studied only after others. So, Michael’s coach analyzed all subjects and prepared a list of M limitations in the form “s_{i} u_{i}” (1 ≤ s_{i}, u_{i} ≤ N; i = 1, 2, …, M), which means that subject s_{i} must be studied before subject u_{i}.
Your task is to verify if the order of subjects being studied is correct.
Remark. It may appear that it’s impossible to find the correct order of subjects within the given limitations. In this case any subject order worked out by Michael is incorrect.
Limitations
1 ≤ N ≤ 1000; 0 ≤ M ≤ 100000.
*******InputConstraints*******
The first line contains two integers N and M (N is the number of the subjects, M is the number of the limitations). The next M lines contain pairs s_{i}, u_{i}, which describe the order of subjects: subject s_{i} must be studied before u_{i}. Further there is a sequence of N unique numbers ranging from 1 to N — the proposed study plan.
*******OutputConstraints*******
Output a single word “YES” or “NO”. “YES” means that the proposed order is correct and has no contradictions with the given limitations. “NO” means that the order is incorrect.
*******IOTestCases*******
input  output 

5 6
1 3
1 4
3 5
5 2
4 2
1 2
1 3 4 5 2
 YES

5 6
1 3
1 4
3 5
5 2
4 2
1 2
1 2 4 5 3
 NO

______________________________________________________
1281true
You are given a map of rivers of some continent. Every river is shown as a broken line, which begins with a river head and ends either at the point where the river flows into another one, or on the river mouth. The vertexes of the broken line are the turning points of the riverbed, or the points of tributary flow.
We will consider the river basin as a convex polygon of minimum area that contains the river and all its tributaries.
Remark. According to the definition of river basin the same territory may belong to the basins of different rivers.
Sample. A continent with three rivers is shown. The coordinates of the rivers and areas of the basins are given in the table.
River name  X  Y  Basin area 
river1  6  9  12 
5  11 
3  12 
1  7 
river2  7  9  1.5 
5  7 
5  5.5 
river3  3  10  9.5 
5  8 
4  6 
5  5.5 
6  5 
3  5 
Your task is to calculate the maximum among all river basin areas.
*******InputConstraints*******
The first line contains the number of the rivers N. The rest of the input contains N blocks describing the rivers.
Each block
i consists of:
 One line which contains ki – the number of the points in river description;
 ki lines containing pairs of real numbers xj and yj (1 <= j <= ki), separated by space characters – the coordinates of the points that describe the riverbed.
Limitations.
0 < N <= 10, ∑ki <= 1000, 1000 <= xj, yj <= 1000.
*******OutputConstraints*******
contains one number – the area of the largest basin calculated with two digit precision.
*******IOTestCases*******
input  output 

3
4
6 9
5 11
3 12
1 7
3
7 9
5 7
5 5.5
6
3 10
5 8
4 6
5 5.5
6 5
3 5
 16.00

2
4
6 9
5 11
3 12
1 7
6
3 10
5 8
4 6
5 5.5
6 5
3 5
 12.00

______________________________________________________
1282true
A game for two players is determined by its tree. The competitors make moves in turn. The first competitor starts the game. The game ends up with either a draw, or a victory of one of the players. The leaf nodes of the tree of this game may have values equal to one of three numbers: “+1” – victory of the first competitor, “–1” – victory of the second competitor, “0” – draw.
You have to find out who will win if both competitors follow the right strategy.
*******InputConstraints*******
The nodes of the tree are numbered with successive integer numbers. The root of the tree always has number 1.
The first line contains an integer N (1 < N ≤ 1000) – the number of the nodes in the game tree. Next N1 lines describe the nodes – one line for each node (with exception for the first node). The second line will contain the description of the second node of the tree, the third line – the description of the third node, and so on.
If the node is a leaf of the tree, the first symbol of the line is “L”, followed by a space, then the number of the ancestor of this node goes, another space, and the result of the game (+1: victory of the first player, –1: victory of the second one, 0: draw).
If the node is an inner one then the line contains the first symbol “N”, a space character and the number of the ancestor of this node.
*******OutputConstraints*******
contains “–1” if the second competitor wins, “+1” if so does the first and “0” if the result is a draw.
*******IOTestCases*******
input  output 

7
N 1
N 1
L 2 1
L 2 +1
L 3 +1
L 3 +1
 +1

7
N 1
N 1
L 2 1
L 2 +1
L 3 +1
L 3 0
 0

18
N 1
N 1
N 2
L 2 +1
N 3
L 3 +1
L 3 +1
L 4 1
L 4 +1
N 4
N 6
L 6 1
L 6 1
L 11 1
L 11 +1
L 12 +1
L 12 1
 +1

______________________________________________________
1283true
Venus dwarfs are rather unpleasant creatures: ugly, malicious, and meanspirited. Maybe it’s because of hard living conditions on their planet… but the fact remains: each of them is ready to sell his own mother in order to save up his pot of gold and to preserve it to the end of his days.
The dwarfs are especially nervous about the Mercury leprechauns who are always glad to empty a dwarf’s pot and to fill it with solar dust instead of the gold. The dwarfs are weaksighted and can’t distinguish dust from gold. That is why each dwarf once a year visits the Central Galaxy Bank (CGB), where experienced specialists authenticate the content of the pot taking a small commission for the job.
When the amount of gold in a pot becomes less than or equal to a certain level, the life of a dwarf has no sense anymore, so he clears the world of his wretched soul: with the remaining gold he buys in a zoo the largest Jupiter toad and creeps under it which results in crushing his chest.
*******InputConstraints*******
The input contains three integers separated with spaces. The first number is the amount of gold in a dwarf’s pot at the initial moment. The second number is the amount of gold at which the dwarf’s life becomes senseless. Both values are measured in grams and don't exceed 2^{31} − 1. The third number is the CGB commission (from 1 to 100); this is the percentage of gold that is taken from the pot as a way of payment for the verification.
*******OutputConstraints*******
The output should contain the number of years that is left to the dwarf.
*******IOTestCases*******
input  output 

19 10 50  1

1000 1 1
 688

______________________________________________________
1284true
The rules of playing space poker are so complicated that there’s no sense in trying to explain them here. We’ll say only that at the beginning of a game each player is given N (N ≤ 20) cards. Each card has a value (an integer from 1 to 100) and a suit (an integer from 1 to 10). All the cards are different. Suits with odd numbers are called blue and suits with even numbers are called yellow. The cards are dealt by a special card machine, which guarantees that the Steinpuper rule is satisfied. This rule says that if at the beginning of a game a player has X different blue suits and Y different yellow suits, then X−Y ≤ 1. The cards are given to a player one by one and the player puts them into his hand from left to right.
In order to become acquainted with his cards before the game starts, the player
arranges the cards. This means that by means of
atomic operations he attains such a disposition of his cards that
 All the cards of one suit lie one after another.
 Blue and yellow suits alternate (this is always possible due to the Steinpuper rule).
 Inside a suit the cards are ordered either in the ascending or in descending order and all the suits are ordered in the same way.
An atomic operation consists in taking one of the cards and moving it to any place (i.e., to the leftmost position, to the rightmost position, or between any two cards). Obviously, arranging the cards can be performed in many ways, but the aim is to do it with the minimal number of operations.
*******InputConstraints*******
The first line contains the number of cards N. The following N lines describe the cards in the order in which they are given by the machine. Each card is described by its value and suit separated with a space.
*******OutputConstraints*******
The output should contain the minimal number of operations necessary for arranging the cards.
*******IOTestCases*******
input  output 

5
10 1
12 2
8 2
4 4
7 4
 2

______________________________________________________
1285true
There are two starcrafts and a drop of water (nobody knows where it comes from) in a hyperspace (it’s wellknown that hyperspace has 8 dimensions). Whereas there’re anisotropic distortions because of the hyperspace transfer you may assume the ships as points (A and B) and the drop as a sphere with radius R and center in the point C. Coordinates of all the points are integer and their absolute values don’t exceed 1000. The drop is motionless. The radius R is integer positive number. The distance from the point C to the points A and B is greater than R.
The starcraft B is distressed (and motionless as well), and the starcraft A hurries to succor. You are to find out the length of the short cut from the point A to the point B not crossing the sphere (the starcraft may move along the edge of the sphere).
*******InputConstraints*******
There are three lines in succession containing coordinates of the points A, B and C respectively. Each of the lines consists of 8 positive integers. The fourth line contains positive integer R, that is the sphere radius.
*******OutputConstraints*******
Should contain the length of the short cut within 2 digits after a decimal point. There must be exactly 2 digits after a decimal point. The result is to be rounded according to the standard mathematical rules.
*******IOTestCases*******
input  output 

0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0
10 10 10 10 5 5 5 5
3
 1.00

______________________________________________________
1286true
It is well known that a starship equipped with class B hyperengine is able to travel from any planet to any other planet. But your starship got severe damage in the last travel and now its movement ability is limited. The starship’s technician determined that with the damaged hyperengine the vehicle can move from a point with coordinates (i,j) only to a point from the following list: (i+q, j+p), (i−q, j+p), (i+q, j−p), (i−q, j−p), (i+p, j+q), (i−p, j+q), (i+p, j−q), (i−p, j−q) (all the coordinates here are integers and are given in the standard intergalaxy system). Help the captain of your ship to find out if the ship is able to reach the destination planet on its own or a repair ship must be called.
*******InputConstraints*******
The first line contains two integers p and q (the two remaining discrete power rates of the damaged hyperengine) separated with a space. The second line contains the coordinates of the point where the spaceship is now. The third line contains the coordinates of the destination planet. The numbers in the second and third lines are also separated with spaces. All the numbers are integers and do not exceed 2·10^{9} in absolute value.
*******OutputConstraints*******
If the commander can move the damaged starship to the destination planet, write ‘YES’. Write ‘NO’ if a repair ship must be called.
*******IOTestCases*******
input  output 

4 6
0 0
10 10
 YES

4 6
0 0
9 9
 NO

______________________________________________________
1287true
There is a quadrate area on the Mars surface wreathed in ideal net of canals. They plot the surface into equal squares (we neglect here the surface curvature). Each side of the quadrate area plotted into N square regions.
Archeological investigations showed that there was an ancient country Yatik in this area. The inhabitants cultivated a special grain — sir — that was a basis of their food ration. There is sir of two kinds: coarsegrained and smallgrained. As a matter of fact, the end of Yatik empire started after the civil war between the fanciers of the sir sorts. But until recently noone new which of the parties won that time. The scientists look forward to guess the riddle on the grounds of the last voyage to Mars results. They found out which kind of sir was sowed the last in each square of Yatik. According to the ancient tradition sir was sowed in the sequence of squares (parallel to the northsouth or eastwest directions or at the angle 45° to them), one may suppose that the supporters of the partywinner made the longest sowings.
*******InputConstraints*******
The first input line contains a size of the square area — N (1 ≤ N ≤ 1400). Then there follow N lines. Each of them consists of N symbols. A letter “s” in the ith line and jth row means that in the according square region smallgrained sir was sowed the last, a letter “S” means that coarsegrained sir was sowed the last. You may assume that the inhabitants of the area sowed nothing but sir. Each square region was sowed with only one sort of sir.
*******OutputConstraints*******
The first line should contain a symbol “s”, if the party of smallgrained sir fanciers won in the civil war. And symbol “S”, if the winners were the fanciers of the coarsegrained sir. If it’s impossible to define a winner then the first line should contain one symbol “?”. The second line should contain integer number — the maximal length of the one sort of sir sowing.
*******IOTestCases*******
input  output 

3
SsS
sSs
SsS
 S
3

2
sS
Ss
 ?
2

______________________________________________________
1288true
— Did you call for me, general?
— Come in. You were recommended to me as a young promising programmer. As you probably know, our new … though how can you know, it's all secret. Well, our department needs a program for the analysis of … let's say signals from … let's call it a locator. This locator is designed for searching for … well, objects, which move in a layer of … no, I can't tell you in a layer of what. The locator is placed on our new … well, it also can move. You'll get the signal through the interface … though it's not important, for you it will be a sequence of numbers, each from 0 to 100. First you find in this sequence a signal from the front wall of the layer, this is a number 95 or greater. If there are several such numbers, the first of them will be regarded as the front wall. And you should take into account that someplace before this number in the sequence there must be a number not exceeding 35, otherwise it's not a wall, it's … well, you don't have to know what. Further you have to check two chan… two places where these objects can be. You'll be given for each of the places two numbers, which are the beginning and the end of the search zone counting from the front wall of the layer. You have to search in these zones for an object, that means you have to find maximal numbers in these zones of numbers. If a maximal number is equal to or greater than a certain level, which you'll be given, then you report that you have found an object and give us its location. If there are several maximal numbers in a search zone, we regard only the first of them as an object. There's another complication: the width of the layer is not constant though it has a lower bound, and you'll have to watch for a signal from the back wall of the layer. This signal is also a number 95 or greater and it must be not earlier than after a certain amount of numbers from the front wall. Note that somewhere between the front and the back wall there must be a number not exceeding 35. Of course, if you don't find a signal from the front wall, you don't have to search for objects or the back wall at all. And you don't have to search for anything behind the back wall. I suppose you understand that a signal from the back wall may fall into a search zone, then you don't regard it as an object. Is everything clear to you?
— No ifs. You're free, you may go now. Wait, one more thing: according to our recent investigations, the signal decays inside the layer, so after you have found the front layer you have to multiply each subsequent number by a decay coefficient and only then you may analyze it. The decay coefficient for the mth number is calculated by the formula 1 + (m − f) · А, where f is the location of the front wall, and the value А will be given to you later. That's all, now go.
*******InputConstraints*******
The input begins with 9 numbers separated with spaces or ends of line. These numbers are:
 the total amount of numbers in the sequence N (3 < N ≤ 10000);
 the minimal layer width D (D > 0), which is the minimal possible difference between the positions of the numbers corresponding to the back wall and the front wall;
 the beginning of the first search zone S1 (S1 > 0) (if S is the position of the front layer, then S1 + S is the first number of the search zone);
 the end of the first search zone E1 (E1 ≥ S1) (the point S + E1 must also be checked);
 the level at which an object is reported in the first zone L1 (if a signal is equal to or greater than L1, then there is an object, whose location is the first maximal number in the search zone);
 S_{2},
 E_{2},
 L_{2} are similar numbers for the second search zone;
 the parameter for calculating the decay coefficient A (0 ≤ A ≤ 0.1).
The following N lines contain a record of the signal; in each line there is one number from 0 to 100.
*******OutputConstraints*******
If the front wall of the layer was not found, you should output “No surface.”. If the front wall was found, you should output “Surface found at *.”, where there is the position of the front wall instead of * (the very first number of the sequence has position 1). In this case the next line of the output should contain your report concerning the back wall: either “Bottom found at *.”, where instead of * there is the difference between the positions of the back wall and the front wall, or “No bottom.” The next line should contain information on the first search zone. If no numbers were analyzed in this zone, you should output “Channel 1: No search.”, otherwise there should be one of the two messages: either “Channel 1: Object at *.”, if an object was found, where instead of * there is the difference between the positions of the object and of the front wall, or “Channel 1: No object.”, if no object was found. The last line should contain an analogous information on the second search zone (note that there must be “Channel 2” in this line).
*******IOTestCases*******
input  output 

10 4 1 1 50 2 2 56 0.09
9
26
96
56
21
73
73
93
96
97
 Surface found at 3.
Bottom found at 4.
Channel 1: Object at 1.
Channel 2: No object.

______________________________________________________
1289true
A crowed of volunteers dressed in the star striped overalls have filled the starport. There starcraft leaves to the thorium mines of Haron. Their job will be hard and dangerous. Will many of them return home?
This question has an exact answer. Each of the volunteers has a ticket to the starcraft. There signed a compartment number where he is to fly. The starcraft is not passenger, it departs to Haron once a month full of the volunteers and returns back loaded with thorium. This precious metal can be loaded not in all of the compartments. In such a compartments volunteers can return home. All the others are to stay at Haron... Forever.
The compartments are numbered. The numbers of the unfit compartments (and only their numbers) are so that the digit root of the first half of the number equals to the digit root of the second half. To calculate the digit root of a number one is to summarize the digits of the number; if the result is greater or equal than 10, then the digits of the result are to be summarized again; and so on until one gets a number from 0 to 9.
How many volunteers will return home?
*******InputConstraints*******
Even integer number N <= 200000 – an amount of digits used to number the compartments. There are exactly 10^{N} compartments numbered from 0 to 10^{N}1 with the leading zeros.
*******OutputConstraints*******
The number of compartments free of thorium on the way home.
*******IOTestCases*******
______________________________________________________
1290true
It is the seventh year of the terrible harmful Galaxy War... Leo Hao is one of the first defenders of his planet. He is lucky! He has gone through many troubles. For example, he stayed alive after the close combat with a meklon warrior – a perfect killing machine. He lost his left leg, right eye and spent five long months in hospital. After that incident, he had to leave the army and return to the Earth.
But Leo is lucky twice! He was able to find a good job after all these terrible incidents. Now he is a leading programmer in “U.S. Robots”. He was involved into the creation of software for zero level defense system. However, even there he was faced with interplanetary intervention! Just a few days ago it was found out that one of his coworkers is not a human! No! Physically he was a human of course, but parasitical Darloxian – agent of the most odious race in the Galaxy, captured his mind.
Obviously, mind corrupted by Darlok agent was not able to write highquality code. That why Leo is now reviewing his code. It’s terrible!!! It is not effective, slow, dirty and tangled. It must be rewritten!
However, Leo faced trouble during the exploration of the following function: input is the array of positive integer numbers. First, function prints quantity of numbers in the array onto a sheet of paper. Then quantity of numbers in the array greater than 1 is printed. Then quantity of numbers greater than 2 and so on, until the function encounters zero (zero is never printed out). After that, special mechanical manipulator puts this sheet of paper into scanner, which reads this set of numbers into memory and the described operation repeats again. After that the new paper with numbers comes out from the printer. The scanner reads these new numbers, and stores them into the array. This array is the result of the function.
Example. Input: 4 1 6.
After first stage printer prints 3 2 2 2 1 1
After second stage the result of the function will be 6 4 1
Leo feels that it can be done more effectively. Your goal is to write a program, which will be able to replace the function written by Darlok agent, and will be much faster.
*******InputConstraints*******
First line of input contains the number N (0 ≤ N ≤ 25000). The next N lines contain integers p_{i} (1 ≤ p_{i} ≤ 25000) one per line. It is the input for the described function.
*******OutputConstraints*******
Output should contain the result of the function, written by Darlok Agent.
*******IOTestCases*******
______________________________________________________
1291true
— Arny! What happened with coordinator?
Bad working coordinator was the everlasting trouble of their spaceship. Arny already had been working under this trouble while his not very attentive and responsible mate just noticed the breakage.
Judging by schematics the broken module of coordinator consists of the set of special gears connected with each other in order to transfer the traction from the kinetic generator to the lot of antenna driving engines.
Despite the extraterrestrial origin of these gears, they are connected by usual terrestrial method: the cogs of one gearwheel get into the slots between cogs of another gearwheel. So the rotation of the first gearwheel is transmitted to the second gearwheel.
After the multiple Arny’s revisions, no unnecessary gears stayed in the coordinator. It means that there is no cycles in gears connection graph. The only problem now is to check that all the gears have right directions and speeds of rotation.
*******InputConstraints*******
First line of input contains the number of gearwheels in mechanism N (1 ≤ N ≤ 1000). The next N lines contain the information about the gearwheels. ith line contains K (1 ≤ K ≤ 1000) — the number of cogs on the ith gearwheel followed by the list of gears, that are connected to the ith one. Zero ends the list.
The last line of input contains the number of gearwheel, that is connected to the kineticgenerator and the speed of its rotation V (1 ≤ V ≤ 1000). This gearwheel rotates in counterclockwise direction.
*******OutputConstraints*******
Output should contain N lines. In the ith line there is a speed of rotation of ith gearwheel in the form of irreducible fraction. Numerator and denominator of this fraction should be separated by the sign ‘/’. If speed is negative, it is assumed that the gearwheel rotates in clockwise direction (in this case the minus sign should be displayed before numerator). Otherwise the gearwheel rotates in counterclockwise direction. If speed equals zero than numerator should be equal 0 and denominator should be equal to 1. It is guaranteed that neither numerator nor denominator of all speeds will be greater than 10^{6}.
*******IOTestCases*******
input  output 

4
10 2 3 0
20 1 0
40 1 4 0
100 3 0
1 6  6/1
3/1
3/2
3/5 
______________________________________________________
1292true
BANG! Loud sound of warning sirens had filled the living and service rooms of the space cruiser “Admiral Brisko” — flagship of 3rd earth fleet. It was on the way to Sirius, when light Zerg scoutship appeared from nowhere.
— Captaaain!
— Quiet! Damage report!
— Captain! Before the enemy ship was destroyed, it had damaged our left reactor, left engine and the onboard computer. We are doomed! They will intercept and destroy us!
It was absolutely useless to even try to get to Sirius without left engine. The same was about returning to the Earth: enemy ship certainly reported their coordinates to the rest of Zerg fleet, and light Zerg interceptors could be already on the way to their feeble cruiser with only one goal. And this goal was not to help them to repair the left engine…
There was only one solution — try to reach the nearest Mars space station. Uh! You don’t know what is a Mars space station?! It is a new defensive weapon of Martians — mobile, well defended and almost invulnerable space fort for defense of strategically important routes of Union of Five (union of the Earth, Mars, Venus, Andromeda and Sirius). There are many space stations located in special way along such important routes. Every spaceweek, in order to maintain secrecy the positions of space stations change according to weekly updates of the Secret Mars Key (SMK)!
— Call the programmer here! — bark out the captain.
Let’s guess what is your role here? Right! Here is your play! You task is to write program for calculation of the distance to the next space station — “AndromedaSirius4”. It’s good that the secret algorithm of the station positioning is not a secret at all! Mmm… May be except Martians themselves… It’s quite simple: first base is located at the distance equal to SMK from the beginning of the path (Sirius in our case). The next station is located at the distance of F(SMK) from the first. Third station — at the distance of F(F(SMK)). And so on. Here F — is the Top Secret Mars Function (TSMF) It’s value is the sum of the cubes of digits its argument in decimal notation (for example F(12) = 1^3 + 2^3 = 9). So if the distance from the (I − 1)th to Ith stations is X, then the distance between Ith and (I + 1)th stations is F(X). “What a nonsense?!” — you’ll say. And you will be absolutely right, but you should not be so strict — the authors of that idea were just small pretty downy rabbits — Martians.
Your cruiser is located between (N − 1)th and Nth space stations at the distance of L from (N − 1)th station. Taking N, K (Secret Mars Key) and L as input your program should output the distance M between your cruiser and Nth station. Oh, by the way! The value of SMK is always divisible by 3. It’s normal for Martians — all their numbers are divisible by 3.
*******InputConstraints*******
Number T (2 ≤ T ≤ 33333) is placed in the first line of input — it is the number of tests for your program. It followed by the next T lines. Each of these T lines contains 3 integer numbers: N (2 ≤ N ≤ 33333), K (3 ≤ K ≤ 33333) and L (L ≥ 1).
*******OutputConstraints*******
T lines. Ith line contains the calculated value of M for Ith test case.
*******IOTestCases*******
input  output 

2
4 6 123
7 93 49  18
104 
______________________________________________________
1293true
It’s restless now on the slips of the intergalactic port’s sixth dock of planet of Torn. No longer then in a month the reconstruction of the small ironclad corvette “Eniya” will be finished. And again this battle ship and its brave team would have to struggle for the control over plutonium mines of Sibelius. The work cannot be stopped even for a second, selfpowered laser welders work round the clock. Joints of robotsrepairers fuse because of this permanent work. Nevertheless, they can’t stop not for a single moment.
Now in all this turmoil it is discovered that corvette’s thermopanels again need an urgent processing with thorium sulphide. It is known that the processing of the one square meter of the panel needs 1 nanogramm of sulphide. In general, it is needed to process N rectangular panels, which dimensions are A by B meters. It is necessary to calculate as fast as possible, how much sulphide is needed in general for the processing of all panels of “Eniya”. Moreover, do not forget, that the panels need processing of both sides.
*******InputConstraints*******
The only line contains integers N (1 ≤ N ≤ 100), A (1 ≤ A ≤ 100), B (1 ≤ B ≤ 100).
*******OutputConstraints*******
Output the weight of thorium sulphide in nanogramms needed for the processing.
*******IOTestCases*******
______________________________________________________
1294true
Four artificial satellites travel in one plane along the areostationary orbit around Mars. They have code names A, B, C and D and travel exactly in this order. Venus’s scouts for military purposes (for what particular purpose they did not say) decided to find a distance between satellites C and D. All Mars satellites could measure distances to the other satellites, that is why all what is needed to do is to penetrate in the computer system of satellite C and measure the distance to satellite D (or vice versa). Nevertheless, Martians are not so stupid and have not very bad defense. That is why all what could Venus’s scouts do is to break the defense of satellites A and B (that were older models). They measured distances from satellites A and B to satellites C and D, but now they do not know how to find the distance from C to D using these measurements. You can help them.
*******InputConstraints*******
There are 4 numbers: distances from A to D, from A to C, from B to D and from B to C in thousands kilometers (integers from 1 to 10000). Satellites can measure distance even through the planet and you may assume that orbit is a circle. Do not assume the radius of the orbit equal to 20392 km as it should be for the real areostationary orbit.
*******OutputConstraints*******
If it is impossible to find out the distance from C to D with these data, you should print "Impossible.", otherwise you are to print "Distance is X km.", where X is the required distance in kilometers (rounded to the integer number).
*******IOTestCases*******
input  output 

4 7 5 7  Distance is 5385 km. 
______________________________________________________
1295true
For five days robotloader JK546L54p has been buried under the thick layer of the Sibelian plutonium slag. The terrible strike of the atmospheric electricity has led to the depressurization of the robot’s fuel elements. Who will examine this heap of fused, broken metal here, where there is no any robot technician even at distance of a hundred parsecs? Robotcommissar even did not try to investigate what happened with JK546L54p. He ordered to throw him out into dumps and that is all. Nobody noticed that positron brains of JK546L54p were still working. If only the robopsychologist was here with JK546L54p! Of course, he would be killed with the hard gamma radiation in a moment, but… If he attached the visualizer of thoughts to the fused connectors of JK546L54p! He would see the strange performance. Robot was creating! No, I am not joking. He was investigating. Semi casual objects arose in his mind, and he examined them. Crazy properties, crazy theorems.
Besides, here is an example. Let’s take an expression 1^{n}+2^{n}+3^{n}+4^{n}. How much zeros does its decimal notation end with? JK546L54p solved this problem, and you, student, could you?
*******InputConstraints*******
The only line contains an integer n (1 ≤ n ≤ 300000).
*******OutputConstraints*******
Output the number of zeroes the decimal notation of 1^{n}+2^{n}+3^{n}+4^{n} ends with.
*******IOTestCases*******
______________________________________________________
1296true
Developed in the beginning of XXI century, hyperjump remains the primary method of transportation for distances up to thousands parsecs. But physicists have recently discovered an amazing phenomenon. They believe the duration of the hyperjump alpha phase can be easily controlled. Alpha phase is the period when hyperspacecraft accumulates its gravity potential. The larger is the gravity potential accumulated, the less energy is required to complete the hyperjump.
Your task is to write a program, which would help pilots decide when to enter and when to leave the alphaphase, in order for the hyperspacecraft to accumulate the largest possible gravity potential.
The most crude gravity field model (which you will have to use) yields the sequence of integers p_{i}, which represent field intensities at different moments in time. According to this model, if the alphaphase begins at moment i and ends at moment j, then the value of gravity potential accumulated will be equal to the sum of sequence elements at places from ith to jth inclusive.
*******InputConstraints*******
The first line of the input contains an integer N being the number of elements in the intensity values sequence (0 ≤ N ≤ 60000). Next N lines specify sequence elements, each line containing a single integer p_{i} (−30000 ≤ p_{i} ≤ 30000).
*******OutputConstraints*******
The only line of output contains the largest possible value of the gravity potential that can be accumulated by a hyperspacecraft during the alpha phase. You should assume that the initial gravity potential of a hyperspacecraft is equal to zero.
*******IOTestCases*******
input  output 

10
31
41
59
26
53
58
97
93
23
84
 187

3
1
5
6
 0

______________________________________________________
1297true
The “U.S. Robots” HQ has just received a rather alarming anonymous letter. It states that the agent from the competing «Robots Unlimited» has infiltrated into “U.S. Robotics”. «U.S. Robots» security service would have already started an undercover operation to establish the agent’s identity, but, fortunately, the letter describes communication channel the agent uses. He will publish articles containing stolen data to the “Solaris” almanac. Obviously, he will obfuscate the data, so “Robots Unlimited” will have to use a special descrambler (“Robots Unlimited” part number NPRx8086, specifications are kept secret).
Having read the letter, the “U.S. Robots” president recalled having hired the “Robots Unlimited” exemployee John Pupkin. President knows he can trust John, because John is still angry at being mistreated by “Robots Unlimited”. Unfortunately, he was fired just before his team has finished work on the NPRx8086 design.
So, the president has assigned the task of agent’s message interception to John. At first, John felt rather embarrassed, because revealing the hidden message isn’t any easier than finding a needle in a haystack. However, after he struggled the problem for a while, he remembered that the design of NPRx8086 was still incomplete. “Robots Unlimited” fired John when he was working on a specific module, the text direction detector. Nobody else could finish that module, so the descrambler will choose the text scanning direction at random. To ensure the correct descrambling of the message by NPRx8086, agent must encode the information in such a way that the resulting secret message reads the same both forwards and backwards.
In addition, it is reasonable to assume that the agent will be sending a very long message, so John has simply to find the longest message satisfying the mentioned property.
Your task is to help John Pupkin by writing a program to find the secret message in the text of a given article. As NPRx8086 ignores white spaces and punctuation marks, John will remove them from the text before feeding it into the program.
*******InputConstraints*******
The input consists of a single line, which contains a string of Latin alphabet letters (no other characters will appear in the string). String length will not exceed 1000 characters.
*******OutputConstraints*******
The longest substring with mentioned property. If there are several such strings you should output the first of them.
*******IOTestCases*******
input 

ThesampletextthatcouldbereadedthesameinbothordersArozaupalanalapuazorA

output 

ArozaupalanalapuazorA

______________________________________________________
1298true
Even paratroopers have vacations. The flight to Sirius in the depths of “The Admiral Brisco” Leo Hao whiled away with chessboard. No, he did not like usual chess game, and in addition, he did not have likely rival. The whole day Leo amused himself with an interesting thing: he tried to travel over all cells of the chessboard with the knight so that the knight visited each cell only one time. Leo attempted one time, then second, but always something was wrong. Leo became a little angry. Then he attempted board 4*4 instead of 8*8. Again failure after failure. A little angry, with the chessboard under his arm, Leo went to look for a local programmer. They two together indeed will solve this problem.
*******InputConstraints*******
There is only one number N (1 ≤ N ≤ 8) in the input.
*******OutputConstraints*******
If it is possible to travel with the knight over the square field N×N cells, then output should contain N^{2} lines with tour over the chessboard with mentioned property, otherwise the only word “IMPOSSIBLE”.
*******IOTestCases*******
input  output 

3
 IMPOSSIBLE

5
 a1
c2
e1
d3
e5
c4
d2
e4
c5
a4
b2
d1
e3
d5
b4
a2
c1
e2
c3
b1
a3
b5
d4
b3
a5

______________________________________________________
1299true
The Psylonian race is known to wield by far the most advanced military battlerobots. During the fight for Terra, it took four of these battlerobots only three hours to completely wipe out one of the ancient cities with adjacent territories. You’d better watch your back with them. The Earth Defense Forces command is utterly preoccupied. Personnel is being trained for military operations against Psylonians in case the armed conflict bursts out again. But working out good tactics requires modeling of the battlerobot’s artificial intelligence unit. And you are to help us!
The robot’s behavior turned out to be rather simple. He can use just four basic patterns: “Defense”, “Attack”, “Guard” and “Patrol”. Moreover, the behavior control unit you have to model implements a rather simple scheme: it takes some parameters as input and outputs one of the following commands for the robot to execute:
LEFT X – spend X energy units for turning left;
RIGHT X – spend X energy units for turning right;
FRONT X – spend X energy units for moving forward;
BACKWARD X – spend X energy units for moving backward;
FIRE P – spend P fire units for attacking the enemy;
STOP – nothing to do.
In all these cases X is calculated as follows: If the robot’s power supply has more than 100 energy units available, then X = 100; otherwise, X is the amount of power units remaining. Similarly, P is calculated as the smallest of two values: 20 and the actual amount of ammunition units remaining.
The most simple behavioral pattern is “Guard”. When it’s active, robot does not walk, it can only turn. It picks the most dangerous target, and determines angle between robot’s current line of sight and direction to the target. If the angle is less than 5 degrees (by absolute value), robot shoots. Otherwise, if the angle is greater than or equals to 5, the robot turns left; if the angle is less than or equals to 5, the command is to turn right. If there are no targets around, robot does nothing.
According to the “Defense” pattern, robot’s actions are defined as follows: calculate the number of enemies and multiply it by 20. If the result is not less than the amount of ammunition units left, the robot will “Retreat and Return Fire”. Otherwise, it will act as if following the “Guard” pattern.
The “Attack” pattern works as follows: If N*NP > M*MP*3, then the robot will “Advance and Return Fire”; else it will “Retreat and Return Fire”. Here: N is the total number of allied battlerobots; NP is the average amount of energy units they have remaining; M is the total number of enemy robots; MP is the average amount of energy units the enemy robots have remaining.
When the battlerobot “Retreats and Returns Fire”, it checks the angle to the most dangerous enemy. If the angle is 5 degrees or more, or there are no enemies, the robot just moves backward. Otherwise, it fires its guns.
Similarly, when the battlerobot “Advances and Returns Fire”, it checks the angle to the most dangerous enemy. If the angle is 10 degrees or more, or there are no enemies, the robot just moves forward or shoots otherwise.
When “Patrolling”, the robot follows its waypoint route, if there are no enemies. If the robot encounters enemy when patrolling, then it acts as if the “Defense” pattern was active. When following a route, robot uses this algorithm to move to the next waypoint:
If the angle to the next waypoint exceeds 20 degrees by absolute value, the robot turns into direction to waypoint. Note that it does not matter whether the robot is moving forward or backward while following the route. You should consider this when calculating the turn direction  the turn angle should be minimal.
Otherwise, if the angle to the next waypoint does not exceed 20, then the robot just moves towards the next waypoint.
*******InputConstraints*******
The first line contains two integers separated by space; the first integer is the amount of energy units available, the second one is the amount of ammunition available. The second line contains a single character, which determines the operating pattern: G stands for “Guard”, D for “Defense”, A for “Attack”, and P for “Patrol”. On the third line there are three integers: amount of enemies, average amount of energy units enemy bots possess, and angle to the most dangerous enemy target.
If the robot follows the “Attack” pattern, then the fourth line contains two integers: amount of allied bots and average amount of power units remaining in their power supplies, respectively. If the robot follows the “Patrol” pattern, then the fourth line contains only one integer: angle to the next waypoint.
Angle values range from 179 to 180 inclusive, all other integers are nonnegative and
none of them exceeds 1000.
*******OutputConstraints*******
The command for the robot using the format described above.
*******IOTestCases*******
input  output 

100 100
P
0 0 0
100
 LEFT 100

10 1000
A
1 10 30
100 1000
 FRONT 10

10 1000
G
1 10 4
 FIRE 20

______________________________________________________
1300true
There is a taxation system based on the known parameters N_{1}…N_{m}, S_{1}…S_{m+1}. in some country.
Let the total annual income of a citizen is equal to K bibriks (bibrik is a local currency). A citizen pays S_{1} percents from the sum N_{1} bibriks and less, he pays S_{1} percents of N_{1} plus S_{2} percents of (K−N_{1}) from the sum from N_{1} to N_{2}. If the income is N_{2} ≤ K ≤ N_{3} then the citizen must pay S_{1} percents of N_{1} plus S_{2} percents of (N_{2}−N_{1}) plus S_{3} percents of (K−N_{2}) and so on.
If the total annual income exceeds N_{m} then he is to pay S_{1} percents of N_{1} plus S_{2} percents of (N_{2}−N_{1}) plus … plus S_{m+1} percents of (K − N_{m}).
Let the function T(K) be the total tax from the annual income K. Moreover, in the assumed country the government pays to the citizens additional L percents as the regional coefficient. This coeficient is taxed independently from the salary.
I.e. if the salary of a citizen is R bibriks he may legally spend R−T(R) + L%*R−T(L%*R). The taxes to pay are T(R) + T(L%*R).
The calculation of the regional coefficient and all kinds the taxes is made with rounding off to two digits after a decimal point. The initial income is given within two digits after a decimal point too.
Each employer automatically retains the taxes in favor of the government from the annual income of his employee taking into account the regional coefficient.
If a citizen works at several places, in the end of a year he is to make a recalculation of the payed taxes because the sum of retained taxes in different places may be not equal to the tax from the total income.
You are to write a program that calculates and outputs the difference between the tax from the total income and the sum that is retained by all his employers.
*******InputConstraints*******
The first line contains the regional coefficient L. Then there are pairs N_{1} S_{1}, N_{2} S_{2}, …, N_{m} S_{m}, 0 S_{m+1}. Each pair is located in a separate line. The number in pairs are separated by one or several spaces. The values of L and coefficients S_{i} are given in percents (i.e. they are integers from 0 to 99).
Each of the next lines contains the total annual net profit of the citizen on some enterprise, where he worked, taking into account the regional coefficient and taxes.
The input is ended by −1. All the parameters are integer not greater than 10^{9} within two digits after a decimal point. The number of different workplaces of the citizen doesn’t exceed 30. An amount of taxation coefficients (m) is not greater than 20.
*******OutputConstraints*******
The difference between the tax from the total income and the sum that is retained by all his employers with exactly two digits after a decimal point.
*******IOTestCases*******
input  output 

15
12000000 12
24000000 20
36000000 25
48000000 30
0 35
12000000
12000000
1  937233.19 
______________________________________________________
1301true
There is a cube on the rectangular X × Y board. The cube side is equal to the side of a cell of the board. During one turn the cube may roll over its edge moving to the vertically or horizontally neighboring cell. There may be walls between some cells that are obstacles. The cube may not roll over the obstacles. The cube may not leave the board.
You are to find the minimal number of turns necessary to move the cube from the initial point with coordinates A and B to the given final point with coordinates C and D. Moreover, in the final position the upper side must be the same as it was in the initial position.
*******InputConstraints*******
The first input line contains two numbers X and Y separated with one or more spaces. The second line consists of the numbers A and B, and the third line consists of the numbers C and D presented in the same way. Then an information about the walls may follow. All the numbers are integers; 2 ≤ X,Y ≤ 10.
After a symbol ‘v’, located in a separate line, there are pairs of integers describing the walls. Here the pair of numbers M and N define a wall between the cells N, M and N+1, M. Each pair of numbers is located in a separate line.
After a symbol ‘h’, located in a separate line, there are pairs of integers describing the horizontal walls in the same way. The pair M, N define a wall between the cells N, M and N, M+1.
*******OutputConstraints*******
The only line containing the minimal number of moves. If such a displacement is impossible, you should output “No solution”.
*******IOTestCases*******
input  output 

10 2
1 1
10 1
v
2 1
6 2
h
4 1
 11

______________________________________________________
1302true
A triangle field is numbered with successive integers in the way shown on the picture below.
The traveller needs to go from the cell with number m to the cell with number n. The traveller is able to enter the cell through cell edges only, he can not travel from cell to cell through vertices. The number of edges the traveller passes makes the length of the traveller's route.
Write the program to determine the length of the shortest route connecting cells with numbers m and n.
*******InputConstraints*******
Input contains integers m and n separated with space (1 ≤ m, n ≤ 10^{9}).
*******OutputConstraints*******
Output the length of the shortest route.
*******IOTestCases*******
______________________________________________________
1303true
Given set of line segments [L_{i}, R_{i}] with integer coordinates of their end points.
Your task is to find the minimal subset of the given set which covers segment [0, M] completely (M is a positive integer).
*******InputConstraints*******
First line of the input contains number M (1 ≤ M ≤ 5000). Subsequent lines of input contain pairs of numbers L_{i} and R_{i} (abs(L_{i}), abs(R_{i}) ≤ 50000).
Each pair is placed on separate line. Numbers in the pair are separated with space(s). List of pairs is ended with pair of zeroes. i ≤ 100000.
*******OutputConstraints*******
Your program should print in the first line of output the power of minimal subset of segments which covers segment [0, M]. The list of segments of covering subset must follow. Format of the list must be the same as described in input with exception that ending pair of zeroes should not be printed. Segments should be printed in increasing order of their left end point coordinate.
If there is no covering subset then print "No solution" to output.
*******IOTestCases*******
input  output 

1
1 0
5 3
2 5
0 0
 No solution

1
1 0
0 1
0 0
 1
0 1

______________________________________________________
1304true
Two opposite vertices of the parallelepiped A with the edges parallel to the datume lines, have coordinates (0, 0, 0) and (u, v, w) correspondingly (0 < u < 1000, 0 < ;v < 1000, 0 < w < 1000).
Each of the n points of the set S is defined by its coordinates (x(i), y(i), z(i)), 1 ≤ i ≤ n ≤ 50. No pair of points of the set S lies on the straight line parallel to some side of the parallelepiped A.
You are to find a parallelepiped G of the maximal volume such that all its sides are parallel to the edges of A, G completely lies in A (G and A may have common boundary points) and no point of S lies in G (but may lie on its side).
*******InputConstraints*******
The first line consists of the numbers u, v, w separated with a space. The second line contains an integer n. The third, …, (n+2)nd line – the numbers x(i), y(i), z(i)separated with a space.
All coordinates are nonnegative, not greater than 1000 and written with not more than two digits after a decimal point.
*******OutputConstraints*******
One number – the volume of G with two digits after a decimal point. If the true volume has more than two digitrs after a decimal point you should round off the result to two digits after a decimal opint according to the common mathematical rules.
*******IOTestCases*******
input  output 

1.0 1.0 1.0
1
0.5 0.5 0.5  0.50 
______________________________________________________
1305true
Let a finite set of points M be defined on plane. The plane has a usual Cartesian coordinates. Wellformed convex hull of set M is minimal (relative to inclusion) convex set, containing M, and bounded by closed broken line. All sections of this broken line should be parrallel to axes or inclined by 45°.
Your task is to find a wellformed convex hull for a given set M.
*******InputConstraints*******
In the first line an number N (1<=N<=100 000) of following lines is written. In the second and all next lines coordinates of set’s points is written. In every line there are coordinates (two numbers separated several spaces, each number is greater or equal to 0 and less or equal to 1000) of only one point. Some points of set can overlap, thus the same coordinates can be found in different lines.
*******OutputConstraints*******
Your program should print the sequence of broken line’s vertices. Vertices should be enumretated in the counter clockwise order. As a first vertex any of them can be taken. In every line exactly one vertex’s coordinates (two numbers, separated by spaces) should be put out. Every vertex of broken line should be mentioned only once.
No three consecutive vertices of broken line should lie on a straight line.
*******IOTestCases*******
input  output 

4
3 3
3 1
2 2
4 2
 3 1
4 2
3 3
2 2

______________________________________________________
1306true
Given a sequence of N nonnegative integers. Let's define the median of such sequence. If N is odd the median is the element with stands in the middle of the sequence after it is sorted. One may notice that in this case the median has position (N+1)/2 in sorted sequence if sequence elements are numbered starting with 1. If N is even then the median is the semisum of the two "middle" elements of sorted sequence. I.e. semisum of the elements in positions N/2 and (N/2)+1 of sorted sequence. But original sequence might be unsorted.
Your task is to write program to find the median of given sequence.
*******InputConstraints*******
The first line of input contains the only integer number N — the length of the sequence. Sequence itself follows in subsequent lines, one number in a line. The length of the sequence lies in the range from 1 to 250000. Each element of the sequence is a positive integer not greater than 2^{31}−1 inclusive.
*******OutputConstraints*******
You should print the value of the median with exactly one digit after decimal point.
*******IOTestCases*******
______________________________________________________
1307true
It is custom to start each problem given at a programming contest with a 'tale', in order to link the problem to the real world as well as to fog its essence, especially if the essence seems too easy to understand. But this problem has no tale, because, first, it is quite unusual, and, second, the problem itself is about brevity.
Suppose that we are given a text. An archive of this text is a text satisfying the following requirements:
 An archive is a program in one of the programming languages allowed by the rules of the contest.
 The first line of the archive is “{PAS}”, or “/*C*/”, or “//CPP”.
 After compiling and executing an archive, we obtain the original text.
 The length of an archive is strictly less than the length of the original text.
You should write a program that outputs an archive for a given text. The archive is compiled and executed with the same parameters and restrictions that are used for compiling and executing the submitted program containing the solution of the problem. The archive might not to be in the same language as a generating it solution. Checking the problem the judges determines the archive language according to the first line («{PAS}» — Pascal/Delphi, «/*С*/» — С, «//CPP» — C++).
*******InputConstraints*******
The input contains a text of length not less than 20000 and not more than 200000 symbols. The text may contain capital and lowercase English letters, digits, punctuation signs, line breaks, and quotation marks. It is guaranteed that all the texts used as tests for this problem are literary texts in English.
Remark. The sample input is just an illustration, it does not satisfy the requirements since it is too short and not a literary text.
*******OutputConstraints*******
You should output an archive of the text given in the input.
*******IOTestCases*******
input 

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 
output 

//CPP
#include<iostream.h>
int main()
{for(int i=1;i<58;i++)cout<<i;return 0;}

______________________________________________________
1308true
I guess everyone who was in the cabinet of dean of USU mathmech faculty remembered the glass pyramid lying on the deans table. There is a legend that several students remembered this pyramid on all treir lifes as a part of a hard test. The everlasting question of every dean – to sent down a weak student or to give him the last chance.
The legend says that to get this last chance some weak students was to bring this pyramid by 70 rolls from one point of the table as closer as possible to given one another. Usually the destination point was the point of the deans table where the list of dismissed students lied. At the end of its path pyramid should stand on its base. And ideally pyramid should cover the locus of deans signature on the dismissing list.
After the student spent all his rolls or after he confessed that he couldn’t bring it closer, the dean measured the distance between the center of pyramids base and the destination point. The legend says that the student was given the desired last chance, if this distance was recordbreaking small.
May be it’s just a beautiful legend but you can go to the deans cabinet right now and make sure that the pyramid lays on the table and the golden fog charming swirls in its depth… So, just in case, you’d better to train a little in rolling the pyramid from one point to another.
You can assume that the pyramids base is square and its lateral faces – regular triangles. You can roll the pyramid by turning it from one face to the adjacent one around some edge. During this turning the edge should not slide on surface of the table. Moreover to make the test harder the dean demands you to obey such a rule: if after the turn around some edge the pyramid stands on its base, the next turn can be performed either around the same edge or around the opposite edge of the pyramids base only. There are no any restrictions on the rolling from the triangle faces.
*******InputConstraints*******
Input contains two real numbers – coordinates of the destination point. The pyramids edge length is concidered to be equal to 1 in the coordinate system. The origin coincides with the center of the pyramids base at the initial moment. The edges of the pyramids base at the initial moment are parallel to the coordinate axes.
*******OutputConstraints*******
Output should contain only one real number – the minimal possible distance between the center of the pyramids base after rolling and the destination point within 4 digits after a decimal point. The base edges may be not parallel to the coordinate axes at the final moment of time, but the pyramid should stand on its base. You can perform not more than 70 turns of pyramid during its rolling.
*******IOTestCases*******
input  output 

2.3660254037 1.3660254038  0.0000 
______________________________________________________
1309true
Dispute is a great thing! It is known that the truth is born in a dispute. Two organizers of the Ural Championship have an argument. The first of them says that computing the value of a function is a very stupid and useless problem for a programming contest. His reasoning is that when the definition of a function is known and there is enough time for the necessary preparations, it is possible to calculate the value of the function at any point very fast. The second organizer asserts that not any function can be calculated fast enough. To resolve this dispute, they decided to make an experiment. So you are to prove that you are really able to calculate the value of a function at any point fast enough.
The function f(n), where n is an integer, is defined recursively by the following expressions:
 f(0) = 0,
 f(n) = g(n, f(n1)),
where g(x,y) = ((y1)x
^{5} + x
^{3} – xy + 3x + 7y) % 9973, the symbol % denotes taking the residue of division.
*******InputConstraints*******
The only line contains an integer n (0 ≤ n ≤ 10^{8}).
*******OutputConstraints*******
You are to write a program that outputs the value f(n). And it should perform the necessary computations very fast!
*******IOTestCases*******
______________________________________________________
1310true
Have you ever heard about ACM? May be, may be… It is known to be a new project of computing machinery lab. ACM (Abstract Computation Machine) — it is a new device for quite complex computations. There is only one problem: the preproduction model doesn't work properly. So, the diagnostics is necessary to find out the reasons of the device faults.
There are some necessary facts known about the internal structure of the device. It consists of L independent registers. Each of these registers is able to store the number in the range from 1 to M. Not all registers are used for computations — some of them are used for the proposes of error control. The values of these registers are choosing in such way, that the sum of the values of all registers is divided by given number K.
The values of all registers of ACM completely define the state of device. So for proposes of diagnostics it is enough to know the values of all these registers. The problem is that developers who created the diagnostics procedure had decided to optimize the presentation of diagnostics information. So instead of simple list of register values the procedure returns the single integer — code of the state.
This code should completely describe the state of device. That's why developers decided to calculate it such way. State of device — is an arbitrary vector of length L, satisfied defined above demands. And the code of the state is just an index of this vector in the lexicographically increasing list of all possible states. (Note that the first state has index 0). It's easy to understand that such vector is really completely defines a state of the ACM.
Now the device faults and outputs code of the state. The error code has become useful! Now it is necessary to reconstruct the values of device registers from this code. As you guessed — it is your entry!
*******InputConstraints*******
The first line of input contains three numbers L, M and K (1 ≤ L ≤ 100; 2 ≤ M ≤ 50; 1 ≤ K ≤ 50)
The second line contains an integer number N — error code, returned by the ACM device.
*******OutputConstraints*******
You are to write the program that outputs the values of device registers, corresponding to the code N. I.e. L integer numbers, separated by spaces.
*******IOTestCases*******
input  output 

3 10 4
213  9 6 1 
______________________________________________________
1311true
As they say, every man must build a house, plant a tree, and grow a son during his life. So a programmer Vasechkin decided not to stay behind and to start building his own house. Vasechkin knew that his taste was not bad and thus he himself decorated the facade with brickwork. He carefully attached each brick with cement solution to a vertical wall. The result was very nice. Each brick was placed horizontally and lay on no more than one brick from the lower row. Vasechkin finished his work and thought. The time would pass and the cement solution between the bricks would crack. And one would like this beauty to remain for ages. So would it be stable even without the cement? It is necessary to perform complicated calculations, taking into consideration that all bricks have the same height, density, and width, but different lenghts. Also, a brick (or a system of bricks) with center of gravity on the edge of its support or outside it is considered to be unstable.
*******InputConstraints*******
The first line contains an integer H, which is the number of brick rows, i.e., the height of the wall (0 ≤ H ≤ 10000). Then the disposition of bricks in the rows is given, row by row, beginning from the topmost one. For each row, there is a line containing an integer K, which is the number of bricks in this row (0 ≤ K ≤ 1000); each of the next K lines contains two integers L_{i} and R_{i}, which are the coordinates of the left and right edges of the ith brick. It is known that L_{i} < R_{i} < L_{i+1} and 0 ≤ L_{i}, R_{i} ≤ 10000. The number of all bricks does not exceed 10^{6}.
*******OutputConstraints*******
You should write a program that outputs “Yes” if all the bricks are stable and “No” otherwise.
*******IOTestCases*******
input  output 

3
1
10 20
3
1 7
13 17
100 200
2
0 20
60 160  Yes 
______________________________________________________
1312true
Once I dropped into a cafe to have a snack. I took a first course (a big round plate), a salad (a smaller round plate), and a cup of tea (on a small saucer). I tried to arrange all this on a rectangular tray, which was quite a problem. “Yes, a problem! A nice problem for the Urals Championship!”, I thought.
Now you are to solve this problem. I will give you the size of the tray and of the three plates, and you should try to arrange the plates on the tray.
*******InputConstraints*******
The input contains the sides of a rectangular H and W and the radii of circles R_{1}, R_{2}, R_{3}. All the numbers are positive integers and do not exceed 10^{6}. The numbers are separated with spaces or line breaks.
*******OutputConstraints*******
You should output the only number 0 if the required arrangement is impossible. Otherwise, you should output three pairs of numbers, which are the coordinates of the centers of the plates. The coordinates must be given in the following coordinate system: the origin is the corner of the tray, the X axis is directed along the side of the tray whose length is given first, the Y axis is directed along the other side of the tray. The order of the pairs of coordinates should correspond to the order of the radii given in the input data.
*******IOTestCases*******
input  output 

800 400 200 200 50
 200.0000 200.0000 600.0000 200.0000 400.0000 350.0000

800 400 200 200 51
 0

______________________________________________________
1313true
Ural doctors worry about the health of their youth very much. Special investigations showed that a lot of clever students instead of playing football, skating or bicycling had participated in something like Programming Olympiads. Moreover, they call it sports programming! To sit near the monitor and think during 5 hours a day – is it a sport? To do it two times per year during the contests – it is more or less normal, but during the preparations to the nearest contest they spend several hours a week sitting at their computers! It would be possible to understand if they were some blockheads and dunces, but they are ones of the best students all over the world!
To save students from the harmful habit to sit at the computer for hours, Ural doctors has invented a fundamentally new monitor with diagonal trace of a beam in its electronbeam tube. Soon the winners of Ural Programming Championship would be awarded with such monitors. In the specially designed square monitor the electronic beam would scan the screen not horizontally but diagonally. The difference of the lengths of different diagonals causes such effects as nonuniform brightness, flashing and nonlinear distortions. The terrible properties of such monitors would break of the habit of looking at the monitor for hours. There is a little problem: the majority of computer video cards generates the normal “rectangle” signal for monitor. So it is necessary to develop special adapterprogram, which should transform the usual “rectangle” signal to the signal necessary for this kind of monitors. Program should be fast and reliable. That’s why the development of this program is entrusted to the participants of the Ural Championship for Sports Programming.
*******InputConstraints*******
The first input line contains the single integer N (1 ≤ N ≤ 100) – the number of pixels on the side of new square monitor. It is followed by N lines, each containing N positive integers not exceeding 100 divided by spaces. It is the image outputting by the usual video card (as you can see the color depth of new monitor is not so large – anyway usual programmer does not need more than 100 colors).
*******OutputConstraints*******
You are to write the program that outputs the sequence for input into the new monitor. Pixels are numbered from the upperleft corner of the screen diagonally from left ot right and bottomup. There is no need to explain details – look at the sample and you'll understand everything.
*******IOTestCases*******
input  output 

4
1 3 6 10
2 5 9 13
4 8 12 15
7 11 14 16  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 
______________________________________________________
1314true
The police has let a criminal slip. He has disappeared in the complicated grid of subway lines, where a chase is senseless. But the criminal does not know that there is a radio beacon attached to his clothes. The beacon sends a signal to the police from each of the stations visited or passed through by the criminal (it is not possible to detect a signal from a tunnel between stations, because the signal is too faint). Having the information about the sequence of stations passed by the criminal, the police wants to determine the stations where the criminal might be going to, in order to set watch posts at these stations.
The police knows that the criminal behaves quite logically; he has a goal (the subway station where his shelter is located), and he is moving there using one of the shortest routes. For the criminal, the length of a route is determined by the number of spans only (in the subway, a span is a tunnel between two adjacent stations). The length of a route does not depend on the lengths of spans or the number of line changes.
*******InputConstraints*******
The first line of input contains the number N of lines in the subway (1 ≤ N ≤ 50). Each of the next N lines contains a description of the corresponding line. A description starts with an integer K (2 ≤ K ≤ 50), which is the number of stations of the line. Then there are the numerical indices of the stations of the line, in the order in which the stations are on the line. The indices are integers from 1 to 32767. All the numbers are separated with spaces. If there is the same station index in the descriptions of two different lines, then these lines have an intersection at this station, where a change can be made. The last line of input contains surveillance data: an integer M ≥ 1, which is the number of stations where the criminal was registered, and M numbers, which are the indices of these stations in the order in which the criminal visited them.
*******OutputConstraints*******
You should output the indices of all stations that can be the goal of the criminal, in the ascending order, one per line.
*******IOTestCases*******
input  output 

3
2 61 62
5 75 20 85 50 61
3 10 20 30
3 30 20 85  50
61
62
85 
______________________________________________________
1315true
Speleology is a very interesting occupation. But it is also quite risky. According to the statistics, accidents are most often in spring, and many of them are caused by unexpected cave floods. In the last few years, there were several rescue operations, and each of them required quite a lot of financial resources and manpower. For the sake of economy, the Ministry for Extreme Situations issued the following order.

Order № 321/1.
For the sake of economy of resources at spring rescue operations, it is ordered to:
 Create a database of all caves and all speleologists of the Russian Federation.
 Put into geostationary orbits 12 satellites S349857 to make possible the exact determination of the location of speleologists in caves.
 Employ programmers to develop systems of satellite control.
 Create a device interacting with the satellites for automatically issuing rescue instructions to a speleologist. The device specification is given in Appendices A and B.
 Oblige speleologists to have special equipment for urgent communication with a rescue center, including the device described in Article 4.
Minister.
Appendix A. The device specification.
The device has two modules.
 The module for detecting the possibility of automated rescue (MDPAR):
 determines which part of a cave is filled with water for the known configuration of the cave;
 determines whether automated rescue is possible if the location of a speleologist and the maximal duration of his underwater stay are known.
 The module for issuing instructions for automated rescue (MIIAR):
 given the location of a speleologist, determines the direction of movement guaranteeing reaching the surface.
Appendix B. The principles of filling caves with water.
This document is a result of investigations of the Institute for Cave Studies.
A cave is filled with water according to the following rules:
 The cave is regarded as a collection of cubicles.
 A cubicle is filled with water if there is a path from this cubicle to the surface.
 A path is a sequence of cubicles that have common side.
Here only the paths having no downward segments are considered.

You are to implement the MDPAR.
*******InputConstraints*******
The first line contains 5 integers W, H, X, Y, D, which are respectively the width and depth of a cave (in cubicles), the X and Y coordinates of a speleologist, and the number of cubicles through which he can swim without air. The following H lines describe the configuration of the cave. Each of these lines contains W characters: "#" denotes a wall, i.e., a cubicle inaccessible both for the speleologist and for water, and a dot "." denotes air, i.e., a cubicle that is possibly accessible for the speleologist and can be filled with water. The module should be able to operate in the following ranges of the parameters: 1 ≤ W, H ≤ 500; 1 ≤ X ≤ W; 1 ≤ Y ≤ H. 1 ≤ D ≤ 1000. Cubicles are numbered from left to right, from bottom to top.
It is known that a speleologist can reach the surface while cave is not filled with water.
*******OutputConstraints*******
You should output "Can be rescued by himself" if the speleologist can reach the surface following the instructions issued by the MIIAR. Otherwise, you should output "Rescue operation required".
*******IOTestCases*******
input  output 

9 4 8 2 5
##..##..#
##.#.####
##......#
#########
 Rescue operation required

9 4 8 2 6
##..##..#
##.#.####
##......#
#########
 Can be rescued by himself

______________________________________________________
1316true
There is a deficit in castiron pigs in the country. They are sold at an electronic auction. Customers make their bids: announce a price at which they are ready to buy a pig (the price is between 0.01 and 10000.00 bibriks and has at most 2 digits after the decimal point). From time to time a seller puts up for sale К pigs at a price of X bibriks each. The first К customers who offered the same or higher price get one pig each.
Customers may cancel their bids (after a purchase a bid remains valid until it is canceled). Only bids made in a current month are valid, so each month a customer should renew his bid. If a seller did not sell all the pigs offered for sale, then the unsold pigs remain at his storehouse and don’t participate in the auction any more.
Each sold castiron pig makes a profit of 0.01 bibriks for the auction. Having a month's log of auction operations, you are to calculate the profit of the auction in this month.
*******InputConstraints*******
The input contains a month's operations log, one operation per line. There are three types of operations:
 “BID X” — a customer announces that he is ready to buy a pig at a price of X bibriks;
 “DEL X” — a customer cancels his bid for a pig at a price of X bibriks;
 “SALE X K” — a seller puts up for sale К pigs at a price of X bibriks.
The number of operations does not exceed 100000. All operations are correct. The last line contains the command “QUIT”.
*******OutputConstraints*******
Output the profit of the auction in the current month with 2 digits after the decimal point.
*******IOTestCases*******
input  output 

BID 0.01
BID 10000
BID 5000
BID 5000
SALE 7000 3
DEL 5000
SALE 3000 3
SALE 0.01 3
QUIT  0.06 
______________________________________________________
1317true
A special device was mounted to defend a car parking from a hail. Large hailstones are detected by a special radar and evaporated by a powerful laser. The parking lot has the shape of a convex polygon and is surrounded by a high fence. The height of the fence is h meters. The laser is located somewhere strictly inside this polygon at the ground level. The laser can evaporate hailstones, which pass at a distance of no more than d meters from it. The fence is impenetrable for laser beams. Hailstones fall vertically downward. It is known that the location and power of the laser are such that it can destroy all hailstones falling to the territory of the parking lot before they reach the level of the upper edge of the fence. The laser destroys all hailstones it can, regardless of whether they would fall inside or outside the fence. The laser can perform all the necessary operations instantly, so it can destroy several hailstones in different places practically simultaneously. Knowing the coordinates of the places where hailstones would fall, you should determine how many of them will be destroyed by the laser.
*******InputConstraints*******
The first line contains an integer n (3 ≤ n ≤ 10), which is the number of polygon vertices, and a real number h (1.00 ≤ h ≤ 100.00), which is the height of the fence. The following n lines contain pairs of real numbers, which are coordinates (in meters) of the polygon vertices. The vertices are given in the order of bypass. The next line contains the number d (h < d < 1000.00) and the coordinates of the laser. It is followed by a line containing the number of hailstones k. And the following k lines contain pairs of real numbers, which are x and y coordinates of hailstones. Absolute values of all coordinates do not exceed 1000.
*******OutputConstraints*******
You are to write a program that outputs exactly one integer, which is the number of destroyed hailstones.
*******IOTestCases*******
input  output 

4 10.00
1.00 0.00
0.00 1.00
1.00 0.00
0.00 1.00
50.00 0.00 0.00
5
0.00 0.00
1.00 1.00
2.00 2.00
3.00 3.00
4.00 4.00
 3

______________________________________________________
1318true
Given a set A of N unordered 128bit numbers. You are to compute a value of the function
where A_{k} is the k^{th} element of A, log_{10}X — the integer part of the decimal logarithm of X. We’ll assume that log_{10}0 = 0.
*******InputConstraints*******
The first input line contains a number N ≤ 5000. In the following N lines there are 128bit numbers A_{k} presented by sets of numbers (a_{1k}, a_{2k}, a_{3k}, a_{4k}), each of them lies in range from 0 to 2^{32}1. The number A_{k} can be obtained from this set according to the formula
A_{k} = 2^{96}a_{1k} + 2^{64}a_{2k} + 2^{32}a_{3k} + a_{4k}.
*******OutputConstraints*******
You are to output the value of the function for the given set.
*******IOTestCases*******
input  output 

2
0 0 0 2324
0 2332 0 0  44 
______________________________________________________
1319true
— You programmers are lucky! You don't have to deal with these terrible people – designers…
This story happened with me not so long ago. We had an order from a company building a new hotel. One day they brought a sketch to our workshop. They said that THIS was invented by a very cool designer. They said they had paid heaps of money for THIS. So, THIS had to be built. In general, THIS was not a very complex thing. It was just a square set of shelves where a porter puts guests' mail. Usual hotels have usual stands with shelves for this purpose. But this cool designer had turned everything upside down! To be more precise, not exactly upside down, but upon a corner. Moreover, the cells should be numbered from the right to the left, from the top to the bottom, looking at THIS, staying on its corner, of course. Tell me please, how can the master attach the labels with numbers to THIS? He will look on the shelves, staying normally on its side, you know. He will get tangled on the fourth label already! I will get tangled on the seventh, myself… Actually one should make such designers to label the shelves themselves.
— Oh! You are the cool programmer, I know. Couldn’t you help me? I need just a printout of the table with an arrangement of the labels in the cells. But not in such way as THIS will hang on the wall, but as THIS stands on the table of my workshop. Yes, I understand that you are busy, but you are busy every time! Preparations to the Ural Championship, tests, solutions… So what? If you can’t do it yourself – entrust your competitors with this task. They are the best programmers all over the world, aren’t they? I don’t believe that they couldn’t print the desired table having the size of the square! I would never believe it! So… Excellent! I will take the desired printout away after the contest.
*******InputConstraints*******
The input consists of the only one integer N (1 ≤ N ≤ 100), which is the size of the square.
*******OutputConstraints*******
You are to write a program that outputs the table of numbers, as they would be arranged when THIS would stand in the workshop. The label with number 1 should be in the upper right corner and other numbers should be arranged along the diagonals from the top to the bottom. The label with the last number (N*N) should be in the lower left corner.
*******IOTestCases*******
input  output 

3
 4 2 1
7 5 3
9 8 6

______________________________________________________
1320true
There is a simple graph with an even number of edges. You are to define if it is possible to present it by the set of pairs of adjacent edges (having a common vertex).
*******InputConstraints*******
contains a sequence of the numbers pairs. Each pair denotes vertices identifiers of one edge. All the identifiers are integers from 1 to 1000. You may assume that there are no loops and multiple edges in the graph defined by the input data.
*******OutputConstraints*******
“1” (without quotation marks), if the decomposition is possible and “0” otherwise.
*******IOTestCases*******
input  output 

1 2
2 3
3 1
1 10
 1

1 2
2 3
3 1
4 10
 0

______________________________________________________
1321true
"Let's go!", thought a hotel's manager entering an elevator. He pressed the tenth floor button and meditated. The day was not easy. The manager looked at the floor indicator, saw the number 9, and prepared to get out. But the elevator did not stop. The nine gave place to eight, then to seven. The manager became amazed. He remembered precisely that he had entered the elevator at the first floor. He was sure that the elevator goes up. Yes, it was not an easy day, but not to such an extent! Then he saw eight instead of seven, then there was nine again, then ten, and the elevator stopped.
The strange behavior of the elevator worried the manager. The next morning he decided that the problem was with the floor indicator, and so a repairman should be called for.
The repairman comes by a helicopter, enters the building through a window at one of the floors, gets into the elevator, and goes several floors up or down comparing the numbers on the indicator with the numbers of floors. The indicator can show several digits, and each digit place has 7 short linear indicating lamps shown here:
These lamps allow to show any digit:
The indicator does not show leading zeros and has no "extra" lamps, that is lamps which will never light up in this building. A properly working lamp switches on or off when it is needed; a defective lamp is always on or always off. During his journey in the elevator, the repairman must find all the defective lamps. For the sake of economy, it is necessary to minimize the number of passages between floors needed for this work. The floors are numbered with successive integers starting with 1.
*******InputConstraints*******
The only line contains the number of floors in the building N (4 < N < 10^{1000}).
*******OutputConstraints*******
You should output the minimal number of passages between adjacent floors that the repairman should go in the elevator in order to find all the defective lamps.
*******IOTestCases*******
______________________________________________________
1322true
The secret service detected an acting foreign agent. Frankly speaking — a spy. A surveillance showed that each week the spy sends strange unreadable texts to somebody via the Internet. In order to find out which information became available to the spy, it is necessary to decipher the texts. Secret service agents got into the spy's apartment, discovered a cipher machine, and found out the principle of its operation.
An input of the machine is a text line S_{1} = s_{1}s_{2}...s_{N}. The machine constructs all cyclic permutations of this line, i.e., S_{2} = s_{2}s_{3}...s_{N}s_{1}, ..., S_{N} = s_{N}s_{1}s_{2}...s_{N1}. Then the set S_{1}, S_{2}, ..., S_{N} is sorted lexicographically in the ascending order, and the lines are written out in this order in a column, one under another. Thus an array N × N is obtained. One of the rows of this array contains the initial word. The number of this row and the last column of the array are the output of the machine.
For example, if the initial word S
_{1} = abracadabra, then the following array is formed:
 aabracadabr = S_{11}
 abraabracad = S_{8}
 abracadabra = S_{1}
 acadabraabr = S_{4}
 adabraabrac = S_{6}
 braabracada = S_{9}
 bracadabraa = S_{2}
 cadabraabra = S_{5}
 dabraabraca = S_{7}
 raabracadab = S_{10}
 racadabraab = S_{3}
In this case, the output of the machine is the number 3 and the line rdarcaaaabb.
So it is clear how the cipher machine operates. However, no deciphering machine was found. But as the information can certainly be deciphered (otherwise there is no sense in sending it), you have to invent a deciphering algorithm.
*******InputConstraints*******
The first and the second lines contain an integer and a string respectively. This is the output of the cipher machine. Both the number and the length of the string do not exceed 100000. The string may contain only the letters az, AZ and the underlining character. The lexicographic order on the set of words is determined by the following order of characters:
ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz
The characters here are given in the ascending order.
*******OutputConstraints*******
The only line should contain the initial message.
*******IOTestCases*******
input  output 

3
rdarcaaaabb  abracadabra 
______________________________________________________
1323true
Tanya almost left for school when the telephone rang. It was the director of studies. She said the first three lessons that day had been cancelled because of an electricity failure. Tanya was the head girl of the class and the director of studies asked her to pass this news to her classmates.
— What shall I do? — thought Tanya, — there is almost no time! OK, now I’m going to call Lena, then Katya, then Masha. Lena will meantime call Vitya, she knows his telephone number, Vitya will call Masha. No, I’ll call Masha myself: let him better call Misha. Katya will call Natasha... No, it won’t work. They quarreled yesterday. Thus there is no time to think. I must immediately call Lena. Hitormiss everyone will know the news.
Tanya managed to send this message to all her classmates. But someone knew it very late and someone heard this news from several people. In the evening, Tanya decided to work out a plan of calls and not to let it ride the next time. After all, she is the head girl of the class!.. But the problem turned out to be not so easy.
Help Tanya to work out a plan of calls such that a news might be delivered to all the pupils as soon as possible. All the pupils of the class must receive the message but not more than once. It takes exactly one minute to pass the news over the telephone. At the beginning only the head girl knows the news.
To solve the problem, Tanya wrote down the list of her classmates and for each classmate the list of those whom he or she might call. You may assume that if Masha can call Katya, then Katya can call Masha, too (even if only one connection is mentioned in the list). It is known that a message can be delivered to everyone in the class through a sequence of calls.
*******InputConstraints*******
The first line contains the number of pupils N in Tanya’s class (1 ≤ N ≤ 10). The second line contains the integer number M (0 ≤ M ≤ 45). Each of the following M lines contains a pair of pupil’s names who can call each other separated by space. The last line contains the name of the head girl. All the names in the class differ and consist of no more than 20 capital and small Latin letters.
*******OutputConstraints*******
The first line of the output should contain the time in minutes necessary to spread the news to all the class according to the suggested plan. Then there is a description of the plan. The calls that should be made simultaneously must be arranged in groups. Groups should be ordered according to the time. Each group should start with a line containing the amount of calls in the group. Each call must be described in a separate line. The description of call consists of a pair of names (who calls and whom) separated by a space.
*******IOTestCases*******
input  output 

6
7
Tanya Lena
Tanya Katya
Tanya Masha
Lena Natasha
Lena Vitya
Natasha Vitya
Masha Vitya
Tanya
 3
1
Tanya Lena
2
Tanya Masha
Lena Vitya
2
Vitya Natasha
Tanya Katya

______________________________________________________
1324true
A programmer Petrov took part in a programming contest outside his home university for the first time. There he suddenly understood that using an alien computer was not so nice. The computer he was working on even didn't have his favorite text editor. And, unfortunately, the program committee had given a text formatted by a nasty DOS text editor in such a way that all right ends of lines were at the same level. Of course, it had been performed by inserting extra spaces in many places. To read such a text was a torture for Petrov. It was his luck he found the FAR Manager, which could help to delete all these disgusting spaces replacing a combination of two spaces by one space. However, there were too many spaces, so such operation had to be performed several times, because after a replacement FAR did not search for the specified combination in the processed text. For example, if there are six successive spaces, then after one round of replacement the first two spaces are replaced by one space, the middle two spaces are replaced by one space, and the last two spaces are replaced by one space. As a result, we have three successive spaces. The second round of replacement deletes the first two of the three spaces and puts one space instead of them. So we need one more round of replacement, which replaces the remaining two spaces by one space. On the whole, three rounds of replacement are needed.
Petrov had already pressed Ctrl+F7, but than had a sudden thought: what if he first replaced each three spaces by one, and then each two spaces by one? So six successive spaces would be processed by two operations only! But which sequence of operations would be optimal if a text contained rows of spaces of a length not exceeding N?
Your task is to determine the minimal number of replacement rounds (each of which replaces rows of spaces of a certain length by one space) necessary for processing a text containing sequences of spaces of any length from 1 to L. You should also offer a scheme of the replacements. If there are many such schemes, then you should choose an optimal scheme among them, i.e., a scheme that also reduces any sequence of up to K spaces (K ≥ L) for a maximal possible K. If there are several optimal schemes, you may give any one of them.
*******InputConstraints*******
The input contains an integer L, L < 2000000, which is the maximal length of a row of spaces in the text.
*******OutputConstraints*******
The first line of the output should contain an integer R, which is the minimal number of replacement rounds. The next R lines should describe an optimal scheme of replacements. Each of these lines must contain the length of row which are replaced by one space during the correspondent round.
*******IOTestCases*******
______________________________________________________
1325true
— Hello, may I speak to Petrov, please? Hello, my darling… You know, there was a little accident at our home… No, no, don't worry, your computer was not damaged. It is only a bit dirty there now. Well, I should say it's very dirty there and I'm at my Mom's now. Of course, I'll clean it… When? Well, maybe when I have my vacation. What? Well, when we are back from Turkey… the next vacation then. I'll stay at Mother's until then, and you may live here also. No, no, I don't insist, sure, you may stay at home if you wish so. I prepared boots for you, they are at the door. But please, don't make it worse, before you step on a clean floor, change your boots, put on your slippers, they are at the door also. Take them with you when you walk through the dirt. And when you walk on a clean floor, take the boots with you. You see, the dirt is in different places. OK, my love? Thank you!
It is not a great pleasure to change boots each time you get from a clean floor to a dirty floor and vice versa, it's easier to walk extra several meters. So it is necessary to find a way of getting from one place in the apartment to another with the minimal possible number of boots changes; and among these paths the shortest one must be found.
To begin with, it is natural to determine an optimal way of passing the Most Important Route: from the computer to the refrigerator.
*******InputConstraints*******
The first line of the input contains two integers M and N, which are dimensions of the apartment (in meters), 1 <= N, M <= 500. The two integers in the second line are the coordinates of the computer, and the third line contains the coordinates of the refrigerator. Each of the following M lines contains N symbols; this is the plan of the apartment. On the plan, 1 denotes a clean square, 2 denotes a dirty square, and 0 is either a wall or a square of impassable dirt. It is possible to get from one square to another if they have a common vertex. When you pass from a clean square to a dirty one or vice versa, you must change shoes. The computer and the refrigerator are not on the squares marked with 0.
The upper left square of the plan has coordinates (1, 1).
*******OutputConstraints*******
You should output two integers in one line separated with a space. The first integer is the length of the shortest path (the number of squares on this path including the first and the last squares) with the minimal possible number of boots changes. The second number is the number of boots changes. If it is impossible to get from the computer to the refrigerator, you should output 0 0.
*******IOTestCases*******
input  output 

3 7
1 1
3 7
1200121
1212020
1112021  8 4 
______________________________________________________
1326true
Programmer Petrov has a hobby to collect beerbottle taps. There’s nothing unusual — he knows hundreds of programmers that like beer. And they collect taps, too. Not everyone, but some of them.
Frankly speaking, he has bought a part of his collection. But unfortunately he hasn’t got some rare taps to complete his collection. He has found some programmers over the Internet that are ready to sell him these taps. Some of the programmers sell the taps in sets with big discounts.
It’s left to find an optimal offer. Petrov can explain to his wife why he is to store the taps but he won’t be able to prove why he is to spend money for the collection. So he is to buy the taps as cheap as possible.
Petrov has written down all the variants and has started thinking. There’s no way to find out the solution of the problem without a program!
*******InputConstraints*******
The first line contains an integer N, an amount of available taps (1 ≤ N ≤ 20). The following N lines contain prices of bottles with the taps if one buys them in stores. The next line contains an integer M (0 ≤ M ≤ 100) — an amount of offers to sell the taps. The following M lines describe the sets. The first number of each line is the price of the set and the second one is the amount of taps in the set. Then there are numbers of the taps in the set (each number lies in the range from 1 to N). The numbers in a set are unique. All the prices are positive integers and do not exceed 1000. The last line begins with the amount of taps that Petrov plans to buy. Then their numbers follow separated by spaces. These numbers are unique, too.
*******OutputConstraints*******
Output the minimal sum of money that Petrov should spend on obtaining the necessary taps.
*******IOTestCases*******
input  output 

4
10
11
12
13
3
17 2 1 3
25 3 2 3 4
15 2 3 4
3 1 3 4
 25

______________________________________________________
1327true
"Janus Poluektovich (I don't remember anymore whether A or U) used the machine only once. He brought with him a small semitransparent box, which he connected to the Aldan. In approximately ten seconds of operation with this device, all the circuit breakers blew, and Janus Poluektovich apologized, took his box, and departed."
Sasha Privalov, a young programmer working in the SRITS (Scientific Research Institute for Thaumaturgy and Spellcraft), finds his job rather enjoyable. Indeed, he is the only programmer of such a wonderful machine as Aldan3  that's a refreshing shift from a dull job in Leningrad. There is just a single problem, and the problem's name is Janus Poluektovich.
On Privalov's first workday, Janus burdened Aldan with the task of fourdimensional convolution in the conjuration space. Aldan worked for a while, flashing its lights and rewinding tapes, then a fuse blew and the machine shut down. Well, replacing fuses is something even a programmer can do. But Janus is rather absentminded, and he, being lost in thoughts about his convolution problem, forgot about the weak fuse next day. So, on a third day Janus launched his program again, blowing another fuse. The fourth day went calmly, but on a fifth day one more fuse had to be replaced. And Janus is still not going to give up…
Nevertheless, these accidents don't bother Sasha, as long as he has enough spare fuses.
Your task is to help Sasha in making the requisition for spare parts. The requsition is made for a specific period  from the Ath workday to the Bth workday inclusive. You should calculate, how many fuses Janus is going to blow with his programs in the specified period of time.
*******InputConstraints*******
The first line contains an integer A. The second line contains an integer B. 1 ≤ A ≤ B ≤ 10000.
*******OutputConstraints*******
The output should contain one number  the amount of fuses that will be blown by Janus in the interval from day A until day B.
*******IOTestCases*******
input  output 

1
5
 3

100
200
 50

______________________________________________________
1328true
Today almost everybody knows about the scientific research department of the Night Watch, located in Solovetz city. Due to the artful actions of Zavulon (the boss of Day Watch, you know) this Scientific Research Institute for Thaumaturgy and Spellcraft (SCITS) was absolutely declassified and removed from secret list already in 60s.
However this fact had not made any harm to its ability of research work. For example right now 3^{rd}level wizard Vitka Korneev tests a new battlespell of fireball in his lab in SCITS. Oh… fireball is such a ball of fire that is used for… mmm… for neutralization of undesirable consequences.
New fireball appeared to be just an ingenious invention! First of all due to the incongruence of transgression inside the incubtransformation’s psyfield it has a zero radius. But its greatest characteristic is the ability of remaining stable during the predefined number of collisions with obstacles. This characteristic is called Nstability: fireball is Nstable if it stays stable after N collisions but explodes after (N + 1)^{th} collision. So, you may consider, that Nstable fireball loses one level of stability and becomes (N − 1)stable after each collision with a wall. For example ordinary fireball is 0stable. So with this invention it became possible to strike an enemy with fireball after several ricochets from the walls. So the military value of this invention is beyond questions. In addition, new Nstable fireball (N > 0) has quite unusual behavior: After collisions it rebounds only from concrete walls! So, it easily flies through any other obstacles. (The theory ties this fact with the accumulation of bioemotional energy by all static constructions of living quarters). This fact, as you can guess, causes additional military value of new invention: now it is not necessary to provide clear trajectory for the thrown fireball — it will fly thwough any obstacles before it damages the target.
But it is long way from the first prototype to the mass usage. First of all it is necessary to investigate the trajectory of the fireball flight. The following experiment is prepared for this purpose: in the rectangle room two points A and B are being chosen at random. One wizard stands at the point A and the target is placed at the point B. Wizard creates Nstable fireball while his assistant calculates the direction of throw with the help of special program. The direction of throw is selected such way that thrown fireball rebounds from the walls exactly N times and then hits the target. At the same time it should do this with the shortest trajectory (i.e. as quickly as possible).
So, you are to write this special program for direction calculation. The scientists of SCITS tell that all fireballs rebound from the walls according to the law: “angle of incidence equals angle of reflection”. And after collision with room’s corner it rebounds exactly in the opposite direction. Moreover, the theory of fireballs says that, due to continuity, one collision with corner equals two collisions with walls. So, 2stable fireball explodes after the second collision if the first was with room’s corner. And finally you may assume that the fireball is a point moving in straight lines with constant velocity.
*******InputConstraints*******
The first line contains two numbers — width and length of the room. The second line contains the number N — Nstability of fireball. The third line contains four numbers — coordinates of points A and B.
All numbers are integers and are separated by one or more spaces. Points A and B lie inside the room but not on its border. The room’s width and length do not exceed 1000 and are greater than 1. N is between 0 and 10 inclusive.
*******OutputConstraints*******
Angle in degrees (with 2 digits after decimal point), that gives the desired direction of fireball. If there are several such angles your program should output the minimal one.
Angle and coordinates are measured as shown on the figure.
*******IOTestCases*******
input  output 

1000 10
3
101 5 128 8  45.00 
Hint
Characters and background are taken from books “Monday Begins on Saturday” (Arkady and Boris Strugatsky) and tetralogy “Night Watch”, “Day Watch”, “Twilight Watch” and “Final Watch” (Sergey Lukyanenko).
______________________________________________________
1329true
It is very hard for one person to learn all galactic history. But, on the other hand, every diplomat who wants to hold a more important post in a galactic empire must know the subject well. For example, letting a spoon fall among highrankers of the star system Arcturus means offending them awfully. (Didn’t you hear that the last conflict between systems Arcturus and Alpha flamed up because of the only shattered glass?)
Fortunately, the solution was found in the Galactic Academy. For diplomats of the lower rank it is enough to learn just a single branch of history – the one that concerns only the cluster of star systems, in which he is going to work. (Diplomats of the lower rank negotiate only with planets that are located in one star cluster. How come we didn’t guess this earlier?)
Taking this very important observation into consideration, it was decided to replace a single intergalactic course with several separate courses, each covering only the part of history that refers to only one star cluster. Of course, it is necessary to learn history in chronological order, beginning from the origin of humanity. That’s why the history of the Earth needs to be included in all collections of separate histories. Then things become complicated: for example, emigrants from Centaurus system colonized the star system of Herdsman, so the textbook on the history of Herdsman system has to contain the early history of Centaurus system. In order to decide, in which textbooks which phases of history should be included, historians of Galactic Academy divided general intergalactic history into many small milestones. Then all milestones were combined into one big tree (omnipresent biologists helped historians in this work, as they had always been using these trees). The milestone referring to early history of the Earth (before the space colonization) was declared the root. Milestones referring to history of star systems close to solar system appear to be its sons (because these systems were colonized by emigrants from Earth) and so on. That’s all! To determine milestones that have to be included in a particular textbook it is only required to determine quickly, whether the milestone A is located in a subtree with the root in milestone B.
*******InputConstraints*******
In the first line there is a number N (N ≤ 40000), which defines the total number of milestones. In the next N lines there are descriptions of each milestone.
Each milestone is defined by two numbers: ID – an unique numerical identifier of a milestone and ParentID – identifier of the milestone which is its father in a tree. ParentID for the root equals to 1.
(N+2)^{th} line contains number L (L ≤ 40000) – amount of queries. The next L lines contain descriptions of queries: on each line there are two different numbers A and B. All identifiers lie between 0 and 40000.
*******OutputConstraints*******
For each query it is necessary to write in separate line:
 1, if milestone A is a root of subtree which contains milesone B.
 2, if milestone B is a root of subtree which contains milesone A.
 0, if no one of the first two conditions is true.
*******IOTestCases*******
input  output 

10
234 1
12 234
13 234
14 234
15 234
16 234
17 234
18 234
19 234
233 19
5
234 233
233 12
233 13
233 15
233 19
 1
0
0
0
2

______________________________________________________
1330true
— Superstitions, prejudices… — said the stranger absentmindedly. — Indolence of mind and envy, envy, shaggy envy… — He interrupted himself. — I beg your pardon, Aleksandr Ivanovich, I would dare to ask your permission to take away this ladle. Unfortunately, iron is almost not transparent for hyperfield, and growth of the hyperfield intensity in a small volume…
After the Vybegallo’s “ideal consumer” incident in the Scientific Research Institute for Thaumaturgy and Spellcraft, an automatic security system is being put into operation urgently. It is to guarantee that in any case the total hyperfield intensity won’t exceed a critical value. They pin hopes on Sasha Privalov and his Aldan machine to automagically process readings of sensors that are located all over the Institute.
All the sensors are numbered with integers ranging from 1 to N (1 ≤ N ≤ 10000). The reading of ith hyperfield intensity sensor is integer k_{i} (10000 ≤ k_{i} ≤ 10000). Aldan is to process quickly queries like "What is the sum of intensities read from the sensors with numbers from i to j (i ≤ j)? The number of queries Q is expected to be rather large (0 ≤ Q ≤ 100000).
*******InputConstraints*******
The first input line contains integer N. The following N lines contain k_{i} numbers (one at a line). Then there are the integer Q and Q pairs of numbers i, j (each pair is in a separate line).
*******OutputConstraints*******
should contain Q lines with the sums of the corresponding intensity sensors readings.
*******IOTestCases*******
input  output 

5
1
2
3
1
4
3
1 5
4 4
1 4  9
1
5 
______________________________________________________
1331true
— We call this satellite Vladya. As you know Vladislava has one more satellite, artificial as well, and also extraterrestrial. It is smaller. We call it Slava, you get it? The planet is called Vladislava and it is natural to call its satellites Vladya and Slava, isn’t it?
— Yes, of course,— said Gorbovsky. He was familiar with this beautiful argumentation. He heard it for the third time. — You suggested it very wittily, August. Vladya and Slava — Vladislava. Splendid!
— You call these satellites respectively Yone and Ytwo on the Earth,— continued Bader,— Vladya and Slava. But we, we call them other way. We call them Vladya and Slava.
He looked at Valkenstein strictly. Valkenstein worked his jaws. As far as he knew “we” ment Bader himself and only Bader.
N artifacts of extraterrestrial civilizations were found on the planet Vladislava.
The scientific spacecraft settled on the planet’s orbit and launched automatic probes, which found out that a stormboat will be able to touch down only in one of M points on the planet’s surface because of the rough relief. Inasmuch as the transportation on the planet’s surface takes much time, it is reasonable to find the nearest landing place for each artifact.
*******InputConstraints*******
The first line contains integers N and M (1 ≤ N, M ≤ 5000) — amounts of artifacts and landing grounds respectively. Then there is positive real R ≤ 1000 — that is the planet radius. Each of the following M lines consists of latitude W_{i} and longitude L_{i} of one of the landing grounds, W_{i}, L_{i} are real numbers, W_{i} ≤ 90, L_{i} ≤ 180. The next N lines contain artifacts coordinates — latitude w_{i} and longitude l_{i} — real numbers, w_{i} ≤ 90, l_{i} ≤ 180.
All real numbers are rounded to 6 digits after decimal point.
*******OutputConstraints*******
You are to output exactly N lines. ith line should contain the distance between the i^{th} artifact and the nearest landing ground within two digits after a decimal point.
*******IOTestCases*******
input  output 

1 2
1
0 0
1 1
0 0
 0.00

2 1
1
0 0
0 90
0 45
 1.57
0.79

______________________________________________________
1332true
The last survivor was a certain Pitirim Schwartz, an erstwhile monk and inventor of the forked musket rest, who was selflessly laboring on the geniebomber project. The essence of the project was to drop on the enemy cities bottles with genies who had been held imprisoned no less than three thousand years. It is well known that genies in their free state are capable only of destroying cities or constructing palaces. A thoroughly aged genie, reasoned Schwartz, was not about to start building palaces, and therefore things would go badly for the enemy. A definite obstacle to the realization of this concept was an insufficient supply of bottled genies, but Schwartz counted on overcoming this through the deep dragging of the Red and Mediterranean Seas.
The geniebomber project has eventually entered the experimentation stage. Research fellows’ doubles have constructed N cities in the testing area. Each of these cities is a circle with a radius of r. As M. M. Kamnoedov provided only one bottled genie for the experiment, experimenters decided to demolish as many cities as possible for the sake of science. It is generally known that a genie demolishes everything in the range of R around the bottle’s touchdown point. Any city contained completely within this demolition area is ruined. Before the experiment is conducted, you are required to find the maximum possible number of cities that one genie can ruin.
*******InputConstraints*******
The first line contains the number N of cities (1 ≤ N ≤ 100). The following N lines contain the coordinates x_{i}, y_{i} of city centers (x_{i}, y_{i} are integers, x_{i}, y_{i} ≤ 10000). City centers don’t coincide with each other.
The last line contains radius R of the genie’s area of destruction and the city radius r (1 ≤ R, r ≤ 10000). R and r are integers.
*******OutputConstraints*******
Output the maximum number of cities that can be destroyed by one bottled genie.
*******IOTestCases*******
input  output 

3
0 0
0 4
4 0
3 1
 2

5
0 0
0 1
0 2
0 3
0 4
1 1
 1

______________________________________________________
1333true
Thanks to your effortful work, the geniebomber has successfully passed all the tests. But Modest Matveevich Kamnoedov has some more problems to solve. He is concerned with efficiency of the bombing. Basically, he needs to calculate the area of a testing ground that a genie bombardment can cover.
We will assume that the testing ground is the portion of the plane defined by two inequalities: 0 ≤ x ≤ 1, 0 ≤ y ≤ 1. One genie blast zone covers a circle on the plane. Point of the testing ground is covered with the bombardment if it lies within one or more blast zones. You have to calculate the coverage efficiency – that is, the portion of the testing ground area that is covered with the bombardment.
*******InputConstraints*******
In the first input line there will be one number N, which is the number of bombs dropped (N ≤ 10). The following N lines contain three numbers x_{i}, y_{i}, r_{i} each, where x_{i} and y_{i} define the center of the i^{th} genie bomb blast zone (0 ≤ x_{i}, y_{i}, r_{i} ≤ 1), and ri defines its radius.
*******OutputConstraints*******
should contain one real number  coverage efficiency percentage (that is, percentage of the testing ground area covered with the bombardment in relation to the total testing ground area, where the testing ground is the square defined by inequalities 0 ≤ x ≤ 1, 0 ≤ y ≤ 1). Precision of the result is required to be 1% or better.
*******IOTestCases*******
input  output 

1
0.5 0.5 0.5
 78.539816

2
0.2 0.2 0.5
0.8 0.8 0.5
 80.74292

______________________________________________________
1334true
Taking the front staircase, which to my memory was used only once when the most august personage from Africa came to visit, I descended into the limitless vestibule decorated with a multicentury accumulation of layers of architectural excesses, and peered into the gatehouse window. Two Maxwell macrodemons were oscillating about in its phosphorescent gloom. They were playing at the most stochastic of all games — pitchandtoss. They occupied all their free time with this diversion. Looking more like poliomyelitis virus colonies under an electron microscope than anything else, they were huge, indescribably inept, lethargic, and dressed in worn liveries. As befit Maxwell demons, they opened and closed doors throughout all their life. They were experienced, welltrained exemplars, but one of them, the one in charge of the exit door, had reached retirement age, which was comparable to the age of the galaxy, and now and then reverted into second childhood, malfunctioning ignominiously. Thereupon, someone from Technical Maintenance would put on a driving suit, enter the gatehouse with its argon atmosphere, and bring the oldster back to reality.
Following instructions, I cast a spell on both of them, that is, I crossed the information channels and locked the inputoutput peripherals to myself. The demons did not react, being otherwise absorbed. One was winning, and, correspondingly, the other was losing, which greatly disturbed them, since it upset the statistical equilibrium.
The fact is that pennies matching is not stochastic enough. Sasha is lost in thoughts what game may be better. Maybe it is stochastic checkers? This is a very simple game. Demons in turns put checkers of two colors on the black cells of the chess field. Loses that player, after whose move one of the opponents gets the opportunity to fell the checker.
Checker A may be felled by checker B if checkers A and B are of different color and a cell, on which B comes after "jumping over" checker A, is free. You need to determine what move the given set of stochastic checkers was lost on.
*******InputConstraints*******
There is a description of 32 stochastic checkers’ moves in traditional chess notation in the input. Moves of white pieces are in lines with odd numbers, and moves of black pieces are in lines with even numbers.
*******OutputConstraints*******
Output the number of move on which a set was lost, or the word "Draw", if a set was not lost by either demon.
*******IOTestCases*******
input  output 

a1
a3
a5
a7
b2
b4
b6
b8
c1
c3
c5
c7
d2
d4
d6
d8
e1
e3
e5
e7
f2
f4
f6
f8
g1
g3
g5
g7
h2
h4
h6
h8  5 
______________________________________________________
1335true
"At this point, the baccalaureate of black magic, Magnus Feodorovich Redkin, brought in his keys, looking obese, customarily preoccupied, and hurt. He obtained his baccalaureate three hundred years ago for inventing the invisibility socks. Since then, he has been improving them over and over. The socks became culottes, and then pants, and now they are referred to as trousers. Still, he remained unable to make them work properly. At the last session of the seminar on black magic, when he made his serial presentation "On Certain Novel Aspects of the Redkin Invisibility Trousers," he was once more overtaken by disaster. During the demonstration of the updated model, something in its inner workings stuck, and the trousers, with a belllike click, became invisible themselves, instead of their wearer. It was most embarrassing. However, Magnus Feodorovich worked mostly on a dissertation whose subject sounded something like "The Materialization and Linear Naturalization of the White Thesis, as an Argument of the Sufficiently Stochastic Function E Representing the Not Quite Imaginable Human Happiness."
Here he had achieved significant and important results, from which it followed that humanity would be literally swimming in not quite imaginable happiness, if only the White Thesis itself could be found, and most importantly if we could understand what it is and where it could be found."
According to Redkin's last hypothesis, the White Thesis is a positive integer triplet (A, B, C) satisfying the following property: A^{2} + B^{2} is divisible by C. The hypothesis also states that all three White Thesis components lie between the squares of two consecutive integers N and N+1.
*******InputConstraints*******
contains one integer N (2 ≤ N ≤ 30000).
*******OutputConstraints*******
Output three different integers A, B and C, that (A^{2} + B^{2}) is a multiple of C and N^{2} ≤ A, B, C ≤ (N+1)^{2}.
If two or more such triplets exist, output any one. If there are no such triplets, then output "No solution".
*******IOTestCases*******
input  output 

2
 8 6 4

1000
 1000000 1000756 1000976

______________________________________________________
1336true
"Bbut, my dear ffellows," said Feodor Simeonovich, having diligently deciphered the handwriting. "This is BBen BBeczalel's problem! Didn't CCagliostro prove ththat it had no ssolution?"
"We know that it has no solution, too," said Junta, bristling immediately. "But we wish to learn how to solve it"
"Hhow strangely you rreason, CCristo… Hhow can you look for a solution, where it ddoes not exist? It's ssome sort of nnonsense.
"Excuse me, Feodor, but it's you who are reasoning strangely. It's nonsense to look for a solution if it already exists. We are talking about how to deal with a problem that has no solution. This is a question of profound principle, which, I can see, is not within your scope, since you are an applications type. Apparently I started this conversation with you for nothing."
Problems that do not have solution — that’s cool, of course. However, sometimes you want to solve something in solution of which nobody doubts. For example, to present an integer in the form of ratio of square and cube of some integers. But why does this problem always have a solution?… Ok, you will see :)
*******InputConstraints*******
The only line contains an integer n (1 ≤ n ≤ 10^{9}).
*******OutputConstraints*******
In the first line output an integer m. In the second — an integer k. m^{2} should be equal to k^{3}·n; 1 ≤ m, k ≤ 10^{100}.
*******IOTestCases*******
______________________________________________________
1337true
After the wonderful properties of the Field of Wonder in the Fools Country were discovered, the huge bureaucratic mechanism appeared. So, to plant his coin in the field, Pinocchio has to gather a lot of documents. Moreover it is impossible to get some documents without getting some set of another documents first.
The issue of one type of documents is a prerogative of exactly one bureaucrat. And all of these bureaucrats are so lazy, that they agree to work only one day a week. So there are incredibly long queues to the bureaucrat’s offices during the visiting days and it really takes a whole day to get only one document.
Pinocchio wants to realize a profit on his investments as soon as possible. The only way to do it is to gather all necessary documents as soon as possible. He found out what bureaucrats he needs to visit and numbered them from 1 to N inclusive. He found out the visiting day of week and the set of documents he should have on his hands during the visit for each of the bureaucrat.
After a short time of thinking, Pinocchio understood that he can’t find the optimal solution of his problem. And then he promised to pay a half of his future profits to one, who will help him.
*******InputConstraints*******
The first line of input contains amount of bureaucrats in the Fools Country N (1 ≤ N ≤ 100) and amount of days in a week according to calendar of Fools Country L (1 ≤ L ≤ 100). The next line contains the numbers of bureaucrat’s visiting days A_{i} (1 ≤ A_{i} ≤ L). The next N lines describe the sets of documents, necessary for receiving the corresponding document. Set of documents consists of numbers delimited by spaces. It is known, that i^{th} line doesn’t contain document with number i. Each line is ended by 0 which means the end of the set. If the set is empty (line contains single 0), the document can be gathered without any other documents. After these lines there is one more number — current day of week K (1 ≤ K ≤ L). The next line contains the list of documents Pinocchio already has. This list consists of numbers delimited by spaces and it ends with 0. And the last line of input contains the list of documents necessary for Pinocchio in the same format.
Though the Fools Country seems to have an ideal income source but because of the official circumlocution the state can’t get a huge part of the taxes. As a result there is enough money to keep only one office. So there may work not more than one official at the same time.
*******OutputConstraints*******
If it is impossible to get the necessary set of documents then output "No Solution". Otherwise it should output the minimal amount of days (excluding the current day) he will spend gathering the necessary set of documents, and in the next line it should output all gathered documents delimited by spaces in chronological order. If there are several such answers then the program may output any of them.
*******IOTestCases*******
input  output 

2 7
1 2
0
1 0
1
1 0
2 0
 1
2 
______________________________________________________
1338true
Everyone knows what traffic congestion is. Even supercomputer won’t be able to lay an optimal passage of the city center in the rushhours. But it is possible to simulate the traffic flows.
For that the following experiment is carried out. We choose several check points on the streets net of the city and one goal T from the checkpoints. We send a car from each checkpoint (except T) to the point T along the shortest way. In the point T we fix how many cars came from the North, how many from the South, from the East and from the West. So we can judge about the functioning capacity of the approaches to the point T.
You are to carry out such an experiment. No, you are not given a car! You are no to go anywhere. You are only to write a program simulating the experiment.
*******InputConstraints*******
Input contains the city plan description in the following format. The first line contains two integers W and H (1 ≤ W, H ≤ 500) – the width and the height of the plan. The next H lines consists of the streets net and checkpoints description. A symbol “.” means a place where a building is. A symbol “#” means a road fragment. A symbol “o” (small Latin letter) means a checkpoint. A road fragment always occupy a cell completely. Two road fragments belong to one road if and only if they have a common side.
Then there is a series of assignments of the experiment. First of all there is a number of assignments M (0 ≤ M ≤ 20). Each of the next M lines contains the number of the goal point T for the corresponding experiment. Assume that the checkpoints are numbered bottomup and from left to right.
If some car is to choose a way from several shortest ones the next scheme of priorities acts: South, North, West, East.
*******OutputConstraints*******
You are to output the results of each experiment in the following format:
Experiment #N: North: Rn, South: Rs, East: Re, West: Rw
where Rn, Rs, Re and Rw  an amount of cars that came in the experiment number N to the goal point from the North, South, East and West respectively.
*******IOTestCases*******
input  output 

10 5
..####....
..o..o....
..####.#o.
......##..
.o#####...
1
4
 Experiment #1: North: 0, South: 1, East: 0, West: 0

______________________________________________________
1339true
Presentday babies progress quickly. There are exactly k boys and k girls in the kindergarten. Some boys like some girls. But in this age the boys are still knights, so, if some boy like some girl then he likes the only girl and moreover one and the same girl can’t be liked by more than one boy. And the girls in this age are true ladies. So, if a girl likes a boy she likes the only one, and different girls like different boys.
The children are ingenuous. Their secret amorousness is wellknown to the nurse. Once the group decided to go for a walk and the nurse made up her mind to fall the children in pairs so that if there is a boy or a girl in love in a pair then the boy likes his pairmate or the girl likes the boy. Help the nurse to arrange the described pairs. You may assume that either the boys or the girls enumerated with positive integers from 1 to k.
*******InputConstraints*******
The first line contains the integer k — the number of boys (1 ≤ k ≤ 250 000). The second line consists of the numbers of girls that are liked by boys: if the i'th boy likes some girls, her number is at the i'th position; if the i'th boy likes nobody, there is 0 at the i'th position. The numbers are separated with a space. The third line consists of the analogous information about the girls.
*******OutputConstraints*******
You should output the sequence of k integers. The i'th element of the sequence is the number of a girl that is a pairmate of the i'th boy. The numbers are separated with a space.
*******IOTestCases*******
input  output 

3
3 0 0
0 2 0
 3 2 1

______________________________________________________
1340true
Once upon a time a cockroach Vasya running along the kitchen noticed a wonderful crumb. Vasya’s internal voice whispered him that he should reach the crumb using minimum of his vital energy. It meant that he should make the minimal number of his cockroach steps. And even Vasya’s little brain understood that he was to count the motion path neatly.
*******InputConstraints*******
The first line contains four numbers X, Y, A, R — the cockroach’s initial coordinates, the initial angle between the axis Ox and his motion path and the minimal turning radius of the cockroach (have you thought that cockroaches can turn around at one point?). The second line consists of two numbers KX and KY — the desired crumb coordinates.
Cockroaches count coordinates off the kitchen center and measure in cockroach steps. Inasmuch as a cockroach has six legs, this measure is rather relative, so you aren’t to think that a cockroach can run only integer number of steps. For example, 314.15 steps is the length of Vasya’s night walk.
The absolute values of all the coordinates X, Y, KX, KY and the radius R do not exceed 10000. The angle is counted off the axis Ox counterclockwise. It’s measured in degrees (cockroaches don’t know radians) and lies in the diapason from 0 to 360.
*******OutputConstraints*******
You are to find the length of the shortest Vasya’s motion path towards the crumb. The result is to be outputted within 4 digits after a decimal point.
*******IOTestCases*******
input  output 

1 2 90 10
21 2
 31.4159 
______________________________________________________
1341true
Major (M): You claimed that your device would be able to fly round the Earth several times and to miss not more than a couple of centimeters?
Designer (D); Yes! Our gravitational fields system of navigation absolutely...
M: Furthermore it can’t be fixed by detectors and doesn’t have a receiver or transmitter.
Engineer (E): It was your demand that nobody could detect the device...
M: We gave it a simple task to fly round the square. It didn’t return to the initial point.
D: Was that square large?
M: It’s none of your business! This is the State secret! You are to find the device!
Programmer (P): How did you programme the mission profile?
M: The device was to fly one conditional length unit to the North, the same distance to the East, the same distance to the South and then to the West. It passed more than 40 minutes since the device was to return. If they find it before us!.. In short, you are to find it!
D: It’s understood. Where was the initial point?
(The major flags and in two seconds the designer lies on the floor with his hands tied and two gunpoints look at his nape).
M: Why do you need this information?
E: You misunderstood! We don’t need information! But if we knew the initial point coordinates we could say where the device was...
(In two seconds two gunpoints look at the engineer’ nape, too).
M: Who interests this information? Where is the device? One, two, ...
P: You can’t understand! If the device reached the North Pole it can’t continue not to the North. Not to the East. Only to the South! Where the device is depends on where it started.
(Major aims at the programmer.)
M: No, it didn’t reach the Pole. It was taken into account.
P: Let me write a program that would count the final coordinates of the device. You’ll input the latitude, the longitude and the value of your conditional length unit yourself! The program would give you the answer keeping the absolute secrecy.
M: I’ll give you a chance. You three have got a computer and five hours... Less than five hours already. If we do not get the coordinates... You’ll suffer first.
*******InputConstraints*******
The first line contains the initial latitude W. –90 < W < 90. The second line – the initial longitude L, 180 < L ≤ 180. The third line contains the length of the square side, which the device was to fly round. The length is given in kilometers. The device keeps the fixed distance 6400 km from the Earth center of mass. The South Pole has latitude –90, the North Pole – latitude 90. The East direction is counted off the 0^{th} meridian in the positive direction.
*******OutputConstraints*******
You should output the final latitude and longitude of the device within three digits after a decimal point.
*******IOTestCases*******
input  output 

56.846841
53.36673
1124.427
 56.847
60.631

______________________________________________________
1342true
To bind a broom it’s a hard work. As there is a very big demand for this hightech product an brooms binding enterprise is to have a big amount of production workshops. You are to help such an enterprise to allocate the work among the workshops. Each workshop can bind from 0 to K brooms a day. Economists of the enterprise found out that each bound broom has a different prime cost: in most cases the more brooms were bound a day the less prime cost has the last broom bound that day. However, there may be more complicated situations. As a first approximation you may assume every dependence linear. So decided the economists when they determined a dependence of the next in turn broom’s prime cost on the industrial output of the workshop. You are to find out the optimal work load of the workshops.
*******InputConstraints*******
The first line contains two integers N and M (1 ≤ N, M ≤ 1000) — an amount of workshops and the required industrial output of brooms, respectively.
Then workshops description follows. The (i+1)st line describes the ith workshops with three numbers K_{i}, P_{i}, and Q_{i} (1 ≤ K_{i} ≤ 100;
0 ≤ P_{i}, Q_{i} ≤ 1000) — they are the maximal number of brooms that can be bound at the ith workshop a day, the prime cost of the first broom and the prime cost of K_{i}th broom at the ith workshop. As it was mentioned above the cost of jth broom’s production is the linear with respect to j function.
*******OutputConstraints*******
If the enterprise can’t produce the required number of brooms your program is to output the maximal number of brooms V that can be bound at the enterprise.
Besides, you are to output the total costs on production of M (or V if the enterprise can’t bind M) brooms with optimal allocation of industrial outputs within two digits after a decimal point.
The output format is to be as in sample outputs below.
*******IOTestCases*******
input  output 

2 10
6 20 15
100 100 100
 Minimum possible cost: 505.00

2 10
5 30 14
1 20 20
 Maximum possible amount: 6
Minimum possible cost: 130.00

______________________________________________________
1343true
12 months to sing and dance in a ring their celestial dance. One after another they hold a throne. The first is young and fierce January and the last is elderly and wise December. Leaving the throne, every month cry out a digit. During a year a 12digit number is formed. The Old Year uses this number as a shield on his way to the Abyss of Time. He defend himself with this shield from the dreadful creatures of Eternity. Because of hard blows the shield breaks to pieces corresponding to the divisors of the number.
Your task is to help the months to forge the shield for the Old Year such that it couldn’t be broken to pieces.
*******InputConstraints*******
The first line contains a number of months that already left the throne. The second line contains the digits already cried out.
*******OutputConstraints*******
Output an arbitrary 12digits integer that starts with the given digits and that has no nontrivial divisors. It’s guaranteed that the solution exists.
*******IOTestCases*******
input  output 

5
64631
 646310554187

______________________________________________________
1344true
As usual old man has planted a turnip. Every year he plants a turnip and every year happens one and the same thing — the turnip grows gigantic. May be the old man has good artificial fertilizers, may be his surname is Michurin, may be the atomic station that is not far from that place tells on the yield. And this year the turnip has grown very big and the old man is to take it out.
The old man tried to call in an old wife aid but she suffers from sciatica since the previous year when they tried to take off a turnip. Granddaughter after that event received medical treatment in Switzerland (that turnip turned very expensive), and a dog, a cat and a mouse have got idiosyncrasy to root crops upon the whole.
The old man has grieved. Que faire? (What is to be done? — Fr) The turnip is to be taken off!
Suddenly the old man recalls that he’s got a precious book at the garret — a course of physics by Pyoryshkin for the secondary school. He remembered that very interesting things are described in this book – pulleys. The construction of such pulleys may help the old man to get along without the old wife, granddaughter, the dog, the cat and the mouse.
The old man takes the book, reads it, — and assembles a construction. Now he is sitting at the porch of his house and thinks how much will this construction help him to save on the force?
Pulley is a wheel with a rope thrown over it and another rope that is bound to the axle. If the rope that is bound to the axle looks up and the ends of the other rope that is thrown over the wheel look down then it is a pulley of the first type. If the rope that is bound to the axle looks down and the ends of the thrown over rope look up then it is a pulley of the second type.
Help the old man, given a configuration of blocks of the first and the second types, to determine the win in the force while the crop hasn’t rotted. Assume that two pulleys coupled with a rope are on different heights.
*******InputConstraints*******
The first line contains integer N(1 ≤ N ≤ 32) — that is the number of pulleys. The pulleys are numbered with integers from 1 to N. The next N lines consist of the blocks description in the following format: T X1 X2 Y, where T — the pulley type (1 or 2), the ends of the rope thrown over the current pulley look towards the pulleys number X1 and X2, the rope that is bound to the axle looks towards the pulley number Y. However there are some exclusions.
 Some going up ropes are bound to the ceiling of the hothouse (the old man planted turnips in hothouses). In this case there is 0 instead of the number of pulley to which this ripe was to go.
 Exactly one rope that goes down from a pulley is bound to the turnip with mass 1 centner. In this case in the line with description of the ith pulley number 1 instead of the pulley number is written.
 Exactly one rope going down from a pulley is free. Then there is 2 instead of the number of pulley in the description of the ith pulley.
All the ropes are vertical.
*******OutputConstraints*******
You are to output the mass of a load in centners (within 4 digits after a decimal point) that is to be hung on the free rope in order to balance the system of pulleys. If there is no such a mass output “No solution”. If any mass suits output the string “Any”.
*******IOTestCases*******
input  output 

2
1 1 2 0
2 1 0 2
 2.0000

4
1 3 2 0
2 1 0 4
1 1 4 1
2 3 2 –2
 No solution

4
1 2 2 0
2 1 1 2
1 4 4 0
2 3 3 1
 Any

______________________________________________________
1345true
Once a veteran of the ACM contests, thinking about the younger generation, decided to help them to master with the cobwebs of the sports programming. He decided to make an Internet site that would contain articles on programming, different interesting problems, solutions and the sources of those solutions. But his marvelous sources look faded and poor, not as they look in his favorite development framework: the key words are not emphasized, comments don’t differ from the other text... Nothing appeals to the eye.
He knows the basis of the HTML and he understands that it is a very unpleasant work to add coloring his sources tags manually.
 To write a program that adds tags is a duck soup! – he thought. – Or not a duck soup… May be it’ easier to do it manually… Or, may be… Eureka! If I can’t solve this problem, I’ll give it at the next ACM contest – some will surely solve the problem!… And if they make mistakes… Let them try!…
*******InputConstraints*******
The correct source of a program in Pascal is given The length of the input text is not longer than 100 000 symbols.
*******OutputConstraints*******
You are to add formatting HTML tags so that the source text would look as it is required. The requirements are as follows:
 All the comments must be enclosed in the pair of tags “<span class=comment>” and “</span>”
 All the key words must be enclosed in the pair of tags “<span class=keyword>” and “</span>”
 All the strings must be enclosed in the pair of tags “<span class=string>” and “</span>”
 All the numbers must be enclosed in the pair of tags “<span class=number>” and “</span>”
 If key words, strings or numbers come upon the comments then they are assumed as a part of the comment and not as key words, strings or numbers.
 If key words, comments or numbers come upon the strings then they are assumed as a part of the string and not as key words, comments or numbers.
A string is the sequence of symbols enclosed in a pair of quotation marks “ ’ ” that does not contain other quotation marks. Or a symbol “#” which is followed by nonempty sequence of digits. In the second case it’s necessary to take the maximal sequence. E. g. in the sequence “#123” a subsequence “#1” is not a string and the entire sequence “#123” is a string.
A number begins with a digit and contains only digits and possibly one point “.”, followed by one or more digits. As in the case of a string a number is the maximal by inclusion sequence of symbols that satisfies the given above requirement.
An identifier may start with a letter or underscore (“_”) and contains letters, digits and underscores. As in the cases of strings and numbers, identifier is a maximal by inclusion sequence satisfying the given requirements.
There are comments of two types: comment of 1st type begins with ‘{’ and ends with ‘}’, both braces are the part of the comment; comment of 2nd type begins with ‘//’ and ends with line feed, slashes are the part of the comment while line feed is not. Nested comments are the part of the most outer comment.
Key words are the following identifiers:
'and', 'array', 'begin', 'case', 'class', 'const', 'div', 'do', 'else', 'end', 'for', 'function', 'if', 'implementation', 'interface', 'mod', 'not', 'of', 'or', 'procedure', 'program', 'record', 'repeat', 'shl', 'shr', 'string', 'then', 'to', 'type', 'unit', 'until', 'uses', 'var', 'with', 'while'.
Here every key word is enclosed in the pair quotation marks. The key words are given in the lower case but occur in any case in the text. E. g., ImPlEmentAtioN is a key word.
*******IOTestCases*******
input  output 

Begin
writeln('Hello world!');
end.
 <span class=keyword>Begin</span>
writeln(<span class=string>'Hello world!'</span>);
<span class=keyword>end</span>.

Hint
Many of you have guessed that if you save the result in a file output.html and to add in the beginning of the file the following lines:
<STYLE>
span.string {color: fuchsia;}
span.number {color: darkblue;}
span.keyword {fontweight: bold; color: black;}
span.comment {fontstyle: italic; color: gray;}
</STYLE>
<PRE>
in the end, then having opened this file in a browser you’ll see the input text with the colored syntax.
______________________________________________________
1346true
It’s well known that a domain of any continuous function may be divided into intervals where the function would increase monotonically or decrease monotonically. A number of intervals of such a partition we will call a complexity of the partition. A complexity of a continuous function is the minimal possible complexity of partition in the domain into the monotonicity intervals.
The notion of complexity may be defined not only for continuous functions. In particular, it is applicable to the functions specified on a grid.
*******InputConstraints*******
The input contains a description of a function F, specified on a grid. The first line contains two numbers A and B — the first and the last point of the integer grid with step 1 (0 ≤ A < B ≤ 100 000). The second line contains the values table of the function F. The table consists of the integers F(A), F(A+1), …, F(B) separated with a space and/or linefeeds. All the values of the function F are in diapason from –100 000 to 100 000.
*******OutputConstraints*******
Output the only number — the complexity of the function F.
*******IOTestCases*******
input  output 

1 10
1 2 3 4 2 1 1 3 6 7
 3

______________________________________________________
1347true
The last time many users keep internet diaries — blogs. The users keep their diaries and occasionally read other’s. Those users like to count their virtual friends. A friend for them is anyone who reads their twaddle. Assume that a user reads another’s blog if he mentions the one in his diary.
You are to output for each user a list of his friends, the people who regard him as a friend and a list of mutual friends, i.e. those who are friends of the assumed user and regard him as a friend.
You are given the blogs of those users. For each user you are to output the mentioned above three lists. The users mark their friends with a tag <friend>. A tag is the line that consist of small Latin letters between the marks lower than (<) and greater than (>). A closing tag is the string of small Latin between the symbols lower than and slash (</) in the beginning and greater than (>) in the end.
*******InputConstraints*******
The first line contains a integer N (1 ≤ N ≤ 100) — a number of blogs in the input. The first line of each blog consists a name of the blogger. All the bloggers’ names are different. The next line starts with a tag <blog>. The last blog line ends with a closing tag </blog>. There is no other tags in the text of blog. Each opening and closing tag has it’s pair tag in the text. Symbols <, > and / occur only in tags. The input contains only small and capital Latin letters, digits, symbols greater than, lower than, slash, full stops, commas and underlining symbols. The friends’ names are case sensitive. A tag can’t be torn by a line feed. A friend’s name may consist of small and capital Latin letters and an underlining symbol. A friend’s name can’t be empty. Blogs line doesn’t exceed 255 symbols. A blog contains not more than 1000 lines. An amount of friends mentioned in a blog doesn’t exceed 100.
*******OutputConstraints*******
For each blogger from the input you are to output a list of those who’s blogs he mentioned (friends), a list of those who mentioned him in his blog (is a friend of) and a list of those who is present in both previous lists. Each list is to be outputted in a separate line and sorted in the alphabetic order. Names in a list are to be separated with a comma and space. Before the “friends” list you are to output s string “1: ”. Before an “is a friend of” list you are to output a string “2: ”. Before a list of “mutual friends” you are to output a string “3: ”. Before those three lists you are to output a name of the blogger and an empty line beforehand (if it is not the first input blogger). A blogger is not a friend of himself even if he mentioned himself in his blog.
*******IOTestCases*******
input  output 

3
xoposhiy
<blog>
Tomorrow I found <friend>_denplusplus_</friend> to
be <b>smartest</b> blogger in the net.
Also I received interesting link from
<friend>strange_human</friend>
</blog>
_denplusplus_
<blog>
Some shit about my work.
</blog>
strange_human
<blog>
<friend>xoposhiy</friend>
<friend>_denplusplus_</friend>
</blog>
 xoposhiy
1: _denplusplus_, strange_human
2: strange_human
3: strange_human
_denplusplus_
1:
2: strange_human, xoposhiy
3:
strange_human
1: _denplusplus_, xoposhiy
2: xoposhiy
3: xoposhiy

______________________________________________________
1348true
A goat is tied to a peg (in a point C) in a garden with a strong rope of the length L (i.e. a goat may eat a grass that is not farther than L meters from the peg). There is a bed of pineapples that he loves very much. The bed is a line segment with the ends A and B.
Humph… We wonder, how much the goat is to stretch the roap in order to reach at least one pine apple? And all the pineapples?
*******InputConstraints*******
There are points’ A, B and C coordinates and a length of the rope L in the input. All the numbers are integer, L ≥ 0, all the coordinates don’t exceed 10000 by the absolute value. The numbers are separated with spaces or line feeds.
*******OutputConstraints*******
The first line should contain the minimal length that the goat is to elongate the rope in order to reach the pineapples bed. The second line should contain the minimal length that the goat is to elongate the rope in order to eat all the pineapples from the bed. All the numbers are to be outputted within two digits after a decimal point.
*******IOTestCases*******
input  output 

8 6 8 6
0 0 7
 1.00
3.00

______________________________________________________
1349true
Here is a farm. Here is a farmer that counts how many animal live in his farm: a camels, b sheep, c green cockroaches. Occurs that a^{n} + b^{n} = c^{n}. n is given. You are to find all the rest.
*******InputConstraints*******
*******OutputConstraints*******
Three different integers (a, b and c) such that a^{n} + b^{n} = c^{n}, 1 ≤ a, b, c ≤ 100. If there are several solutions you should output the one where a is minimal. If there are several solutions with the minimal a you should output the one with minimal b, and so on. Output −1 if there is no solution.
*******IOTestCases*******
______________________________________________________
1350true
It’s dangerous to eat in a canteen — you may be poisoned by a not fresh food. One may fall into a coma because of the canteen’s chicken and the other feels OK. And vice versa. The food is cooked from M different food stuffs. There are N different food stuffs in the menu but not all of them are at the distribution. Assume that K + 1 students eat the food and we know for each student what products may poison him. The first student eats and he is not poisoned. How the dinner affect on the other students?
*******InputConstraints*******
The first line contains an integer N (1 ≤ N ≤ 100). The next N lines contain the food stuffs names — nonempty sequences of Latin letters and digits with length not more than 40 symbols. Then there is a number K (1 ≤ K ≤ 100) and K + 1 blocks describing the menu food stuffs dangerous for the canteen visitors afterwards. The i^{th} block starts with a line with an integer N_{i} — an amount of dangerous food stuffs and then there are N_{i} lines with the names of those dangerous stuffs (0 ≤ N_{i} ≤ N). The first block describes the food stuffs dangerous for the first student, the next K blocks — for the rest ones. The input ends with the line containing an integer M (0 ≤ M ≤ N).
*******OutputConstraints*******
K lines — the
i^{th} line should contain:
 YES, if the dinner is harmless for the (i + 1)^{st} student,
 NO, if among the food stuffs there is a dangerous one for the (i + 1)^{st} student,
 MAYBE, if there may be different situations under the given conditions.
*******IOTestCases*******
input  output 

7
Rafinad
Kefir
Pastila
Smetana
Chokolade
Kljukva
Imbir
3
3
Rafinad
Kefir
Imbir
1
Rafinad
3
Kefir
Kljukva
Smetana
2
Imbir
Smetana
3
 YES
NO
MAYBE

______________________________________________________
1351true
A dwarf bibr — a rare animal from the planet Globland. Aborigines of Globland, loathsome gnusmases, like the bibrs’ meat. Thet believe that a has eaten the bibr gnusmas becomes a globalizer (i.e. a semigod, semignusmas that is not afraid of neither acid rains nor radioactive winds of Globland.) Bibrs are very peaceful animals but defending themselves from gnusmases they use all their arsenal of weapons: pistols, submachine guns, projectors and some kinds of the weapons of close fight: fungos, knuckledusters and so on.
One nice morning bibr Bob woke up from the howl of antignusmas siren. There were thousands of points on the radar. It meant that loathsome gnusmases scrambled out from their burrows and slowly approached Bob’s little house. But Bob was a flash guy and just a week before he had set a new Kakashnikov machine gun on his house’s roof. One burst of fire annihilates all the gnusmases that were in the arc of fire and those who survived ran away. He decided to state the value of effectiveness of his bargain and to find out how many gnusmases he would annihilate and how many of them would hide back in their burrows.
*******InputConstraints*******
The first line contains the machine gun characteristics: D — the range (1 ≤ D ≤ 30000), X_{1}, Y_{1}, X_{2}, Y_{2} (1 ≤ X_{1} , Y_{1}, X_{2}, Y_{2} ≤ 30000) — coordinates of the right and the left bounds of the arc of fire. The second line contains an integer N (1 ≤ N ≤ 30000) — an amount of gnusmases that attack Bob’s house. The next N lines consist of the gnusmases coordinates X_{i}, Y_{i} (0 ≤ X_{i}, Y_{i} ≤ 30000; X_{i} and Y_{i} are not equal to zero at the same time). All the numbers are integer. Bob’s house coordinates are (0,0). The arc of fire is less than 180 degrees.
*******OutputConstraints*******
N lines with the answers “YES” and “NO”. “YES” — if the gnusmas will be annihilated (i.e. he is inside the arc of fire at the distance from Bob’s house not greater than the range of the machine gun). “NO” — otherwise.
*******IOTestCases*******
input  output 

5 1 0 0 1
6
1 1
5 6
3 0
1 2
0 5
3 0
 YES
NO
YES
NO
YES
NO

______________________________________________________
1352true
Definition. If the number 2^{N}−1 is prime then it is called a Mersenne prime number.
For example, 2^{2}−1 — the first Mersenne prime, 2^{3}−1 — the second Mersenne prime, 2^{11213}−1 — the 23^{rd}, 2^{216091}−1 — the 31^{st}.
It’s a hard problem to find those numbers without a computer. So, Euler in 1772 found the 8^{th} Mersenne prime — 2^{31}−1 and then for 100 years no Mersenne prime was found! Just in 1876 Lucas showed that 2^{127}−1 is a prime number. But he didn’t find the 9^{th} Mersenne prime, it was the 12^{th} one (the numbers 2^{61}−1, 2^{89}−1 and 2^{107}−1 are prime but it was found out later). A new breakthrough happened only in 1950’s when with the help of the computing machinery Mersenne primes with the powers 521, 607, 1279, 2203 and 2281 were found. All the following Mersenne primes were found with the help of computers. One needn’t be a great mathematician to do that. In 1978 and 1979 students Noll and Nickel found the 25^{th} and 26^{th} numbers (21701 and 23209) on the mainframe of their University and they became famous all over the USA. But the modern supercomputers have the limits of their capability. Today the dozens of thousands people all over the world united in one metaproject GIMPS (Great Internet Mersenne Prime Search, www.mersenne.org) look for Mersenne primes. GIMPS found 8 the greatest Mersenne primes. Their powers are 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951. 2^{6972593}−1 is the 38^{th} Mersenne prime, and for the last 4 numbers one can’t tell what are their sequence numbers because not all the lower numbers are checked. Those four numbers are also the greatest known prime numbers.
The latest number 2^{25964951}−1 was found on February 18, 2005, it contains 7816230 decimal digits. The one who will find a prime number with more than 10 millions digits will get a prize of $100000. You may gain the prize if you join the project.
You are not now to find the 43^{th} Mersenne prime — the jury won’t be able to check your answer. N doesn’t exceed 38 in this problem. So, given an integer N you are to find N^{th} Mersenne prime.
(Information is actual for March, 2005)
*******InputConstraints*******
The first line contains integer T — an amount of tests. Each of the next T lines contains an integer N.
*******OutputConstraints*******
For each N you should output the power of the N^{th} by order Mersenne prime.
*******IOTestCases*******
input  output 

13
18
32
24
21
19
34
27
33
20
30
28
29
22
 3217
756839
19937
9689
4253
1257787
44497
859433
4423
132049
86243
110503
9941

______________________________________________________
1353true
Vasya is the beginning mathematician. He decided to make an important contribution to the science and to become famous all over the world. But how can he do that if the most interesting facts such as Pythagor’s theorem are already proved? Correct! He is to think out something his own, original. So he thought out the Theory of Vasya’s Functions. Vasya’s Functions (VF) are rather simple: the value of the N^{th} VF in the point S is an amount of integers from 1 to N that have the sum of digits S. You seem to be great programmers, so Vasya gave you a task to find the milliard VF value (i.e. the VF with N = 10^{9}) because Vasya himself won’t cope with the task. Can you solve the problem?
*******InputConstraints*******
*******OutputConstraints*******
The milliard VF value in the point S.
*******IOTestCases*******
______________________________________________________
1354true
A word is the nonempty sequence of symbols a_{1}a_{2}…a_{n}. A palindrome is the word a_{1}a_{2}…a_{n} that is read from the left to the right and from the right to the left the same way (a_{1}a_{2}…a_{n} = a_{n}a_{n−1}…a_{1}). If
S_{1} = a_{1}a_{2}…a_{n} and
S_{2} = b_{1}b_{2}…b_{m}, then S_{1}S_{2} =
a_{1}a_{2}…a_{n}b_{1}b_{2}…b_{m}. The input contains some word S_{1}. You are to find a nonempty word S_{2} of the minimal length that S_{1}S_{2} is a palindrome.
*******InputConstraints*******
The first input line contains S_{1} (it may consist only of the Latin letters). It’s guaranteed that the length of S_{1} doesn’t exceed 10000 symbols.
*******OutputConstraints*******
*******IOTestCases*******
input  output 

No
 NoN

OnLine
 OnLineniLnO

AbabaAab
 AbabaAababA

______________________________________________________
1355true
A student dreamt that he walked along the town where there were lots of pubs. He drank a mug of ale in each pub. All the pubs were numbered with positive integers and one could pass from the pub number n to the pub with a number that divides n. The dream started in the pub number a. The student knew that he needed to get to the pub number b. It’s understood that he wanted to drink on the way as much ale as possible. If he couldn’t get from the pub number a to the pub number b he woke up immediately in a cold sweat.
*******InputConstraints*******
The first line contains an integer T — an amount of tests. Then T lines with integers a and b follow (0 ≤ T ≤ 20; 1 ≤ a, b ≤ 10^{9}).
*******OutputConstraints*******
For each test in a separate line you are to output the maximal number of mugs that the student could drink on his way.
*******IOTestCases*******
input  output 

5
30 89
2 16
3 243
1 1
2 2
 0
4
5
1
1

______________________________________________________
1356true
“How do physicists define prime numbers? Very easily: prime numbers are the number 2 and all the odd numbers greater than 2. They may show that this definition corresponds to the mathematical one: 3 is prime, 5 is prime, 7 is prime… 9? 9 is certainly not prime. Then: 11 is prime, 13 is prime. So 9 is the experiment mistake.”
From mathematical analysis course
Once physicist and mathematician argued how many prime numbers one needed for the purpose that their sum was equal to N. One said that it wasn’t known and the other that 3 was always enough. The question is how many.
*******InputConstraints*******
The first line contains T, an amount of tests. Then T lines with integer N follow (0 ≤ T ≤ 20; 2 ≤ N ≤ 10^{9}).
*******OutputConstraints*******
For each test in a separate line you should output prime numbers so that their sum equals to N. An amount of such prime numbers is to be minimal possible.
*******IOTestCases*******
input  output 

7
2
27
85
192
14983
3
7
 2
23 2 2
2 83
11 181
14983
3
7

______________________________________________________
1357true
Several students wake up in the morning and want to drink a cup of hot coffee. But they have only one teakettle. In this case, they usually operate according the following instruction:
Students should wake up one after another and act as follows:
 If nobody boils the water, student should fill the teaketle with 200 ml of water and put it on the burner. Water has initial temperature 20 °C.
 If another student boils water already, he should add 200 ml of water in the teakettle. As a result, water temperature equalize according to law T = (m_{1}T_{1} + m_{2}T_{2}) / (m_{1} + m_{2}), where m_{1}, m_{2} – mass of water in teakettle and mass of additional portion of water, and T_{1}, T_{2} – their temperatures.
 If another students boil water and the teakettle is full already then other students should wait until the teakettle becomes free. The teakettle capacity is 1 liter (1 kg) of water i.e. 5 students are able to boil water simultaneously.
 As soon as water begins to boil, i.e. the water temperature runs up to 100 °C, the teakettle should be put off the burner and water should be poured into the cups. At the same moment teakettle can be used for boiling next portion of water. Water heats up by ΔT = (P Δt) / (C m) degrees during Δt seconds, where P – is a power of burner, C = 4190 J/kg·K – specific heat of water, m – water mass.
You are giver wake up time for each student and you are to simulate this process to find for each student the time when he will be able to drink a cup of coffee. Assume, that students can perform described manipulations in a moment. Power of burner P = 400 Watt.
*******InputConstraints*******
The first line of input contains single integer N – amount of students (0 ≤ N ≤ 500). Each of the following N lines contains a wake up time of corresponding student in format HH:MM:SS. Times are sorted in ascending order. All students wake up at the different moments but during the same day, i.e. all times different and between 00:00:00 and 23:59:59.
*******OutputConstraints*******
For each student you should output the time when he will be able to drink his coffee in the same format HH:MM:SS.
*******IOTestCases*******
input  output 

4
07:00:00
07:02:00
07:05:30
12:00:00
 07:08:23
07:08:23
07:08:23
12:02:48

______________________________________________________
1358true
There are N computers in a computer club. It’s known which computers are to be connected with a cable in order to make the net work properly. It’s left to arrange the computers so that no two cables intersect and distance between every two computer would be greater than one. Regard the computers as points and the cables as line segments. The net is connected, i.e. every two computers are connected with some sequence of cables.
*******InputConstraints*******
First line contains integer N (1 ≤ N ≤ 1000). Then N−1 lines follow. In each line there are two integers a_{i} and b_{i}, the numbers of computers that are to be connected with a cable (1 ≤ a_{i}, b_{i} ≤ N).
*******OutputConstraints*******
You should output N lines. In the i^{th} line there should be two real numbers — coordinates of the i^{th} computer. The absolute values of the coordinates shouldn’t exceed 1000.
*******IOTestCases*******
input  output 

3
1 2
2 3
 0 0
10 0
0 10

______________________________________________________
1359true
A lifting crane broke down. The constructors are to lift down a barrel with and old cement. The barrel is to end up n meters to the left and m meters down from the place where it was. To get a barrel down one can build a ramp of some amount of wooden planks so, that
 both ends of each plank would have integer coordinates;
 one end is always lower than the other one;
 the lowest end of each plank is not to the right from the upper one.
You may assume that barrel doesn’t jump during rolling down, i.e. direction of it’s velocity changes in a moment and value of velocity keeps unchanged at the turns of a planks. Acceleration of gravity assumed to be equal to 10. You should neglect rotation of the barrel and friction between barrel and ramp. You are to find a minimal time to get a barrel down.
*******InputConstraints*******
Input contains two integers n and m (1 ≤ n, m ≤ 50).
*******OutputConstraints*******
Output should contain minimal time in seconds which a barrel would need to roll down on the described construction of wooden planks accurate within 10^{3}.
*******IOTestCases*******
______________________________________________________
1360true
One day, mathematician and philosopher were engaged in a heated dispute.
Philosopher said:
— Ideal line has only length and no width, therefore, no line can have an area.
Mathematician replied:
— That's as it may be, but still you can fill a square with a line in such a way that there will be no gaps.
And you can't deny that a square has an area, and he grinned.
But Philosopher still wasn't convinced:
— Show me this line, then.
— With pleasure… — responded Mathematician and scribbled some equations on a piece of paper:
— With t increasing, the point (x, y) will move around the square, forming a line.
— So what? — asked Philosopher. How is it going to fill the entire square?
— Indeed, it will, — said Mathematician, — Whichever point inside the square you draw, the line will
eventually cross that point.
— No, — replied Philosopher indignantly, — Anyway, I don't believe. When will the line cross this point? — and he put a thick dot inside the square.
Give Philosopher an answer.
*******InputConstraints*******
The first line of input contains the coordinates (x_{0}, y_{0}) of the dot center (−1 ≤ x_{0}, y_{0} ≤ 1). The second
line contains ε ≥ 0.0001 — the radius of the dot (the dot is essentially a small circle).
*******OutputConstraints*******
Any value of t in the segment [0, 10^{12}], which corresponds to the line crossing the dot, or "FAIL", if the line doesn't cross the dot.
*******IOTestCases*******
input  output 

0.744 0.554
0.01
 5.3

______________________________________________________
1361true
Every year in the city of RadonSnark a famous symposium of scientistsspaceologists is held.
Professor A, haunter of the symposium, has decided this time to invite professor B, who does research in
the adjacent field of science — applied chronistics.
Unfortunately, professor A has forgotten to meet professor B at the railway station (he was thinking about
the exciting future of spaceology and remembered that his friend was coming only when B had already
arrived at the city). "There's nothing left to do — I have to go", — decided A. He got into his spacemobile
and left to the railway station.
Now the worldfamous scientist B can't wait even a second (chronistics think that only real action is
true, not the some vague argumentation). He has got into his chronomobile immediately, and has left the
railway station (A and B have started at the same time). What's left to do is to find out when A would
meet B. Note that the spacemobile and chronomobile would not stop before they meet.
Remember that the symposium is just about to start and the strange things that are always associated
with the symposium already began to happen. While notable scientists discuss their problems, all the
machinery in the city behaves very strange. For example, all the spacemobiles turn to the leftmost road
on each junction, and the chronomobiles  to the rightmost one. Some of the roads also began to function
strangely. If you take one of these roads to leave a junction, you will arrive in the same junction. Also,
it is clear that leaving the vehicle on the road between two junctions is against the law, so A and B can
only meet each other on a junction.
*******InputConstraints*******
The first line contains one number N (N ≤ 100000) — the amount of junctions in the city of RadonSnark.
The following N lines describe the junctions. The (i+1)st line contains a list of junctions
that can be reached from the ith junction directly. The roads are listed in order from the leftmost to the
rightmost. Oh ya! All junctions today are quite stange: all roads enter to the junction only from one side.
That's why words "leftmost" and "rightmost" have sense) The list is terminated with 0. Each list contains
at least one nonzero number.
The last input line contains two numbers. The first one specifies the junction where A starts the trip in
his spacemobile. The second number is the junction where B starts from.
*******OutputConstraints*******
Output the number of minutes that B will need to meet A. It takes exactly one minute to
travel from one junction to another directly reachable junction. Output −1 if they won't meet.
*******IOTestCases*******
input  output 

7
2 4 0
3 1 0
4 2 0
5 1 6 3 0
6 4 0
2 5 4 0
6 0
1 7  7 
______________________________________________________
1362true
May be you can remember the "Classmates" problem from the 2004 Urals Programming Contest. The statement of that problem is like follows:
Tanya is a schoolgirl. One day, headmistress asked her to notify the class about next day's
lessons being cancelled due to power outage. Tanya successfully carried out that job. She decided
to call Lena, then Katya, the Masha. While she was calling Katya, Lena, who did already know
the news, called Misha, etc. The whole class knew of the welcome news in almost no time.
The contestants were to determine the minimum time required to pass the news to every
student in the class.
Time passed, and Tanya got a summer internship in the "Advertising, Commercials and Media" agency.
Like any other firm that offers high salaries for students, ACM has a clearly defined hierarchical structure.
The president is the root of the hierarchy. He has some direct subordinates, who themselves can have
direct subordinates, etc. One day, Tanya happened to invent the utterly ingenious method for increasing
the advertisement efectivenes by 110%. She called her boss immediately, then her friend Lena (who was
Tanya's direct subordinate), then Masha and Katya. They, in turn, quickly passed the message to their own
colleagues, and so on. So, you are again to determine the minimum time for the information about Tanya's
method to spread among the entire ACM agency. There is a peculiar feature of the company's phone
network you should take into account. Namely, every employee can only call his/her direct subordinates
or immediate boss (this is supposed to prevent girls from chatting over the phone instead of doing their
work). Each phone call takes exactly one minute.
*******InputConstraints*******
The first line of input contains the number N of ACM employees (N ≤ 100000). Each employee is assigned
the unique ID number (these numbers range from 1 to N).
N lines follow, Kth line containing zeroterminated spacedelimited list of Kth employee's direct subordinates. The last line contains Tanya's ID number. The hierarchical structure is a tree. I.e., each employee has exactly one direct boss, of course, with exception for the topmost boss.
*******OutputConstraints*******
Output consists of one number — the minimum time, in minutes, that is required to propagate Tanya's
idea to all ACM employees.
*******IOTestCases*******
input  output 

10
2 3 0
4 5 7 0
6 9 0
0
0
8 10 0
0
0
0
0
2
 5

______________________________________________________
1363true
Ivan Pyatochnikov loves to tinker with electronics. That's why he has a great authority with his friends.
Indeed, he can repair whatever piece of hardware you give him. He will deal with any incorrectly configured
program. And he will even fix bugs in your code.
Today is Ivan's birthday, and his buddies are preparing a really cool present for him — namely, a genuine
shamanic tambourine. Yes, a tambourine. After all, no real geek can live without such an indispensable
thing.
Having bought the tambourine and read the manual, Ivan's friends have discovered that a tambourine only
becomes effective when there is a picture of owner printed on it, along with some special magical signs.
Now the friends are rather depressed, because they only have a dot matrix printer and a file containing
the grayscale photo of Ivan. Clearly, any image to be printed on a dot matrix printer shall be monochrome
(i.e. shall contain black and white pixels only). Ivan's photo consists of different shades of gray, and friends
are afraid that the printout won't resemble the original photo closely enough for the tambourine to work.
You have agreed to help Ivan's buddies prepare the present.
*******InputConstraints*******
The first line contains two integers N and M (75 ≤ N,M ≤ 600) — the dimensions of the image.
N following lines, each line containing M integers ranging from 0 to 255, define the image itself.
*******OutputConstraints*******
The output shall contain the monochrome image in the form of N lines with M numbers on each line.
Each number must be either 0 or 255. For the resulting monochrome image to resemble the original, the
following condition must be satisfied for each i and j:
where A[i, j] is the brightness of the original image pixel (i, j) and B[i, j] is the corresponding monochrome
image pixel brightness.
*******IOTestCases*******
input  output 

3 3
255 255 0
0 0 255
254 0 253  255 255 0
0 0 255
255 0 255 
Hint
Note that this example is incorrect, because N and M are out of the defined range. Nevertheless, the
example shows the correct format of input and output.
______________________________________________________
1364true
A cemetery has a rectangular shape with N rows of graves and M graves in each row. The cemetry, as
usual, is encircled with a high and deep fence. As you know, Lara Croft has penetrated into the cemetry through the sap in the NorthWestern corner in order to find the treasures hidden in the graves. To do that, she has dug an underground passage according to the following rule: if there was an intact grave straight ahead, then Lara lengthened the passage during one night and ravaged the grave. If there was a cemetry fence or a ravaged grave in the way, then Lara turned 90 degrees right and continued with her
questionable affairs. You must have already heard that she found one of the treasures. And she is going to find another one soon. However, Lara doesn't know that Dark Forces have decided to ensnare her. As soon as Lara finds the second treasure (and goes immediately to buy the usual bottle of champagne), a new alarm system (of "LaraKiller" brand) will be set off.
First of all, the allseeingeye tower will go online. The eye will locate Lara after some time. At once
the skeleton reanimation process will be initiated in some of the ravaged graves. It takes T seconds for
skeletons to revive, and Lara will certainly try to escape before these T seconds run out.
As a head programmer of the "LaraKiller" company, you are to calculate where Lara can be located at the
moment of complete skeletons' revival. You should not revive unnecessary skeletons. Otherwise you'll
have to kill them yourself.
It's clear that Lara will run along her underground passage not faster than 1 grave per second.
*******InputConstraints*******
The first input line contains two numbers: N and M, 2 ≤ N,M ≤ 100 — the dimensions of the cemetry. The second line consists of the treasure grave coordinates. The third line contains Lara's coordinates at the moment the allseeingeye located her. The fourth line contains the number of seconds T.
Assume that the NorthWestern grave has coordinates (1, 1) and the SouthEastern — (N, M). Lara starts to dig her passage from the grave (1, 1) moving to the East, i.e. to the grave (1, 2). You may assume that T is less than 24 hours.
*******OutputConstraints*******
Output coordinates of the graves where Lara can be located T seconds after the allseeingeye detected
her. The coordinate pair of each grave is to be output on a separate line. The numbers shall be separated
with spaces. The graves shall be sorted by the distance that Lara will have to run from this grave to the
cemetry entrance.
*******IOTestCases*******
input  output 

5 4
4 3
2 2
5
 5 2
5 1
4 1
3 1
2 1
2 2
2 3
3 3
4 3

______________________________________________________
1365true
Thursday. April 21. First round of IX Urals Programming Contest Championship has just finished. All
teams left the contest area and went to celebrate results of the first round, make sightseeing tour around
Ekaterinburg, or just have a little rest after competition.
Jury would like to have a rest too, but it is impossible. It turned out, that one task for the second round
is missing. Moreover, the error in contest management system was discovered. No, it is not a critical bug,
which distorts results, but a very annoying mistake: one module of the contest management system makes
processing of each submission longer by at least 30 seconds.
Some investigations were done. It was found, that nobody knows what this module is intended for. With
this module contest management system works very slowly. But without the module it does not work at
all.
It seems, that there is no problem. One may take module sources, read them, find specifications for the
module, resolve the error, compile the module and put the corrected version into the system. Unfortunately,
the module was written 8 years ago when The First Urals Programming Contest was prepared and now
sources are not available. They are just lost. Jury feels lost too.
Eureka! We can give out the module to participants of the contest! They are clever enough to run it,
discover the logic and write another version of the module, which will run without delay. Moreover, it is
an excellent task for the second round!
*******InputConstraints*******
Jury was able to discover some information about the module. It is known that the module reads input
data from the input stream. Each line of the input contains single arithmetic expression, which is
evaluated by module. Each expression consists of arithmetic operations of addition (+), multiplication
(*), integer division (/) and concatenation.
Arithmetic operations are written in prefix form with unlimited number of operands. This way expression
"+3;6;10" has a result of "19". Operation of concatenation does not have any notation and gets executed
when no other operation is given. This way expression "3;6;9" is evaluated to "369". It is known also
that expressions may contain brackets. For example, expression "(+3;6)(*2;3)" has a result of "96". It
may be assumed that logic of expression evaluation does not depend on context. It means, that each
subexpression is always evaluated in the same way with no dependency on it's entrance into the whole
expression.
Nothing more is known about the module. You see, that there is no information on how arithmetic
operations interact with concatenation, brackets and separator character (;). You have to discover it by
yourself. To do it, you will be given an existing module. You have to run it, investigate the logic and
reproduce it in your solution.
Input data will be located in the input stream. Each line should be interpreted as a separate expression.
Expression will consist of the following characters only: "0123456789+*/();".
You may assume, that all intermediate values and result of expression evaluation are in the range from 0
to 10^{9}. You may also assume that there will be no expressions longer than 50 characters.
*******OutputConstraints*******
Your solution must reproduce the logic of the given module. It should produce output stream with the result of evaluation of expresions from the input. Each line of output must be of
the following form: "Expression evaluates to: ", where is the line
number and is the result of evaluation of expression in the line of the input stream.
*******IOTestCases*******
input  output 

(+3;6)(*2;3)
(+3;6)(/3;2)  Expression 1 evaluates to: 96
Expression 2 evaluates to: 91 
Hint
______________________________________________________
1366true
A nice entertainment was invented in the kindergarten. Each child has to bring a present from his home — a big box with something interesting inside. Contents of the boxes shall be kept secret up to the last
moment. After that the chidren will exchange their presents.
Children understood that they would have to part with their presents so they stuffed their boxes with
useless junk: candy wrappers, husk, broken computer mice and even unnecessary elder brother's fat book
with some kind of donkey on the cover.
So, a child didn't mind parting with his box. Moreover, he didn't calm down until he made sure he got
rid of his box. Having foisted his box off, no child ever took it back. If some kid didn't get a present in
exchange for his own one, he would become very disappointed and his loud cries would attract attention
of a nurse who had to take away all those boxes along with the marvellous content!
As a chief information officer of entertainment operations, you are to find out the amount of the present
exchange schemes such that each child would be pleased. But there is one hitch… Your handbook on
algorithms was taken by your younger brother to his kindergarten for some purpose. Sixteenth chapter
might prove very useful…
*******InputConstraints*******
One number n (1 ≤ n ≤ 1000) — the amount of children in the kindergarten.
*******OutputConstraints*******
One number — the amount of exchange schemes. E.g., for three presents A, B and C there are only two exchange schemes:
 Box A goes to the child B, box B — to the child C and box C — to the child A.
 Box A goes to the child C, box C — to the child B and box B — to the child A.
*******IOTestCases*******
______________________________________________________
1367true
In the top secret district of the top secret city, there is a top secret factory which produces top secret
Secrets. The top secret spy satellite, equipped with top secret imaging devices, took some top secret
photographs. You have to interpret the photograph correctly. This is crucial for success of the top secret
mission involving covert manipulation of potential enemy's Secrets.
The photo is repesented by a W × H matrix of cells, each cell containing one of the symbols:
.  Empty, passable section 
  Horizontal impassable barrier (wall) 
  Vertical impassable barrier (wall) 
+  Impassable junction of horizontal and vertical walls 
#  The Secret 
The Secret is a regular junction (+) with one of the objects of special interest contained inside. This object
of interest is accessible from any of the four sides of the junction.
Unfortunately, secret agents are unable to penetrate walls, nor they are allowed to break them. But this
is the only limitation — they are secret agents, after all.
We'll give a set of examples to clarify the agents' possibilities.
+++ +
## ##
++ +++
In the first example the agent can walk freely from one Secret to another through a hole between the
bottom horizontal and middle vertical walls. In the second example the hole is sealed by the junction.
Agents can't use holes in the top wall — leaving the photographed area poses a huge risk to the mission.
For the sake of simplicity, you can assume that the photographed area is surrounded with the barrier of
"+"es.
++...++ ++...++
#++# #+++#
+++ +++
Similarly, in the first example Secrets are connected, and in the second they are not.
++ +++++++
+#####+ +#####+
+++++++ +++++++
If you remember that the Secret is a special case of junction, it will become clear why all the secrets in
the first example are connected and why every secret in the second example is connected only with its
neighbors.
Your task is to construct the secret connectedness graph. That is, the graph which set of vertices is the
set of all secrets and the edge (a, b) exists if and only if it is possible for an agent to get from Secret a to Secret b without breaking the walls and leaving the area.
Limitations
The dimensions of the photograph don't exceed 1000 × 1000 cells. It is known that there are no more than
100 Secrets on the photograph.
*******InputConstraints*******
Input stream format is rather simple: it contains H lines, and each line contains a string W symbols
long. These strings of symbols dene the secret photograph of size W × H.
*******OutputConstraints*******
Output the incidency matrix of the secret connectedness graph. Secrets are enumerated from top to
bottom, from right to left. The matrix element in the i^{th} row and in the j^{th} column is 1, if i^{th} and j^{th} secrets are connected, and 0 otherwise.
*******IOTestCases*******
input  output 

++
#++
++#..
##..#.
+++  10100
01010
10100
01011
00011 
______________________________________________________
1368true
How do you let your goat walk around your vegetable garden? That becomes a real problem sometimes.
You should make sure the goat doesn't die of starvation, and you certainly don't want all your crops to
be eaten. The garden is a field consisting of 1 × 1 square elements. You can build a fence in some of the
garden's elementary squares. To feed itself, the goat needs to eat all the crops in the area consisting of
K (1 ≤ K ≤ 10^{6}) squares. The goat initially stands in the point of origin (i.e. in the square with
coordinates (0, 0)). You have to put the fence in the minimum number of squares so that the goat will be
able to visit exactly K squares. The area is said to be fenced if it is impossible to leave it moving only in
horizontal or vertical directions.
*******InputConstraints*******
The input stream contains one number K — the total area granted to the goat.
*******OutputConstraints*******
The first line shall contain the amount N of boundary (fenced) squares. Each of the following N lines
shall contain two numbers — X and Y coordinates of the fenced square, respectively. Squares should be
output in the order of traversal.
*******IOTestCases*******
input  output 

3  7
1 0
0 1
1 2
2 1
2 0
1 1
0 1 
______________________________________________________
1369true
At last, the spring came. Buds swell on the trees, the snow has almost thawn out. More and more often
you can hear birds' sonorous twittering from the outside. Less and less students you can see at the USU
mathmech department. Even the cockroaches, usual inhabitants of the hostels, show up very rarely.
What's the connection between these phenomena, you may ask.
The answer is the Day of Mathematician and Mechanician celebration, which will begin really soon. At
the same time, the traditional cockroach race will take place in the USU. That's what the students are
occupied with now  they are training their pets. Everyone wants his pet to become the prizewinner and
to receive the proud name of "Magaz".
The race rules are somewhat unusual. Every round, some kind of sweets are placed in N points of the
racing area. Together with sweets, M cockroaches are released. N cockroaches that reach these little
delights of cockroaches' life, will make it to the next round.
During the race all spectators have an unique opportunity to place bets and to win a lot of money.
But the totalizator organizers are puzzled, they cannot understand how to calculate the probabilities of
cockroaches' victories quickly and without mistakes. This is absolutely required to make the maximum
profit out of their enterprise. Mathmech is rather big department and everyone here wants to participate.
You are to determine, for each of N pieces of sweet, which of the cockroaches is closest to that piece. This
will help to determine the race leaders.
*******InputConstraints*******
The first line of the input contains the number M (1 ≤ M ≤ 100000). M lines follow, containing 2 numbers each — these are coordinates of the cockroaches at the present moment.
(M + 2)nd line of the input stream contains the number N (0 ≤ N ≤ 10000). N following lines contain coordinates of sweet pieces. All coordinates are floating point numbers (−10000.0 ≤ x, y ≤ 10000.0). The distance between any two cockroaches is not less than 10^{−3}. Also the distance between any two sweets is not less than 10^{−3}.
*******OutputConstraints*******
For each piece of "Cockroach Sweets" you should output all cockroaches closest to that piece in ascending
order of their numbers separated by spaces.
*******IOTestCases*******
input  output 

4
0 0
1 0
0 1
1 2
2
0 0
0 2
 1
3 4

______________________________________________________
1370true
Denis Mednoepole is a famous magician. For example, he can read spectators' minds and tell the random
number that a spectator has got by means of Denis's magic machine. Any spectator can check this: he
or she just rotates the wheel of the machine and looks at the 10digit number that has appeared in the
window of the machine. Within two seconds Denis will read the spectator's mind and tell the number.
You must write a program that will tell this number even faster — within one second. You need to know
that the magic machine has a wheel with N digits written along the edge of the wheel without spaces
between them. All digits are of the same width. The window is 10 digits wide, so it shows 10 successive
digits. Each time the wheel turns "one digit" an audible click is produced. So you know how many clicks
Denis Mednoepole heard while the spectator was rotating the wheel.
*******InputConstraints*******
The first line contains two integers separated with a space, N and M. Here N (11 ≤ N ≤ 1000) is the
number of the digits written on the wheel, and M (1 ≤ M ≤ 32767) is the number of clicks produced by
the wheel. The next N lines contain all the digits written on the wheel, one digit per line. The digits are
given in the clockwise order. The first ten digits correspond to the number visible in the window before
the rotation. The wheel can be rotated only counterclockwise, thus after one click the first digit will go
out of site and the 11th digit will become visible.
*******OutputConstraints*******
Write the number that will appear in the window of the magic machine after the rotation.
*******IOTestCases*******
input  output 

12 7
1
2
3
4
5
6
7
8
9
0
7
7  8907712345 
______________________________________________________
1371true
Advanced Carriage Messaging company does business in cargo delivery, so it has a complicated network of branch offices. Business is successfull, and it was decided to establish new offices to extend further the delivery network. But first of all company management department wants to analyze the efficiency of delivery between offices. You were asked to do this analysis, because of your renowned experience and knowledge.
Delivery works in the following way. There exists exactly one route of cargo delivery from any office to another office (possibly via intermediate ones). The times t[i, j] of cargo delivery between two offices (with numbers i and j) have been measured. These times are available only for offices which have direct communication. Direct cargo delivery for other offices is impossible. You are asked to calculate the average delivery time between offices, i.e. the following value:
sum (t[i, j]) / (N*(N − 1)), where the sum is taken for 1 ≤ i, j ≤ N and i ≠ j.
*******InputConstraints*******
The first line of input contains one integer N (2 ≤ N ≤ 50000) — the number of branch offices of ACM company. Each of next N−1 lines contains three numbers a_{i}, b_{i}, c_{i}. Numbers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ N) are numbers of offices which have a direct communication between them. Integer number c_{i} (0 ≤ c_{i} ≤ 1000) is a cargo delivery time between these offices.
*******OutputConstraints*******
Output must contain a single number: average cargo delivery time between branch offices of ACM company with a precision of 4 decimal digits.
*******IOTestCases*******
input  output 

4
1 2 1
2 3 1
2 4 1
 1.5

______________________________________________________
1372true
A long time ago in a galaxy far, far away…
Well, let's skip these well known entry words of the famous movie.
No doubt, anyone knows them.
Anyway, a long time ago in a galaxy far, far away there was a space station named "Death star". For those of you who do not remember it, we would remind that it mostly looked like a big metal ball with lots of turrets on its surface. And somewere between turrets there were towers with maneuring engines on a top of each tower; that allowed the station to turn in space. All the engines were the same: standard krypton engines with autonomous power supply. And all the towers were the same. Each of the engines could be in two distinct states: switched off and switched on to a maximum power. But it was not a problem since each engine could be rotated individually relative to the station.
Unfortunately, the engine control cable was damaged after one of the space battles: it was melted by the direct hit of a rebel laser weapon. So all the manoeuvre drives became uncontrollable. All of them which were at maximal power just kept working. Switched off engines remained in that state. Death Star won the battle, but stuck manoeuvre drives made a strange effect: instead of smooth and majestic movement through space, station makes unpredictable rotations which are unsuitable for the Imperial fleet flagship.
It makes Emperor annoyed. No, not just annoyed but furious, because it seems to him that the station rotates faster and faster, and he already feels nauseous.
You have to fix the situation as soon as possible, otherwise you are not guaranteed to stay alive for long.
Engine control cable can be fixed in a week. You see, it is too long. So you have to establish another engine tower with a maintenance engine to stop the rotation. And you have to do this really quickly.
You may have thought that you would need to solve a lot of complex differential equations and to write engine controlling program. No, not at all. As a station engineer, you must know that jet thrust of a maintenance engine does not change over time. It depends on jet nozzle size only. So you only have to find the suitable place for the engine tower, calculate jet nozzle size, set up thrust vector and switch the maintenance engine on. No matter how you do it. Just make it in such a way that the working krypton engines won't further speed up the rotation.
*******InputConstraints*******
In the first line of input, some technical data on the Death Star station are given. You know, these are top secret data, but without them you will definitely fail your mission.
The first number gives a radius of station in meters (it ranges from 100 to 2000),
then total station mass is given (in kilograms, not greater than 40000000, you may assume that the mass is uniformly distributed throughout the station), followed by the height of a standard engine tower (in meters above the station surface; maintenance engine will be placed on the very same tower, and you may place this maintenance engine tower anywhere on the station surface).
Next line of input contains krypton engine description. It starts with a number F — standard jet thrust of krypton engine in newtons (ranges from 1 to 100000). Then an integer number N (1 ≤ N ≤ 9) follows.
It is a number of krypton engines currently working at maximum power.
Each of the following N lines contains description of working krypton engine placements. Each line contains 4 numbers. These are: longitude (from 0 to 360 degrees) and latitude (from −90 to 90 degrees) of engine placement relative to the station. Other two numbers define the jet thrust vector of the engine: if this vector is applied to the center of the station, then it would intersect station surface at the
point with longitude and latitude given by these two numbers.
*******OutputConstraints*******
Print 5 numbers with a precision of eight decimal digits: two numbers (longitude and latitude) must define place to establish the maintenance engine tower, then two numbers must define jet thrust vector (in notation described above) of the maintenance engine, and the last number must define jet thrust
in newtons. You should choose the placement with the least jet thrust among different possible maintenance engine placements.
*******IOTestCases*******
input  output 

100.3 1000000.45 15.5
156.5 1
0.0 0.0 90.0 0.0
 0.00 0.00 270.00 0.00 156.50

______________________________________________________
1373true
Don't you want to be a millionair? It is so simple! You only need to automate some prevalent handwork, and then you save enough money to buy so long wanted beautiful red Ferrari.
For example, why not to automate a process of dime novels? Or why not to automate a process of writing songs for popstars?
No! It is too simple for real programmer, it is below you! So in this task you will need to automate something spiritual: the process of paintings creation! Just think about it: home computer will be able to create beautiful landscapes, artful still lifes and even delicate selfportraits!
Frankly speaking, painting algorithm is already developed and implemented by your colleague, great programmer Mr.Petrov. His algorithm makes a description of brushstrokes, so it is enough to load this description into plotter, and in a couple of hours the picture will be ready.
Meanwhile a frame for the picture may be prepared. But this is where Mr. Petrov fails: he can not calculate size of the picture given the brushstrokes description produced by his algorithm…
It could be just trivial if each brushstroke was a line segment. But the major innovation of Petrov's algorithm is that his rushstrokes has a form of an angle. To make this kind of brushstroke one needs to draw (by a brush, or a plotter) a line segment of X millimeters length in one direction, then turn 90 degrees clockwise and draw another line segment of X millimeters length. This is what innovative Petrov's brushstroke looks like.
*******InputConstraints*******
Input contains N (0 ≤ N ≤ 100000) lines of numbers. Each line describes single brushstroke. Description consists of four integers: coordinates of the start and coordinates of the end points of the brushstroke. All integers do not exceed 10000 in absolute value.
*******OutputConstraints*******
Output should contain 2 numbers: the width and the height of the smallest frame for the picture, produced by brushstrokes description given in input. Numbers must be separated with single space. And they should have a precision of 4 decimal digits.
Notice, that picture must not be rotated, even if it allows to fit the picture into the frame of smaller size. Your task is not to save materials, from which the frame is made. You just have to prepare suitable frame for the picture. Also make sure that all parts of each brushstroke are inside
the frame.
*******IOTestCases*******
input  output 

0 0 1 1
1 1 2 0
2 0 0 0
2 0 3 0
 3.0000 2.0000

______________________________________________________
1374true
Naked man walks along the streed. Policeman stops him ans asks:
"Are you alright? Why naked?"
Man answers with a question:
"Listen, does a misere ever gets spoiled by 7, 9 and J?"
Policeman: "Never!"
Man: "And I thought so…"
It is six o'clock. Morning. Or night. Kitchen. Four students play a game of
preference. Or do not play. Indeed, they do not play. But why? What happened? What are they busy with? Oh… They dispute about something. Oh, got it!
One of them bid a misere contract. And believes that he will not get any trick. But other players are trying to convince him of being wrong. Their voices are already hoarse. They even opened all the cards! Made discarded cards known! But nothing helps…
Then one of them tells:
— Aren't we students of Mathematical and mechanical department? Let's write
a program, which will look over all possible plays and justify us.
Nobody objected. But because of they were bad students or maybe due to sleepless
night the program was never written… Will you help them?
Oh, you need to know some basic facts about preference. Precisely, you only
need to know rules of playing a misere.
Preference is played with 32 cards: the Ace (A), King (K), Queen (Q), Jack (J), 10, 9, 8 and 7s (in the order of decreasing rank) from a standard 4suit 52card deck. Suits are usual: Spades, Clubs, Diamonds and Hearts. Preference is played by three players sitting at the round table (in fact, the shape of the table does not matter; the only important thing is that each player has right and left neighbour and that players are numbered clockwise).
After cards are dealt, bidding takes place. We omit bidding rules here, they are not important for this problem. One of the possible result of bidding is a misere contract. It means, that player will try to win no tricks with his cards.
After the bidding each player has 10 cards.
So 10 tricks are played. Each trick is played in the following way. The player, who leads the first trick, puts any of his cards on the table face up. Then his left neighbour puts his card. Then remaining player puts his card.
Each player must follow the suit of the first card in a trick, if possible. Otherwise, he may discard any card from his hand. The player, who put the card of the highest rank with a suit of the first card in a trick, wins that trick. The player who wins a trick leads the next trick.
Successfull playing of the misere contract gives a big profit to the player. But each won trick gives a great loss. Now you know the actual reason for the dispute!
Your task is to justify the students. Given cards of each player and a number of the player, who leads the first trick, you are to determine, whether the first player, who declared the misere contract, is able to play the declared contract regardless of the other players' strategy.
*******InputConstraints*******
Each of the first three lines of the input contain cards of the corresponding player. Each card is described with two characters: a suit (one of the S, C, D or H) and a rank (one of the 7, 8, 9, 10, J, Q, K or A). Card descriptions are separated with space(s). The fourth line contains the number of the player, who leads the first trick.
*******OutputConstraints*******
Output should contain exactly one line. In case when the misere contract can be played successfully regardless of the strategy of other players, this line should contain ";)".
Otherwise it should contain ";(".
*******IOTestCases*******
input  output 

7S 8S 9S 10S JS QS KS AS 7C 8C
9C 10C JC QC KC AC 7D 8D 9D 10D
JD QD KD AD 7H 8H 9H 10H JH QH
1
 ;)

______________________________________________________
1375true
System administrator with a well sounding name of Bill Clevers pays great attention to operating system security vulnerabilities. He truly believes that a system protection must be rather original to be reliable. So he decided to design a new public key cryptography system. No sooner said than done. One sleepless night, a little use of his favourite shamanic tambourine (did you hear about this important tool of system administrator?), a couple of broken computers, and a brand new cryptographic system is designed!
In this cryptosystem, public key is a pair of numbers (k, p) where
p must be a prime number and 0 ≤ k ≤ p−1. Private key is a pair of numbers (x, y), which satisfies the following relation:
x^{2} + y^{2} = k (mod p)
Of course, Bill does not think that his cryptographic system is better than RSA, but it is definitely much less known to potential hackers.
Everything could be just fine, if Bill had not (unfairly!) restricted access to some Internet sites, which were used by the remarkable programmer Bob Buggins to create his software masterpieces. Evidently, this unfair act of Bill must be circumvented somehow. To do it, Bob just needs to recover Bill's own private key from the corresponding public key. But Bill's cryptographic system appears strong enough! That longawaited private key still can't be found by Bob…
*******InputConstraints*******
Input contains two integers: k and p. Number p is a prime number, 2 ≤ p ≤ 10^{6}; 0 ≤ k ≤ p−1.
*******OutputConstraints*******
Output any pair of integers x and y (0 ≤ x ≤ p−1, 0 ≤ y ≤ p−1) such that x^{2} + y^{2} = k (mod p). If there is no such a pair, output "NO SOLUTION".
*******IOTestCases*******
______________________________________________________
1376true
At Ural Championship 2004 there was a task "
Dean's pyramid". Briefly it looks like the following:
There is an egiptian like glass pyramid on the table of Ural State University mathematics and mechanics faculty dean. The faculty legend says that before weak student gets sent down, dean gives the student the last chance. He puts unsigned list of dismissed students at one side of the table, and puts the pyramid at another side. If the student is able to move the pyramid to the locus of deans signature on the dismissing listplace, by rolling the pyramid over the edges for no more than 70 times, the student
stays at the faculty (for the last time).
The task was to determine, how close the pyramid can be moved to the target point under the following conditions. The pyramids base is square and its lateral faces are regular triangles. You can roll the pyramid by turning it from one face to the adjacent one over some edge. During this turning the edge should not slide on surface of the table. If after the turn over some edge the pyramid stands on its base, the next turn can be performed either over the same edge or over the opposite edge of the pyramids base only. There are no restrictions on the rolling from the triangle faces.
After Ural Championship 2004 weak students felt secured: now they know the secrets of dean's pyramid and the simplest algorithm to find the points on the table where the pyramid could be. To learn this algorithm is much, much simpler than to learn theorems. And you never get sent down! The only doubt disturbed them: what if authors of the task garbled something...
And they were right: looking at the hidden camera picture it was found that side faces of the pyramid were not regular triangles, but only isosceles one! And strange rule of rolling the pyramid could be just a fiction of task authors... Weak students feel distress again...
You see, this could be a legend. And could be a truth. The pyramid is so real, and it looks so beautiful at the dean's table...
So help the students for the last time. Try to determine the best way of rolling the pyramid to put it as close as possible to the point of dean's signature.
You are given a number N — the maximum number of rolls allowed by the dean. You are also given an exact size of the pyramid: the length of an edge of square face A_{1} and the length of a side edge A_{2}. Both lengths are given in centimetres. It was estimated by eye that a value of A_{2}/A_{1} is in a range from 0.9 to 1.9. It is known that the dean is severe enough, so he puts dismissing list far enough from the pyramid. You may assume that the pyramid is originally
placed not closer than 20.05 * A_{1} to the point of the dean's signature.
Pyramid originally stands on its base with
a center of the base placed at the point (0,0) and with edges of the base parallel to the axes of coordinate system. You are to find the sequence of rolls by which the pyramid gets to the point (X,Y) as close as possible. After the last roll the pyramid
again must stand on its base, though edges of the base could be arbitrary oriented.
But the distance between the center of the pyramid base and the point (X,Y) must be as small as possible. In the case of tie, you also have to minimize the number of rolls. You are allowed to make less than N rolls.
The pyramid can be rolled from one face to another only via their common edge. And the edge should not slide on surface of the table during the roll.
*******InputConstraints*******
Input contains the numbers A_{1} and A_{2}
(in centimetres, both in range from 0.1 to 10). Two numbers X and Y follows. They are the coordinates of sacramental point of the dean's signature. The number N (2 ≤ N ≤ 32) ends the input.
*******OutputConstraints*******
You have to conform the following format. First of all pring the distance between the center of the pyramid base and the signature point in the pyramid's final placement. This distance must be printed correct to three places of decimals. Then print the number M (0 ≤ M ≤ N) of rolls required to get the printed distance.
Then print M+1 numbers — the numbers of the faces on which the pyramid stands after each roll. Separate these numbers with spaces. And do not forget to start this list with the number of the pyramid base on which it stands initially.
Faces of the pyramid are numbered according to the following scheme. The pyramid's base has number 0. The side faces are numbered clockwise by 1, 2, 3 and 4 being looked
from the top of the pyramid standing on it's base. The face of the pyramid which looks to positive direction of 0Y axis has a number 1.
*******IOTestCases*******
input  output 

10.0 10.0 1000.0 0.0 5
 972.679
5
0 2 3 4 1 0

______________________________________________________
1377true
A cemetery has a form of rectangle. There are N rows of graves, M ones in each row. The cemetery is enclosed with a high and deep fence.
Lara Petrovna Croft has penetrated into the cemetery through the sap at the Northwestern corner. It takes one night for Lara to dig a subway under one of the graves. If there is an intact grave straight ahead then Lara will lengthen the passage during the next night and will ravage the grave. If there is a cemetery fence or a ravaged grave on the way, then Lara will turn 90 degrees clockwise and will continue with her questionable affairs.
Treasures are located in two graves only. And we exactly know in which ones. But Lara doesn't. Lara has bought a package of champagne today. It means, that today she has found one of those graves. We wonder how long will it take her to find the other one?
*******InputConstraints*******
The first line contains two numbers N and M (2 ≤ N,M ≤ 100) — the sizes of the cemetery. The second and the third lines contain the treasure graves coordinates.
Assume that the NorthWestern grave has coordinates (1,1) and the SouthEastern — (N,M). Lara starts with the grave (1,1) moving to the East, i.e. towards the grave (1,2).
*******OutputConstraints*******
Output an amount of days that Lara will spend reaching for another grave with treasures.
*******IOTestCases*******
______________________________________________________
1378true
In his novel "2001: A Space Odissey", Arthur C. Clarke described a situation when a spaceship computer strengthened with an artificial intelligence decided to get rid of humans being aboard. To achieve its goal, the computer invented some tricks. In particular it was able to make a man leave the spaceship without a spacesuit...
In fact, many people just like science fiction writers thought that in the year 2000 the artificial intelligence would be definitely invented. And computers would communicate with humans as equals. Now it is evident that even the problem of human speech recognition (we do not speak about recognizing the meaning of what's said!) is hard enough.
Your task is to make a big step forward and to write a program to recognize photos. There is a photo of a man. You are to process the photo and recognize the nationality of the man. During this competition we will give you photos of Flatland citizens only. So there are only three nationalities: Circle, Square and Triangle.
*******InputConstraints*******
The first line of the input contains two numbers W and H — the width
and the height of the photo (1 ≤ W, H ≤ 1000). Then H lines of W numbers of 0 or 1 follow. It is a blackwhite photo of a black figure (circle, square or triangle) drawn on a white background in a standard photo editor. There is only one figure at the photo. The figure does not touch the borders of the photo. It does not exceed the bounds of the photo either. Size of the biggest side or the radius of the figure is not less than 30 pixels. The least angle of the triangle is not less than 10 degrees.
*******OutputConstraints*******
Just print one of the following words: circle, triangle or square, depending on what figure is drawn at the picture.
*******IOTestCases*******
input  output 

32 32
00000000000000000000000000000000
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
01111111111111111111111111111110
00000000000000000000000000000000
 square

______________________________________________________
1379true
It was decided to prepare specially designed cups with a competition logotype of Ural Championship 2005 for each participant and
for any observer, who wish to have such a cup.
Having a habit to do such important things at the last moment, designer finished his job with a cup design two days before the
Championship. So there is a shortage of time. One day is needed to manufacture the cups and to put Championship logotype onto them. So there are 24 hours left to deliver the cups from an enterprise to contest area.
Of course, it is impossible to deliver ten million cups (this is the amount of cups ordered by organizing committee) in a one trip. But it is desirable to deliver as many of cups as possible in a one trip.
Organizing committee ordered one big delivery truck. One would try to load the truck by the cups for it's full load. But some roads have weight limit: if the weight of the truck exceeds the road weight limit,
it can not pass the road. So it is possible, that fully loaded truck can not go along the shortest route of delivery, it has to use longer route with acceptable weight limit. Moreover, it is possible, that the fully loaded truck will not deliver the cups in time. And it is definitely unacceptable.
So, how many cups can be loaded into the truck, so that this precious load could be delivered in time without violation of road weight limits?
*******InputConstraints*******
The first line contains two numbers: the total number of road map nodes N (1 ≤ N ≤ 500) and the total number of roads M.
Next M lines contain information about the roads. Each road is described on a separate line in the following way. Two numbers of road map nodes connected by the road go first. They are followed by the time required to pass the road. Finally the weight limit for the road goes. It is known that each road connects two different road map nodes. And for any two road map nodes there is at most one road connecting them. All numbers are separated with a one or more space(s).
Road map nodes are numbered with an integers in a range from 1 to N. Enterprise, where the cups are manufactured, is always placed in a node 1. And Urals Championship area always in at node N. Road passage time is given in minutes, and it does not exceed 1440 (24 hours). Weight limit is given in grammes, and it does not exceed 10^{9}. One cup has a weight of 100 grammes, and the empty truck has a weight of
3 tonnes (1 tonne = 1000 kilogrammes; 1 kilogramme = 1000 grammes).
*******OutputConstraints*******
Print the only number: the total amount of the cups (it must be as much as possible), which can be delivered in the first trip of the truck in a time of 24 hours.
*******IOTestCases*******
input  output 

3 3
1 2 10 3000220
2 3 20 3000201
1 3 1 3000099
 2

______________________________________________________
1380true
The wellknown grandmaster Bender arrives at the city of Petrozavodsk. Among others, there were Ha, Ru and Po to come to the simultaneous chessgame. Ru had lost the game N (1 ≤ N ≤ 10^{9}) times, Po had lost the game M (1 ≤ M ≤ 10^{1000}) times, and Ha hadn't counted his losses as all. The friends had noticed that Bender played in his own style: the chesspieces occasionally disappeared from the board, or new pieces occasionally appeared. Bender has no
shame, and he can do the cheats with any chesspiece. Then Ha got tired of these games, and he decided to start writing down the moves, having written down the current position first. You have to tell from Ha's notes whether Ostap cheated during play, or not.
The rules of chess, as known by Ostap, are much like the common ones, but Ostap doesn't know such concepts as en passant, castling and promotion. Otherwise, the pieces move just like the usual chesspieces do. A player's move is considered legal if the only piece moved is this player's piece, and his king isn't in check at the end of the move. A king is considered in check when its location is under attack of a hostile piece, and checkmated when, in addition to this, there is no legal moves. Stalemate (a draw) is a position when neither king is in check, and there is no legal moves. The initial position may be senseless; it needn't be verified before the first move.
*******InputConstraints*******
The current position is given as 64 numbers, delimited with spaces or
newlines. The number 0 corresponds to an empty square, 1 — to pawn, 2 — to knight, 3 — to bishop, 4 — to rock, 5 — to queen, 6 — to king. The positive numbers correspond to white pieces, and their negative counterparts — to black ones. A number 1 ≤ P ≤ 60 follows, which gives the number of moves written down by Ha.
Following is the color of player to move, either 'White' or 'Black'.
At last, the P moves are given, formatted as squaresquare, where
a square is a letter ah (a corresponding to the leftmost file, h to
the rightmost) followed by a number 18 (1 corresponding to the
bottommost rank, 8 to the topmost).
*******OutputConstraints*******
For each move, your program must output either of the following messages:
"Incorrect" for illegal move, "Mate" for checkmate, "Check" for check, "Draw" for stalemate, "Correct" for neither of the above. After an illegal move, checkmate or stalemate, the program must output an empty line followed by the current position, formatted in the same way as the input, without performing the illegal move. The moves following the illegal move, checkmate or stalemate must be ignored.
*******IOTestCases*******
input  output 

4 2 3 5 6 3 2 4
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
4 2 3 5 6 3 2 4
2
White
e2e4
e7e4
 Correct
Incorrect
4 2 3 5 6 3 2 4
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 0 1 1 1
4 2 3 5 6 3 2 4

4 2 3 5 6 3 2 4
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
4 2 3 5 6 3 2 4
8
White
e2e4
e7e5
d1f3
h7h6
f1c4
g7g6
f3f7
e8f7
 Correct
Correct
Correct
Correct
Correct
Correct
Mate
4 2 3 5 6 3 2 4
1 1 1 1 0 5 0 0
0 0 0 0 0 0 1 1
0 0 0 0 1 0 0 0
0 0 3 0 1 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 0 1 1 1
4 2 3 0 6 0 2 4

0 0 0 0 0 6 0 6
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 5
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1
White
h6a6
 Correct
0 0 0 0 0 6 0 6
0 0 0 0 0 0 0 0
5 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

______________________________________________________
1381true
Petya lives in a manystoried building where each flat occupies an entire story. Petya has studied local flora and fauna for many years. Having performed montly metering, he notices the following peculiarities:
 The number of cockroaches in each of the flats is an integer ranged from 0 to N, where N is a nonnegative number not exceeding 30.
 The number of cockroaches in a flat during a month is a function of three arguments: the number of cockroaches in this flat and the flats
above and below this one during the previous month.
Petya becomes interested in inducing the ways the insects' population size changes under these laws. To avoid the special cases of ground
floor and top floor, where the laws might be more complicated, Petya decided to solve this problem for an infinitestoried skyscraper. Let's consider that the number of cockroaches can decrease if they can be distributed among the flats (having no more than
N in any) in such a way that in the next month the total number of cockroaches in the building will decrease. Only a finite number of cockroaches can exist in the building; thus, all the flats, except a finite number of them, are free from these insects. Likewise, the number of cockroaches can increase if they can be distributed among the flats in such a way that in the next month the total number of cockroaches in the building will increase (and may possibly become infinite).
*******InputConstraints*******
The first line of the input contains the single number N — the maximum number of cockroaches in a flat. Following are samples of the function that defines the changes in the
number of cockroaches in a flat. The samples are organized in a table having N+1 block, where each block has N+1 lines, and each line has N+1 numbers ranged from 0 to N. k'th number of i'th line of j'th block contains the number of cockroaches in the flat for the current month
if in the previous month there were j cockroaches in it, i cockroaches
in the flat below, and k cockroaches in the flat above. The indices of blocks, lines, and numbers are zerobased. Petya has studied that if there were no cockroaches in some flat and in the flats below and above it in the previous month then there are no cockroaches in it in the current month.
*******OutputConstraints*******
The output must contain either:
 =, if the number of cockroaches can neither increase or decrease, or
 <, if the number of cockroaches can decrease, but not increase, or
 >, if the number of cockroaches can increase, but not decrease, or
 <>, if the number of cockroaches can both increase and decrease.
*******IOTestCases*******
input  output 

1
0 1
0 1
0 0
1 1
 =

2
0 0 0
0 0 0
0 0 0
1 1 1
1 1 1
1 1 1
2 2 2
2 2 2
2 2 0
 <

______________________________________________________
1382true
Tyomitch plays the following game with
N of his friends. Tyomitch leaves the room. His friends write numbers from 1 to
N on cards,
and each of the friends takes a card in a way that Tyomitch doesn't know which card each one has.
Let's number the friends from 1 to
N. After Tyomitch comes back to the room,
each of his friends makes 2 statements of the following form (examples given for
i'th friend):

I have the card number a_{i}.

b_{i}'th friend has the card number c_{i} (b_{i} ≠ i).
Exactly one of these statements is true, and the other one is false. It's known that no two friends said that friend
b has card
c, and nobody said that friend
b has card
c if
b admitted that he has this very card. The task for Tyomitch is to determine for each of his friends which of
his statements is true.
*******InputConstraints*******
The first line of the input contains the number N (2 ≤ N ≤ 1000). Each of the following N lines contains a triple a_{i}, b_{i}, c_{i} — the statements of Tyomitch's friends.
*******OutputConstraints*******
The only line of output must contain N numbers separated with spaces, being the numbers of the true statement (either 1 or 2) for each of the friends. It is known that a solution exists.
*******IOTestCases*******
input  output 

5
3 4 3
1 3 2
3 2 5
2 5 4
3 4 1  1 2 2 2 2 
______________________________________________________
1383true
There were N people to take part in the competition for a flowergarden design. Each of them had proposed his design, the finite sequence of points in plane which are the suggested locations for flowers. To save the main jury from needless labor of considering identical designs, the prejury wants to find the designs which only differ in rearrangement of points and their affine transformation that doesn't change the orientation (that is, the radiusvector of each point is multiplied by a matrix with positive determinant and translated by a fixed vector).
*******InputConstraints*******
The first line of input contains the single number N (N ≤ 10000). The N designs follow. Each design is represented as the length of the sequence M, followed by coordinates of points (M pairs of integers whose absolute value doesn't exceed 1000, each pair on a line by itself). The sum of all sequences' lengths doesn't exceed 200000.
*******OutputConstraints*******
The first line of output must contain the number of different design classes. The following lines must list the classes as onebased indices of designs, terminated with zero.
*******IOTestCases*******
input  output 

7
5
1 2
0 0
6 0
0 4
2 7
5
1 2
3 9
0 1
2 3
9 2
5
43 37
73 47
3 3
23 7
3 63
3
0 0
1 0
0 1
3
0 0
1 0
3 0
3
10 3
3 7
5 2
3
6 1
6 5
6 7  4
4 6 0
5 7 0
1 3 0
2 0 
______________________________________________________
1384true
Tyomitch takes his favorite goat for a stroll through his neighbor's cabbage garden. Tyomitch had to go away for a while, and he decided to drive a stake into the ground and to bound the goat to the stake to prevent it from eating up all the neighbor's cabbage. To save his pet from starving to death, Tyomitch wishes to select such a spot for the stake, and such a length for the rope, that the goat could deal with as large area of the garden as possible. However, there's a little problem: the goat, when left alone with the garden, tries to pierce the garden's fence with its horns. The goat will succeed if it can reach the fence with its horns and the rope has even a little slack at this moment. Tyomitch wants to avoid the traces of the uninvited guests getting noticed by the neighbors, so he tries to bound the goat in such a way that the fence would remain safe and sound. Your task is to help him. You only have to find the length for the rope, and Tyomitch will locate the stake on his own.
*******InputConstraints*******
The neighbor's garden is polygonal with N vertices, and it may be nonconvex. The first line of the input contains the number N (3 ≤ N ≤ 25). The next N lines give the coordinates of the vertices, listed counterclockwise. (i+1)'th line will give the coordinates x_{i} and y_{i}, being integers between 0 and 1000 inclusive. The garden is so large that you can consider the goat a point.
*******OutputConstraints*******
Your output must be the single number R — the length for the rope, rounded to 2 digits after the decimal point.
*******IOTestCases*******
input  output 

3
0 0
200 0
0 200  58.58 
______________________________________________________
1385true
Tyomitch calls the number with 2N digits (without leading zeroes) "interesting", if it's divisible by both the number formed from its first N digits and the number formed from its last N digits.
For example, 1020 is "interesting" (divisible by 10 and 20) and 2005 is not. Tyomitch wants to know how many "interesting" 2Ndigit numbers exist. You are to help him.
*******InputConstraints*******
Input contains an integer N (1 ≤ N ≤ 10000).
*******OutputConstraints*******
Output the number of "interesting" 2Ndigit numbers.
*******IOTestCases*******
Hint
11, 12, 15, 22, 24, 33, 36, 44, 48, 55, 66, 77, 88, 99.
______________________________________________________
1386true
One of the most popular games of all times is the "Maze". The game is played on a N × M table. The player can make the instructions: 'left', 'right', 'up', 'down'. For each cell of the table and each instruction the gamemaster has defined the destination cell that the player moves to; that is, the player is given the map of the maze. Once a game was interrupted, and the master has forgotten which cell the player was in. Fortunately, a full record of the
gameplay has remained, which is the sequence of the instructions made by the player. You are to write a program determining the cells that
the player can be currently in.
*******InputConstraints*******
The first line of the input contains two numbers N and M (1 ≤ N,M ≤ 100). Four blocks of N lines each follow. Each line contains M pairs, being the new coordinates of the player after making k'th instruction standing in the cell (j, i), where i is the number of pair in the line, j is the number of line in the block, and k is the number of block.
Following is the number S (1 ≤ S ≤ 4000) of the instructions made by the player. The last line contains the S numbers of the instructions made.
*******OutputConstraints*******
The first line of the output must contain the number L of the cells that player can be in after making the given sequence of instructions. Each of the next L lines must contain the coordinates of these cells, ordered first by the first coordinate, and then by the second.
*******IOTestCases*******
input  output 

2 3
1 2 1 3 1 3
2 2 2 3 2 3
2 1 2 2 2 3
2 1 2 2 2 3
1 1 1 1 1 2
2 1 2 1 2 2
1 1 1 2 1 3
1 1 1 2 1 3
4
1 2 3 4  2
1 1
1 2 
______________________________________________________
1387true
Vasya’s dad is good in maths. Lately his favorite objects have been "beautiful" directed graphs.
Dad calls a graph "beautiful" if all the following conditions are true:
 The graph contains exactly N vertices and N−1 edges.
 Exactly one vertex has no entering edges.
 The graph contains no directed cycles.
Dad calls two "beautiful" graphs isomorphic, if the vertices of the first graph can be renumbered in such way that it turns into the second one.
Dad picks an integer N, stocks up blank paper, and draws a "beautiful" graph on each sheet. He verifies that no two drawn graphs are isomorphic.
Given the number N, you are to find the number of sheets that Vasya's dad has to stock up.
*******InputConstraints*******
Input contains the single integer N (1 ≤ N ≤ 50).
*******OutputConstraints*******
Output the number of "beautiful" graphs with N vertices.
*******IOTestCases*******
______________________________________________________
1388true
A river flows down the plain along the line y = 0. There are trees growing in the plain to the both sides of the river, but not on the river itself. A dam is positioned on the river in the point (0,0). It is necessary to make two matching photos of the two riversides
from the dam. The photos are considered matching if the arrangement of the trees on them match (only the horizontal arrangement is considered, not the distance to the trees).
If a tree is obscured with another one, the tree isn't present in the photo. No two trees occupy one point. Sizes of the photocamera and the trees are negligible.
The photographing occurs in the following way: first a camera is used whose spanning angle is arbitrary close to 180 degrees (the photofilm
is a line, and trees in front of it are centrally projected onto the film, center is point (0,0)); then a segment with trees from one riverside only is cut out of the film, and scaled arbitrarily.
*******InputConstraints*******
Each line of the input, except the last one, contains the coordinates of the trees (two integers from −20000 to 20000). The number of the trees doesn't exceed 10^{5}.
The last line contains two zeros.
*******OutputConstraints*******
The output must contain a single number, being the maximum number of trees on two matching photos of the two riversides.
*******IOTestCases*******
input  output 

1 1
0 1
2 1
3 1
7 2
3 2
1 1
0 1
0 5
4 2
3 1
0 0
 4

0 1
1 1
2 1
3 1
2 2
1 3
0 0
 3

______________________________________________________
1389true
Once upon a time there was a king. One day the king counted up the collected taxes and decided to
spend the money for the road maintenance. There were N cities in that kingdom and M twoway roads connected them in such way that one could travel from a city to others using these roads. The road network was catastrophic without repairing, so the king made up his mind to repair as many roads as possible during the summer, before the money depreciated. The inhabitants of the kingdom were shocked to know that all the ways they used to go would be blocked for summer. So the king promised that at most one road from a city would be blocked. Help the king to fulfil his plan without displeasing the citizens.
*******InputConstraints*******
The first line of input contains two natural numbers N and M (2 ≤ N ≤ 10^{5}, M = N − 1), separated with a space. Each of the next M lines describes a road in the form (a_{i}, b_{i}), where a_{i} and b_{i} are numbers of the cities connected with i'th road (1 ≤ a_{i}, b_{i} ≤ N).
*******OutputConstraints*******
The first line of output should contain the only integer K being the maximum number of roads that the king can close for maintenance without raising disorders in his kingdom.
The next K lines should describe these roads in the same form as they were given in the input.
*******IOTestCases*******
input  output 

4 3
1 2
2 3
3 4  2
1 2
3 4 
______________________________________________________
1390true
A new pistol is being tested. The pistol can fire shots with variant bullet speeds. In some points of time shots are fired from the point of origin with certain horizontal speeds, and in some other points of time walls are built on a horizontal platform. The walls are nonsingular segments lying on lines that do not go through the point of origin. The walls may intersect. For processing of the test results, you are to determine the time that each shot bullet had been flying for. You can assume that the speed of the bullet after shot is constant.
*******InputConstraints*******
Each line of the input begins with either "shot", "wall", or "end" (without quotes). The number of lines doesn't exceed 50000. After "shot", the two coordinates of speed of the bullet are listed; the speed cannot be zero. After "wall", the four numbers follow, being the coordinates of wall's beginning and end. "end" denotes the end of the input. All the coordinates are integers whose absolute values doesn't exceed 10000. All the events are listed in chronological order, and time intervals between the events exceed the time needed to build a wall, or the time needed for bullet to reach the next wall or end of the proving ground.
*******OutputConstraints*******
For each of the shots, you must output the single number, on a line by itself: the time that the bullet had been flying for, with precision
of 10^{−6}. If the bullet doesn't hit any wall, you must output "Infinite" instead of a number.
*******IOTestCases*******
input  output 

shot 1 0
wall 1 0 0 1
shot 1 1
shot 1 3
wall 1 0 1 2
shot 1 3
wall 1 1 1 1
shot 1 3
wall 2 3 2 3
wall 3 2 3 2
shot 1 1
shot 40 39
shot 9999 10000
shot 1 1
shot 3000 2000
shot 3001 2000
shot 3000 2001
shot 1 0
shot 1 1
wall 1 2 10 10
shot 1 1
shot 0 1
shot 1 1
shot 1 0
shot 1 1
wall 0 10000 10000 0
shot 2 1
end  Infinite
0.50000000000000000000
Infinite
0.50000000000000000000
0.33333333333333333333
2.00000000000000000000
0.05000000000000000000
0.00020000000000000000
2.00000000000000000000
0.00100000000000000000
Infinite
0.00099950024987506247
1.00000000000000000000
0.50000000000000000000
1.00000000000000000000
0.90909090909090909091
0.43478260869565217391
0.83333333333333333333
2.00000000000000000000
3333.33333333333333333 
______________________________________________________
1391true
Everyone knows that snakes have hard time living in mazes. Even if a snake lives alone, it can perish by running into a wall or its own tail. A certain participant of snakes competition called Vasya decided to teach his snake to get out from distant areas of the maze. Such submazes are dangerous because the snake has little chance to
get out from them alive, and of course the longer the snake the less chance it has. Vasya trains his snake in the following way: when it's young and its length is 2, he lets it into a practice dangerous maze. The snake's goal is to get out from the maze as soon as possible. If the snake survives, then the training will be repeated as soon as the snake reaches the length of 3. The training goes so on until the snake either perishes or matures at the length of 18.
The maze is a rectangle with width
W and length
H, each cell of which is either obstructed 'X' or free '.'. The maze is surrounded with impassable stones '*' with the exception of the only entrance '#' located in the border of the maze. Here's a simple 4by3 maze for your reference:
***#**
*.X.X*
*.X..*
*....*
******
The snake of length
L is a sequence of
L cells. Any two consecutive cells have a common side. All the cells in the sequence are different. The snake can creep in 3 ways relative to its current direction: forward, to the left or to the right. All the cells of snake's body move at once, each moving into the place of preceding one, except for the head cell. Here are the examples of snake's movement:
321. > .321

321 > .32
... ..1

12 > 23
.3 1.

12 > 23
43 14
The snake creeps through exactly one cell per unit of time, or perishes if it has nowhere to creep into.
*******InputConstraints*******
The first line of the input contains H and W specifying the size of the maze, where 1 ≤ H ≤ 300 and 1 ≤ W ≤ 30. The second line contains h_{0} and w_{0} being the coordinates of the entrance cell; h_{0} equals either 1 or H, or w_{0} equals either 1 or W. Following are H lines of W characters each, specifying the maze outline ('X' for obstruction and '.' for free cell). Time is counted starting from 0; initially the snake has its head at (h_{0}, w_{0}) and all other body cells outside the maze. Time is counted until snake's head is again at (h_{0}, w_{0}). Even though the maze is a practice one, no snake of length 18 can get out from it alive.
*******OutputConstraints*******
The output must contain 16 lines, where i'th line is either the best time needed for a snake of length i+1 to get out from the maze, or −1 if it can't get out alive.
*******IOTestCases*******
input  output 

9 9
1 5
XXXX.XXXX
XXX...XXX
XX..X..XX
....XX..X
X.X.X.X.X
..XX.....
X...XXX..
XXXXX....
X.....XXX
 10
10
10
22
22
1
1
1
1
1
1
1
1
1
1
1

______________________________________________________
1392true
For the whole last week Ilya Petrov spent his time sitting at the computer and playing his favourite game "Perimeter". But today he suddenly realized that he does not want to look at the monitor. "Hm… It is so strange… What will I do now?" thought Ilya. "Oh! Astronomy! — most wonderful of all sciences. This is what I need!" — he exclaimed. So he did not lose time, he came to a store and bought a big black telescope. This night he spent admiring the beauty of distant galaxies, unreachable (so far) for a human…
The magic of the moment was broken suddenly as Ilya noticed two planets, which have stuck each other. "What is it?" — exclaimed Ilya. He was really amazed. But he thought a little, took a paper and wrote down the following.
"Two planets have stuck each other if they have at least two common points. In this case we will say that each of the planets is reachable from another one. Then an archipelago is a group of planets for which the following conditions are true:
 Each of planets of archipelago is reachable from any other planet of the archipelago (possibly in a several steps).
 There are no planets of the archipelago reachable from any planet outside of archipelago.
Clearly, any set of planets can be uniquely split into archipelagos. You have to find the number of archipelagos for a given set of planets and from which planets each archipelago consists of. The solution of this task will make the humans more powerful and flawless race. So this task is to be solved immediately."
*******InputConstraints*******
The first line of input contains a number K (0 < K ≤ 1000) — the number of the planets in a set. Then K lines with planet center coordinates X, Y, Z and planet radius R follow. All numbers are integer and they do not exceed 1000 by absolute value. Absence of coinciding planets is guaranteed. All the planets are balls.
*******OutputConstraints*******
Output must contain exactly P lines. Here P is the number of archipelagos in a given set of planets. The ith line of output should contain the list of planets constituting the ith archipelago. Each planet in a list is present by its number (planets are numbered by integers starting from 0). Planet numbers in a list must be printed in increasing order with a comma and a space as a separator. Do not print a comma after last number in a list.
Archipelagos must be printed in the following order. If the least number of the planet of one archipelago is less than the least number of the planet of another, then the first archipelago must precede the second in output.
*******IOTestCases*******
input  output 

2
1 1 1 1
1 3 1 1
 0
1

3
1 1 1 1
1 3 1 1
1 4 1 1
 0
1, 2

3
1000 1000 1000 1
999 1000 1000 1
1 1 1 1
 0, 1
2

______________________________________________________
1393true
Let T denote some string of length n consisting of capital
Latin letters. Let Shift(T, k) denote the left cyclic shift of
T by k1 positions. The permutation array for T is an
array P[1..n] such that Shift(T, P[1]), Shift(T, P[2]),
..., Shift(T, P[n]) is a list of cyclic shifts of T sorted in
lexicographical order.
For given two strings v and w we define LCP(v, w) as
the length of their longest common prefix. The Average LCP of the
string T is the average length of longest common prefix between two
consecutive shifts:
Example. T = 'MISSISSIPPI', n = 11:
i 
P[i] 
Shift(T, P[i]) 
LCP 
1 
11 
'IMISSISSIPP' 
1 
2 
8 
'IPPIMISSISS' 
1 
3 
5 
'ISSIPPIMISS' 
4 
4 
2 
'ISSISSIPPIM' 
0 
5 
1 
'MISSISSIPPI' 
0 
6 
10 
'PIMISSISSIP' 
1 
7 
9 
'PPIMISSISSI' 
0 
8 
7 
'SIPPIMISSIS' 
2 
9 
4 
'SISSIPPIMIS' 
1 
10 
6 
'SSIPPIMISSI' 
3 
11 
3 
'SSISSIPPIMI' 

Average LCP of 'MISSISSIPPI' is 1.3
*******InputConstraints*******
The first line of the input contains integer n (1 < n <
250001). The second line contains string T.
*******OutputConstraints*******
The only line of the output should contain the Average LCP of
T with 3 digits after decimal point.
*******IOTestCases*******
input  output 

11
MISSISSIPPI
 1.300

______________________________________________________
1394true
The military intelligence of one country found out that N (N < 100) battle ships of neighboring enemy country are situated in M rows (1 < M < 10). The intelligence knows the lengths l1, l2, ..., lN of the battle ships which are whole numbers in the interval [1, 100], and wants to know in which rows the ships are situated. The only thing that is known about the M rows are their lengths  L1, L2, ..., LM. Assume that the ships touch their neighbours in the rows and that every row contains at least one ship. Write program that will find one possible ordering of the ships in rows.
*******InputConstraints*******
The first line of the input contains N and M. The next N lines contain the lengths of the ships. The next M lines contain the lengths of the rows.
*******OutputConstraints*******
The output should contain M pairs of lines. The first line of each pair should contain the amount of the ships in the current row, the following line should contain the lengths of the ships from the current row. The order of the M row descriptions should be the same as the order in which the rows are given in the input.
*******IOTestCases*******
input  output 

5 2
4
10
2
5
3
11
13
 3
5 4 2
2
10 3

Hint
This problem is the same as 1115 "Ships" but with harder tests.
______________________________________________________
1395true
Background
This problem is a hardcore version of the problem
"Pascal vs. C++". We, Timus Top Coders, dedicate it to those, who still believe in the power of human intellect. In the fact,