Docstoc

15

Document Sample
15 Powered By Docstoc
					2400   Supervisor, Supervisee
2401   Street Polygon
2402   Palindrome Numbers
2403   Hay Points
2404   Jogging Trails
2405   Beavergnaw
2406   Power Strings
2407   Relatives
2408   Anagram Groups
2409   Let it Bead
2410   Simple Computers
2411   Mondriaan's Dream
2412   Equidistance
2413   How many Fibs?
2414   Phylogenetic Trees Inherited
2415   Hike on a Graph
2416   Return of the Jedi
2417   Discrete Logging
2418   Hardwood Species
2419   Forests
2420   A Star not a Tree?
2421   Constructing Roads
2422   The Wolves and the Sheep
2423   The Parallel Challenge Ballgame
2424   Flo's Restaurant
2425   A Chess Game
2426   Remainder
2427   Smith's Problem
2428   Surface Reconstruction
2429   GCD & LCM Inverse
2430   Lazy Cows
2431   Expedition
2432   Around the world
2433   Landscaping
2434   Waves
2435   Navigating the City
2436   Disease Manangement
2437   Muddy roads
2438   Children's Dining
2439   Disconnect the Orange!?
2440   DNA
2441   Arrange the Bulls
2442   Sequence
2443   Set Operation
2444   Partition a Matrix
2445   Squares
2446   Chessboard
2447   RSA
2448   A New Operating System
2449   Remmarguts' Date
2450   A New Kind of Chess
2451   Uyuw's Concert
2452   Sticks Problem
2453   An Easy Problem
2454   Jersey Politics
2455   Secret Milking Machine
2456   Aggressive cows
2457   Part Acquisition
2458   Rigging the Bovine Election
2459   Feed Accounting
2460   Brownie Points I
2461   Magic Bitstrings
2462   Cutting a polygon
2463   Bungee Jumping
2464   Brownie Points II
2465   Adventures in Moving - Part IV
2466   Pairsumonious Numbers
2467   Snow Clearing
2468   Adventures in Moving - Part V
2469   Stack 'em Up
2470   Ambiguous permutations
2471   Bullshit Bingo
2472   106 miles to Chicago
2473   Decorate the wall
2474   European railroad tracks
2475   Any fool can do it
2476   Game schedule required
2477   Help the problem setter
2478   Farey Sequence
2479   Maximum sum
2480   Longge's problem
2481   Cows
2482   Stars in Your Window
2483   Greatest Common Subtree
2484   A Funny Game
2485   Highways
2486   Apple Tree
2487   Stamps
     2488       A Knight's Journey
     2489       Line Segments
     2490       Pimp My Ride
     2491       Scavenger Hunt
     2492       A Bug's Life
     2493       Rdeaalbe
     2494       Acid Text
     2495       Incomplete chess boards
     2496       Military Recruit
     2497       Strategies
     2498       StuPId
     2499       Binary Tree


                                     Supervisor, Supervisee
                                   Time Limit:1000MS Memory Limit:65536K
                                        Total Submit:180 Accepted:34


Description
Suppose some supervisors each get to hire a new person for their department. There are N people to be
placed in these N departments. Each supervisor interviews all N people, and ranks them according to how
much she wants each of them in her department (1 being "really want" and N being "really don't want"). In
turn, each of the N candidates ranks each of the supervisors as to how much that person would like to work
for that supervisor (again, 1 is "really want to work for him/her" and N is "really don't want to work for
him/her"). Given the scores that each supervisor has for each candidate, and the scores each candidate has
for each manager, write a computer program to determine the "best match" of candidates to supervisors.
The "best match" is determined by finding the distribution that leads to the highest overall (i.e. sum of)
satisfaction for all people. The closer a person is to her number one choice, the better. If everyone gets their
number one choice, the average difference will be 0.


Input
The first line of the input will contain a single integer greater than 0 specifying the number of test cases.

The next line will contain a single integer value N, 0 < N < 15, representing the number of supervisors (and
the number of employees - there are N supervisors and N employees). The next N lines will be the
preferences of each of the N supervisors. Each line will contain N integer entries (1 through N for
employees 1 through N), each separated by a space character, that represents the preferences of that
supervisor from most preferred to least preferred. More specifically, the first entry on the line will represent
that supervisor's first choice, the second entry her second, and so on. The next N lines will be the
preferences of the N employees, in the same format as the supervisors.
All lines of data in the input file will end with an empty line.


Output
For each test case, write the test case number (starting with 1) followed by the best average difference
written to six digits of precision to the right of the decimal point. On the next line, show which best match it
was (starting with 1). On the next N lines, show each supervisor (starting with 1) followed by the employee
with which she was matched (1 per line). NOTE: if there is more than one best match, matches should be
listed in ascending permuted order (see sample output).

Separate each data set with an empty line.


Sample Input
2
7
1 2 3 4 5 6 7
2 1 3 4 5 6 7
3 1 2 4 5 6 7
4 1 2 3 5 6 7
5 1 2 3 4 6 7
6 1 2 3 4 5 7
7 1 2 3 4 5 6
1 2 3 4 5 6 7
2 1 3 4 5 6 7
3 1 2 4 5 6 7
4 1 2 3 5 6 7
5 1 2 3 4 6 7
6 1 2 3 4 5 7
7 1 2 3 4 5 6


2
1 2
2 1
1 2
1 2

Sample Output
Data Set 1, Best average difference: 0.000000
Best Pairing 1
Supervisor 1 with Employee 1
Supervisor 2 with Employee 2
Supervisor 3 with Employee 3
Supervisor 4 with Employee 4
Supervisor 5 with Employee 5
Supervisor 6 with Employee 6
Supervisor 7 with Employee 7


Data Set 2, Best average difference: 0.250000
Best Pairing 1
Supervisor 1 with Employee 1
Supervisor 2 with Employee 2



                                                Street Polygon
                                   Time Limit:1000MS Memory Limit:65536K
                                         Total Submit:69 Accepted:6


Description
Two points p and q inside a simple polygon P are mutually visible, if the line segment connecting p and q
does not include any point outside P. The points on the boundary edges of P are considered to be inside P.
Two sets of points are said to be mutually weakly visible, if for each point in one set, there will be a point in
the other set such that the two points are mutually visible. Given two distinct points s and t on the boundary
of P, P is said to be a street polygon with respect to s and t, if the two boundary chains from s to t are
mutually weakly visible. For example, the following figure shows a simple polygon which is a street and
one which is not.




You are to write a program that given a simple polygon P with vertices v1, v2, ..., vn, determines if P is a street polygon
with respect to vj and vk (which are two given distinct vertices of P).

Input
The first line of the input contains a single integer t (1 <= t <= 10), the number of test cases, followed by the
input data for each test case. The first line of each test case contains an integer n (3 <= n <= 20), the number
of vertices of the simple polygon. Next, there are n lines, containing x and y coordinates of the vertex vi in
the ith line, assuming there is an edge between vertices vi and vi+1, and also between vn and v1. x and y
coordinates are assumed to be integers in the range 0 to 100. The last line of the test case contains two
integers j and k (1 <= j, k <= n , j != k).
Output
There should be one line in the output per test case containing a single word YES or NO, depending on
whether P is a street with respect to vj and vk or not.


Sample Input
1
3
10 15
20 30
99 40
1 2

Sample Output
YES



                                      Palindrome Numbers
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:610 Accepted:210


Description
A palindrome is a word, number, or phrase that reads the same forwards as backwards. For example, the
name "anna" is a palindrome. Numbers can also be palindromes (e.g. 151 or 753357). Additionally numbers
can of course be ordered in size. The first few palindrome
numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, ...
The number 10 is not a palindrome (even though you could write it as 010) but a zero as leading digit is not
allowed.


Input
The input consists of a series of lines with each line containing one integer value i (1<= i <= 2*10^9 ). This
integer value i indicates the index of the palindrome number that is to be written to the output, where index
1 stands for the first palindrome number (1), index 2 stands for the second palindrome number (2) and so on.
The input is terminated by a line containing 0.


Output
For each line of input (except the last one) exactly one line of output containing a single (decimal) integer
value is to be produced. For each input value i the i-th palindrome number is to be written to the output.
Sample Input
1
12
24
0

Sample Output
1
33
151



                                             Hay Points
                              Time Limit:1000MS Memory Limit:65536K
                                   Total Submit:558 Accepted:395


Description
Each employee of a bureaucracy has a job description - a few paragraphs that describe the responsibilities
of the job. The employee's job description, combined with other factors, such as seniority, is used to
determine his or her salary.
The Hay Point system frees the Human Resources department from having to make an intelligent
judgement as to the value of the employee; the job description is merely scanned for words and phrases that
indicate responsibility. In particular, job descriptions that indicate control over a large budget or
management over a large number of people yield high Hay Point scores.

You are to implement a simplified Hay Point system. You will be given a Hay Point dictionary and a
number of job descriptions. For each job description you are to compute the salary associated with the job,
according to the system.


Input
The first line of input contains 2 positive integers: m <= 1000, the number of words in the Hay Point
dictionary, and n <= 100, the number of job descriptions. m lines follow; each contains a word (a string of
up to 16 lower-case letters) and a dollar value (a integer number between 0 and 1,000,000). Following the
dictionary are the n job descriptions. Each job description consists of one or more lines of text; for your
convenience the text has been converted to lower case and has no characters other than letters, numbers, and
spaces. Each job description is terminated by a line containing a period.


Output
For each job description, output the corresponding salary computed as the sum of the Hay Point values for
all words that appear in the description. Words that do not appear in the dictionary have a value of 0.


Sample Input
7 2
administer 100000
spending 200000
manage 50000
responsibility 25000
expertise 100
skill 50
money 75000
the incumbent will administer the spending of kindergarden milk money
and exercise responsibility for making change he or she will share
responsibility for the task of managing the money with the assistant
whose skill and expertise shall ensure the successful spending exercise
.
this individual must have the skill to perform a heart transplant and
expertise in rocket science
.

Sample Output
700150
150




                                           Jogging Trails
                                Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:246 Accepted:96


Description
Gord is training for a marathon. Behind his house is a park with a large network of jogging trails connecting
water stations. Gord wants to find the shortest jogging route that travels along every trail at least once.


Input
Input consists of several test cases. The first line of input for each case contains two positive integers: n <=
15, the number of water stations, and m < 1000, the number of trails. For each trail, there is one subsequent
line of input containing three positive integers: the first two, between 1 and n, indicating the water stations
at the end points of the trail; the third indicates the length of the trail, in cubits. There may be more than one
trail between any two stations; each different trail is given only once in the input; each trail can be travelled
in either direction. It is possible to reach any trail from any other trail by visiting a sequence of water
stations connected by trails. Gord's route may start at any water station, and must end at the same station. A
single line containing 0 follows the last test case.


Output
For each case, there should be one line of output giving the length of Gord's jogging route.


Sample Input
4 5
1 2 3
2 3 4
3 4 5
1 4 10
1 3 12
0

Sample Output
41



                                             Beavergnaw
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:667 Accepted:455


Description
                                When chomping a tree the beaver cuts a
                                very specific shape out of the tree trunk.
                                What is left in the tree trunk looks like
                                two frustums of a cone joined by a
                                cylinder with the diameter the same as its
                                height. A very curious beaver tries not to
                                demolish a tree but rather sort out what
                                should be the diameter of the cylinder
                                joining the frustums such that he
                                chomped out certain amount of wood.
                                You are to help him to do the calculations.
We will consider an idealized beaver chomping an idealized tree. Let us assume that the tree trunk is a
cylinder of diameter D and that the beaver chomps on a segment of the trunk also of height D. What should
be the diameter d of the inner cylinder such that the beaver chmped out V cubic units of wood?
Input
Input contains multiple cases each presented on a separate line. Each line contains two integer numbers D
and V separated by whitespace. D is the linear units and V is in cubic units. V will not exceed the maximum
volume of wood that the beaver can chomp. A line with D=0 and V=0 follows the last case.


Output
For each case, one line of output should be produced containing one number rounded to three fractional
digits giving the value of d measured in linear units.


Sample Input
10 250
20 2500
25 7000
50 50000
0 0

Sample Output
8.054
14.775
13.115
30.901



                                            Power Strings
                                Time Limit:3000MS Memory Limit:65536K
                                     Total Submit:959 Accepted:387


Description
Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def"
then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative
integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).


Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at
least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.


Output
For each s you should print the largest n such that s = a^n for some string a.


Sample Input
abcd
aaaa
ababab
.

Sample Output
1
4
3

Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.


                                               Relatives
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:760 Accepted:257


Description
Given n, a positive integer, how many positive integers less than n are relatively prime to n? Two integers a
and b are relatively prime if there are no integers x > 1, y > 0, z > 0 such that a = xy and b = xz.


Input
There are several test cases. For each test case, standard input contains a line with n <= 1,000,000,000. A
line containing 0 follows the last case.


Output
For each test case there should be single line of output answering the question posed above.


Sample Input
7
12
0

Sample Output
6
4



                                         Anagram Groups
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:357 Accepted:89


Description
World-renowned Prof. A. N. Agram's current research deals with large anagram groups. He has just found a
new application for his theory on the distribution of characters in English language texts. Given such a text,
you are to find the largest anagram groups.

A text is a sequence of words. A word w is an anagram of a word v if and only if there is some permutation
p of character positions that takes w to v. Then, w and v are in the same anagram group. The size of an
anagram group is the number of words in that group. Find the 5 largest anagram groups.


Input
The input contains words composed of lowercase alphabetic characters, separated by whitespace(or new
line). It is terminated by EOF. You can assume there will be no more than 30000 words.


Output
Output the 5 largest anagram groups. If there are less than 5 groups, output them all. Sort the groups by
decreasing size. Break ties lexicographically by the lexicographical smallest element. For each group output,
print its size and its member words. Sort the member words lexicographically and print equal words only
once.


Sample Input
undisplayed
trace
tea
singleton
eta
eat
displayed
crate
cater
carte
caret
beta
beat
bate
ate
abet

Sample Output
Group of size 5: caret carte cater crate trace .
Group of size 4: abet bate beat beta .
Group of size 4: ate eat eta tea .
Group of size 1: displayed .
Group of size 1: singleton .



                                             Let it Bead
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:150 Accepted:76


Description
"Let it Bead" company is located upstairs at 700 Cannery Row in Monterey, CA. As you can deduce from
the company name, their business is beads. Their PR department found out that customers are interested in
buying colored bracelets. However, over 90 percent of the target audience insists that the bracelets be
unique. (Just imagine what happened if two women showed up at the same party wearing identical
bracelets!) It's a good thing that bracelets can have different lengths and need not be made of beads of one
color. Help the boss estimating maximum profit by calculating how many different bracelets can be
produced.

A bracelet is a ring-like sequence of s beads each of which can have one of c distinct colors. The ring is
closed, i.e. has no beginning or end, and has no direction. Assume an unlimited supply of beads of each
color. For different values of s and c, calculate the number of different bracelets that can be made.


Input
Every line of the input file defines a test case and contains two integers: the number of available colors c
followed by the length of the bracelets s. Input is terminated by c=s=0. Otherwise, both are positive, and,
due to technical difficulties in the bracelet-fabrication-machine, cs<=32, i.e. their product does not exceed
32.


Output
For each test case output on a single line the number of unique bracelets. The figure below shows the 8
different bracelets that can be made with 2 colors and 5 beads.
Sample Input
1 1
2 1
2 2
5 1
2 5
2 6
6 2
0 0

Sample Output
1
2
3
5
8
13
21



                                        Simple Computers
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:456 Accepted:118


Description
You are to write an interpreter for a simple computer. This computer uses a processor with a small number
of machine instructions. Furthermore, it is equipped with 32 byte of memory, one 8-bit accumulator (accu)
and a 5-bit program counter (pc). The memory contains data as well as code, which is the usual von
Neumann architecture.
The program counter holds the address of the instruction to be executed next. Each instruction has a length
of 1 byte - the highest 3 bits define the type of instruction and the lowest 5 bits define an optional operand
which is always a memory address (xxxxx). For instructions that don't need an operand the lowest 5 bits
have no meaning (-----). Here is a list of the machine instructions and their semantics:

000xxxxx   STA x    store the value of the accu into memory byte x


001xxxxx   LDA x    load the value of memory byte x into the accu


010xxxxx   BEQ x    if the value of the accu is 0 load the value x into the pc


011-----   NOP      no operation


100-----   DEC      subtract 1 from the accu
101-----     INC      add 1 to the accu


110xxxxx    JMP x     load the value x into the pc


111-----     HLT      terminate program


In the beginning, program counter and accumulator are set to 0. After fetching an instruction but before its execution, the
program counter is incremented. You can assume that programs will terminate.

Input
The input file contains several test cases. Each test case specifies the contents of the memory prior to
execution of the program. Byte 0 through 31 are given on separate lines in binary representation. A byte is
denoted by its highest-to-lowest bits. Input is terminated by EOF.


Output
For each test case, output on a line the value of the accumulator on termination in binary representation,
again highest bits first.


Sample Input
00111110
10100000
01010000
11100000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00111111
10000000
00000010
11000010
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
11111111
10001001

Sample Output
10000111



                                            Mondriaan's Dream
                                   Time Limit:3000MS Memory Limit:65536K
                                        Total Submit:167 Accepted:84


Description
Squares and rectangles fascinated the famous Dutch painter Piet Mondriaan. One night, after producing the
drawings in his 'toilet series' (where he had to use his toilet paper to draw on, for all of his paper was filled
with squares and rectangles), he dreamt of filling a large rectangle with small rectangles of width 2 and
height 1 in varying ways.




Expert as he was in this material, he saw at a glance that he'll need a computer to calculate the number of ways to fill the
large rectangle whose dimensions were integer values, as well. Help him, so that his dream won't turn into a nightmare!

Input
The input contains several test cases. Each test case is made up of two integer numbers: the height h and the
width w of the large rectangle. Input is terminated by h=w=0. Otherwise, 1<=h,w<=11.


Output
For each test case, output the number of different ways the given rectangle can be filled with small
rectangles of size 2 times 1. Assume the given large rectangle is oriented, i.e. count symmetrical tilings
multiple times.


Sample Input
1 2
1 3
1 4
2 2
2 3
2 4
2 11
4 11
0 0

Sample Output
1
0
1
2
3
5
144
51205



                                           Equidistance
                               Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:77 Accepted:34


Description
Alice and Bob haven't met for some time. Bob isn't very happy about this, so he urges Alice to finally make
time for a meeting. Let's listen to an extract from a phone call:

Alice: ... maybe we should meet on neutral territory.
Bob: I've already heard this from you --- two years ago.
Alice: I know ; I just haven't found yet a suitable place that is roughly at the same distance from both yours
and mine.
Bob: Well, the geometric place of the points that are equidistant from two given points on the surface of a
sphere (and the earth is a sphere rather than a disc) is a great circle (namely the one which intersects the
great circle through the given points orthogonally at the center of them). If you insist only on approximately
equal distances though, we get a zone of some kilometers width and about 40000 km length. Not everything
in this zone is water. Thus I think it is a feasible task to find a fitting place.
Alice: Now, if I tell you to pick any, we'll certainly land up in Honolulu.
Bob: Which is not a too bad idea. So, may I pick any ?
Alice: As long as I don't have to accept --- but I'm open to suggestions.
Bob: Honolulu ?
Alice: Is it situated on aforementioned geometric place at all ??!
Bob: Not quite ...
Nice. Now let's stop the preliminaries and come to the facts: Given two locations on the earth's surface you
can find the geometric place of all equidistant points on the surface. For another given location calculate its
distance on the surface to this geometric place. Assume that the earth is a sphere with a radius of 6378 km.


Input
The input consists of two parts: a list of locations and a list of queries.

The location list consists of up to 100 lines, one line per location. Each contains a string and two
floating-point numbers, separated by whitespace, representing the name of the location, its latitude and its
longitude. Names are unique and shorter than 30 characters and do not contain whitespace. Latitudes are
between -90 (South Pole) and 90 (North Pole) inclusive. Longitudes are between -180 and 180 inclusive
where negative numbers denote locations west of the meridian and positive numbers denote locations east
of the meridian. (The meridian passes through Greenwich, London.) The location list is terminated by a line
consisting of a single "#".

Each line in the query list contains three names of locations. You can assume the first location to be Alice's
home, the second location to be Bob's home and the third location to be a possible meeting point. The query
list is terminated by a line consisting of a single "#".


Output
For each query, output a line saying "M is x km off A/B equidistance." with M,x,A,B appropriately replaced
by the location names and the calculated distance rounded to the nearest integer.

If one of the locations in the query didn't occur in the list of locations print "?" instead of the distance.


Sample Input
Ulm              48.700 10.500
Freiburg         47.700 9.500
Philadelphia     39.883 -75.250
SanJose          37.366 -121.933
Atlanta          33      -84
Eindhoven        52      6
Orlando          28      -82
Vancouver        49      -123
Honolulu         22      -157
NorthPole        90      0
SouthPole        -90     0
#
Ulm Freiburg Philadelphia
SanJose Atlanta Eindhoven
Orlando Vancouver Honolulu
NorthPole SouthPole NorthPole
Ulm SanDiego Orlando
NorthPole SouthPole SouthPole
Ulm Honolulu SouthPole
#

Sample Output
Philadelphia is 690 km off Ulm/Freiburg equidistance.
Eindhoven is 3117 km off SanJose/Atlanta equidistance.
Honolulu is 4251 km off Orlando/Vancouver equidistance.
NorthPole is 10019 km off NorthPole/SouthPole equidistance.
Orlando is ? km off Ulm/SanDiego equidistance.
SouthPole is 10019 km off NorthPole/SouthPole equidistance.
SouthPole is 1494 km off Ulm/Honolulu equidistance.



                                             How many Fibs?
                                 Time Limit:1000MS Memory Limit:65536K
                                      Total Submit:980 Accepted:338


Description
Recall the definition of the Fibonacci numbers:

f1 := 1


f2 := 2


fn := fn-1 + fn-2    (n>=3)


Given two numbers a and b, calculate how many Fibonacci numbers are in the range [a,b].

Input
The input contains several test cases. Each test case consists of two non-negative integer numbers a and b.
Input is terminated by a=b=0. Otherwise, a<=b<=10100. The numbers a and b are given with no superfluous
leading zeros.


Output
For each test case output on a single line the number of Fibonacci numbers fi with a<=fi<=b.


Sample Input
10 100
1234567890 9876543210
0 0

Sample Output
5
4



                                Phylogenetic Trees Inherited
                                  Time Limit:3000MS Memory Limit:65536K
                                Total Submit:54 Accepted:27 Special Judged


Description
Among other things, Computational Molecular Biology deals with processing genetic sequences.
Considering the evolutionary relationship of two sequences, we can say that they are closely related if they
do not differ very much. We might represent the relationship by a tree, putting sequences from ancestors
above sequences from their descendants. Such trees are called phylogenetic trees.
Whereas one task of phylogenetics is to infer a tree from given sequences, we'll simplify things a bit and
provide a tree structure - this will be a complete binary tree. You'll be given the n leaves of the tree. Sure
you know, n is always a power of 2. Each leaf is a sequence of amino acids (designated by the
one-character-codes you can see in the figure). All sequences will be of equal length l. Your task is to
derive the sequence of a common ancestor with minimal costs.

                            Amino Acid                                     Amino Acid
                            Alanine         Ala A                          Leucine         Leu L
                            Arginine        Arg R                          Lysine          Lys K
                            Asparagine      Asn N                          Methionine      Met M
                            Aspartic Acid Asp D                            Phenylalanine Phe F
                            Cysteine        Cys C                          Proline         Pro P
                            Glutamine       Gln Q                          Serine          Ser S
                            Glutamic Acid Glu E                            Threonine       Thr T
                            Glycine         Gly G                          Tryptophan      Trp W
                            Histidine       His H                          Tyrosine        Tyr Y
                            Isoleucine      Ile I                          Valine          Val V


The costs are determined as follows: every inner node of the tree is marked with a sequence of length l, the cost of an edge
of the tree is the number of positions at which the two sequences at the ends of the edge differ, the total cost is the sum of
the costs at all edges. The sequence of a common ancestor of all sequences is then found at the root of the tree. An optimal
common ancestor is a common ancestor with minimal total costs.
Input
The input file contains several test cases. Each test case starts with two integers n and l, denoting the
number of sequences at the leaves and their length, respectively. Input is terminated by n=l=0. Otherwise,
1<=n<=1024 and 1<=l<=1000. Then follow n words of length l over the amino acid alphabet. They
represent the leaves of a complete binary tree, from left to right.


Output
For each test case, output a line containing some optimal common ancestor and the minimal total costs.


Sample Input
4 3
AAG
AAA
GGA
AGA


4 3
AAG
AGA
AAA
GGA


4 3
AAG
GGA
AAA
AGA


4 1
A
R
A
R


2 1
W
W


2 1
W
Y
1 1
Q


0 0

Sample Output
AGA 3
AGA 4
AGA 4
R 2
W 0
Y 1
Q 0



                                         Hike on a Graph
                               Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:80 Accepted:50


Description
"Hike on a Graph" is a game that is played on a board on which an undirected graph is drawn. The graph is
complete and has all loops, i.e. for any two locations there is exactly one arrow between them. The arrows
are coloured. There are three players, and each of them has a piece. At the beginning of the game, the three
pieces are in fixed locations on the graph. In turn, the players may do a move. A move consists of moving
one's own piece along an arrow to a new location on the board. The following constraint is imposed on this:
the piece may only be moved along arrows of the same colour as the arrow between the two opponents'
pieces.

In the sixties ("make love not war") a one-person variant of the game emerged. In this variant one person
moves all the three pieces, not necessarily one after the other, but of course only one at a time. Goal of this
game is to get all pieces onto the same location, using as few moves as possible. Find out the smallest
number of moves that is necessary to get all three pieces onto the same location, for a given board layout
and starting positions.


Input
The input contains several test cases. Each test case starts with the number n. Input is terminated by n=0.
Otherwise, 1<=n<=50. Then follow three integers p1, p2, p3 with 1<=pi<=n denoting the starting locations
of the game pieces. The colours of the arrows are given next as a m×m matrix of whitespace-separated
lower-case letters. The element mij denotes the colour of the arrow between the locations i and j. Since the
graph is undirected, you can assume the matrix to be symmetrical.
Output
For each test case output on a single line the minimum number of moves required to get all three pieces
onto the same location, or the word "impossible" if that is not possible for the given board and starting
locations.


Sample Input
3 1 2 3
r b r
b b b
r b r
2 1 2 2
y g
g y
0

Sample Output
2
impossible



                                         Return of the Jedi
                                 Time Limit:1000MS Memory Limit:65536K
                                       Total Submit:23 Accepted:10


Description
Luke Skywalker races through the forest on a speeder bike, trying to outrun a patrol of Imperial scouts on
Endor. A small moon near a new Death Star, Endor is covered by dense foliage and a thick forest of ancient
towering trees. The speeder bike , which Luke stole from an Imperial scout, is an antigravity vehicle
capable of speeds of 200 miles an hour. How quickly can Luke reach Princess Leia in the Ewok village?
The forest is a plane with T trees. Luke's position is specified by a pair of coordinates ( xluke , yluke ) within
the plane. The Ewok village has coordinates ( xewok , yewok ). You are to find the shortest travel time from
Luke's position to the Ewok village.


Input
The first line of input contains T, xluke , yluke xewok , yewok . T lines follow; each gives the coordinates and
diameter of a tree: xtreei , ytreei , dtreei . T is an integer not exceeding 10; coordinates and diameters are real
numbers in miles. Trees do not intersect or touch one another.
Output
Output is a single real number, to two decimal places, giving the minimum travel time in seconds.


Sample Input
2 0.0 0.0 10.0 0.0
4.0 0.0 1.0
6.0 0.0 1.0

Sample Output
181.13



                                         Discrete Logging
                                Time Limit:5000MS Memory Limit:65536K
                                      Total Submit:81 Accepted:31


Description
Given a prime P, 2 <= P < 231, an integer B, 2 <= B < P, and an integer N, 2 <= N < P, compute the discrete
logarithm of N, base B, modulo P. That is, find an integer L such that
        L
    B == N (mod P)

Input
Read several lines of input, each containing P,B,N separated by a space.


Output
For each line print the logarithm on a separate line. If there are several, print the smallest; if there is none,
print "no solution".


Sample Input
5 2 1
5 2 2
5 2 3
5 2 4
5 3 1
5 3 2
5 3 3
5 3 4
5 4 1
5 4 2
5 4 3
5 4 4
12345701 2 1111111
1111111121 65537 1111111111

Sample Output
0
1
3
2
0
3
1
2
0
no solution
no solution
1
9584351
462803587

Hint
The solution to this problem requires a well known result in number theory that is probably expected of you
for Putnam but not ACM competitions. It is Fermat's theorem that states
        (P-1)
    B           == 1 (mod P)


for any prime P and some other (fairly rare) numbers known as base-B pseudoprimes. A rarer subset of the base-B
pseudoprimes, known as Carmichael numbers, are pseudoprimes for every base between 2 and P-1. A corollary to Fermat's
theorem is that for any m
        (-m)           (P-1-m)
    B           == B             (mod P) .



                                                    Hardwood Species
                                             Time Limit:10000MS Memory Limit:65536K
                                                  Total Submit:734 Accepted:239


Description
Hardwoods are the botanical group of trees that have broad leaves, produce a fruit or nut, and generally go
dormant in the winter.
America's temperate climates produce forests with hundreds of hardwood species -- trees that share certain
biological characteristics. Although oak, maple and cherry all are types of hardwood trees, for example,
they are different species. Together, all the hardwood species represent 40 percent of the trees in the United
States.

On the other hand, softwoods, or conifers, from the Latin word meaning "cone-bearing," have needles.
Widely available US softwoods include cedar, fir, hemlock, pine, redwood, spruce and cypress. In a home,
the softwoods are used primarily as structural lumber such as 2x4s and 2x6s, with some limited decorative
applications.

Using satellite imaging technology, the Department of Natural Resources has compiled an inventory of
every tree standing on a particular day. You are to compute the total fraction of the tree population
represented by each species.


Input
Input to your program consists of a list of the species of every tree observed by the satellite; one tree per
line. No species name exceeds 30 characters. There are no more than 10,000 species and no more than
1,000,000 trees.


Output
Print the name of each species represented in the population, in alphabetical order, followed by the
percentage of the population it represents, to 4 decimal places.


Sample Input
Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow

Sample Output
Ash 13.7931
Aspen 3.4483
Basswood 3.4483
Beech 3.4483
Black Walnut 3.4483
Cherry 3.4483
Cottonwood 3.4483
Cypress 3.4483
Gum 3.4483
Hackberry 3.4483
Hard Maple 3.4483
Hickory 3.4483
Pecan 3.4483
Poplan 3.4483
Red Alder 3.4483
Red Elm 3.4483
Red Oak 6.8966
Sassafras 3.4483
Soft Maple 3.4483
Sycamore 3.4483
White Oak 10.3448
Willow 3.4483
Yellow Birch 3.4483

Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceeded.


                                               Forests
                              Time Limit:1000MS Memory Limit:65536K
                                  Total Submit:1129 Accepted:372
Description
If a tree falls in the forest, and there's nobody there to hear, does it make a sound? This classic conundrum
was coined by George Berkeley (1685-1753), the Bishop and influential Irish philosopher whose primary
philosophical achievement is the advancement of what has come to be called subjective idealism. He wrote
a number of works, of which the most widely-read are Treatise Concerning the Principles of Human
Knowledge (1710) and Three Dialogues between Hylas and Philonous (1713) (Philonous, the "lover of the
mind," representing Berkeley himself).


Input
A forest contains T trees numbered from 1 to T and P people numbered from 1 to P. Standard input consists
of a line containing P and T followed by several lines, containing a pair of integers i and j, indicating that
person i has heard tree j fall.


Output
People may have different opinions as to which trees, according to Berkeley, have made a sound. Output
how many different opinions are represented in the input? Two people hold the same opinion only if they
hear exactly the same set of trees. You may assume that P < 100 and T < 100.


Sample Input
3 4
1 2
3 3
1 3
2 2
3 2
2 4

Sample Output
2



                                      A Star not a Tree?
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:171 Accepted:76


Description
Luke wants to upgrade his home computer network from 10mbs to 100mbs. His existing network uses
10base2 (coaxial) cables that allow you to connect any number of computers together in a linear
arrangement. Luke is particulary proud that he solved a nasty NP-complete problem in order to minimize
the total cable length.
Unfortunately, Luke cannot use his existing cabling. The 100mbs system uses 100baseT (twisted pair)
cables. Each 100baseT cable connects only two devices: either two network cards or a network card and a
hub. (A hub is an electronic device that interconnects several cables.) Luke has a choice: He can buy 2N-2
network cards and connect his N computers together by inserting one or more cards into each computer and
connecting them all together. Or he can buy N network cards and a hub and connect each of his N
computers to the hub. The first approach would require that Luke configure his operating system to forward
network traffic. However, with the installation of Winux 2007.2, Luke discovered that network forwarding
no longer worked. He couldn't figure out how to re-enable forwarding, and he had never heard of Prim or
Kruskal, so he settled on the second approach: N network cards and a hub.

Luke lives in a loft and so is prepared to run the cables and place the hub anywhere. But he won't move his
computers. He wants to minimize the total length of cable he must buy.


Input
The first line of input contains a positive integer N <= 100, the number of computers. N lines follow; each
gives the (x,y) coordinates (in mm.) of a computer within the room. All coordinates are integers between 0
and 10,000.


Output
Output consists of one number, the total length of the cable segments, rounded to the nearest mm.


Sample Input
4
0 0
0 10000
10000 10000
10000 0

Sample Output
28284



                                     Constructing Roads
                              Time Limit:2000MS Memory Limit:65536K
                                  Total Submit:1126 Accepted:294
Description
There are N villages, which are numbered from 1 to N, and you should build some roads such that every
two villages can connect to each other. We say two village A and B are connected, if and only if there is a
road between A and B, or there exists a village C such that there is a road between A and C, and C and B
are connected.

We know that there are already some roads between some villages and your job is the build some roads
such that all the villages are connect and the length of all the roads built is minimum.


Input
The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th
of which contains N integers, and the j-th of these N integers is the distance (the distance should be an
integer within [1, 1000]) between village i and village j.

Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a
and b (1 <= a < b <= N), which means the road between village a and village b has been built.


Output
You should output a line contains an integer, which is the length of all the roads to be built such that all the
villages are connected, and this value is minimum.


Sample Input
3
0 990 692
990 0 179
692 179 0
1
1 2

Sample Output
179



                                 The Wolves and the Sheep
                               Time Limit:15000MS Memory Limit:65536K
                                     Total Submit:170 Accepted:26


Description
Nalim, Ocis and Remmarguts are playing on grass, and they feel very hungry now. As baby wolves, they
decide to capture a little sheep to eat. Fortunately, they immediately discover a sheep roaming around the
grass. However, what they found is the queen of the sheep ---- Mmxl, who has extraordinary speed that can
compare with the wolves, and is very clever! Can you judge whether the baby wolves will capture Mmxl!

There are some rules to follow:
The grass field is a rectangular area that consist of R * C grids. And some obstacles like stones or trees exist.
The actions of the baby wolves and Mmxl are taken in rounds. In each round, baby wolves take actions first,
and then Mmxl follows. In the baby wolves' turn, the three wolves will make a decision, and choose one of
them to move (a move means moving from a grid to a neighboring grid). There must be a wolf to move,
unless none of them can move. In the Mmxl's turn, she will always move. If she cannot move, she is
captured. Baby wolves and Mmxl cannot move to the grids on which there are obstacles, and they are
always on different grids. Baby wolves will never get out of the rectangular area. Once Mmxl gets away
from the grass, she is never captured.

You should notice that the only situation that Mmxl is captured is that she cannot move, but is not that in
wolves' turn, some wolf is in the neighboring grid of Mmxl's.


Input
Input contains multiple test cases. Each test case starts with two numbers R and C (1 <= R, C <= 10) in one
line. Then R lines follow, each line has C characters, which describes the grass field. A '.' denotes an empty
grid, an 'X' denotes an obstacle, a 'W' denotes a baby wolf, and a 'S' denotes the Mmxl. There are exactly
three 'W' and one 'S'. Every test case will be followed by a blank line.


Output
There is only one line for each test case. If lovely Mmxl will not be captured in finity rounds, print "Lucky
Mmxl is safe:)". If the wicked baby wolves are able to capture Mmxl, print "Poor Mmxl is in danger:(".


Sample Input
3 5
XXW.X
XWSWX
XXX.X


4 5
XXWXX
XWSWX
XX.XX
XX.XX


7 6
XXXXXX
XWWW.X
X....X
X....X
X....X
X...SX
XXXXXX


7 7
XXXXXXX
XWWW..X
X.....X
X..X..X
X.....X
X....SX
XXXXXXX


7 7
XXXXXXX
XWWW..X
X.....X
X..XX.X
X.....X
X....SX
XXXXXXX


10 10
WWW.......
..........
..........
..........
..........
.....S....
..........
..........
..........
..........


9 9
XXXXXXXXX
X...X...X
XW.....WX
X.X...X.X
X..X.X..X
X...S...X
XXXXXXXXX
XWXXXXXXX
XXXXXXXXX


9 9
XXXXXXXXX
X.......X
XW.....WX
X.X...X.X
X..X.X..X
X...S...X
XXXXXXXXX
XWXXXXXXX
XXXXXXXXX


9 9
XXXXXXXXX
....X....
XW.....WX
X.X...X.X
X..X.X..X
X...S...X
XXXXXXXXX
XWXXXXXXX
XXXXXXXXX


3 3
WX.
XSX
WXW



Sample Output
Lucky Mmxl is safe:)
Lucky Mmxl is safe:)
Poor Mmxl is in danger:(
Lucky Mmxl is safe:)
Poor Mmxl is in danger:(
Lucky Mmxl is safe:)
Poor Mmxl is in danger:(
Lucky Mmxl is safe:)
Lucky Mmxl is safe:)
Poor Mmxl is in danger:(



                           The Parallel Challenge Ballgame
                                    Time Limit:1000MS Memory Limit:65536K
                                          Total Submit:59 Accepted:19


Description
Before the ACM/ICPC world final 2005, there is a competition called "The Parallel Challenge Ballgame".
The Parallel Challenge ballgame gives each team a chance to pit their programming skills against those of
other teams in a fast-moving parallel-programming game of skill, treachery, and hazard avoidance. Each
team will write a single C++ class named MyPlayer which defines the characteristics of a "player". The
MyPlayer class will be instantiated five times in the environment, making up a five-player team, which will
then compete in a series of Parallel Challenge ballgames running on an IBM Power Architecture Blue Gene
supercomputer – the world’s fastest computer.

A Parallel Challenge ballgame is played on a rectangular filed. The filed is surrounded by a wall; balls will
bounce off the walls if they run into it. The rule of bouncing is the same as light (In figure 1,angle 1 equals
angle 2). Near the edges of the fields are a number of goals where points can be scored. Goals are
rectangular areas lying near the edges of the field but within the field boundaries. When the game starts
there are a number of balls placed at random locations on the field. A player can move to a ball, pick it up,
and throw (of course, it is not football, why not use hand?) it. At the start of each game there are also a
number of "nets" distributed at various locations on the edges of the field. A player can move to and pick up
one of these nets, and can then use them to "trap" players on other teams by throwing the net on top of them.
Once a player is trapped beneath a net, that player cannot do anything more in the game until a teammate
comes and lifts the net from the trapped player. A player may "tackle" another player, normally in an
attempt to dislodge a ball being carried by the other player (although it is also legal to tackle a player who is
not carrying a ball).




The objective of each team is to write their MyPlayer class so that their players (the five instances of the class) operate in a
coordinated fashion, taking advantage of the various ways to score points while at the same time avoiding both hazards on
the game filed and impediments thrown at them by players from other teams. The winner of a game is the team whose
players score the largest total number of points.

        There are many ways to score points:
        (1) Successful Tackle (tackle not caught by Referees)
        (2) Opponent’s Failed Tackle
        (3) Throwing a net on one or more opponents
        (4) Lifting a net off a teammate
And of course, the normal approach: (5) Carry or throw the balls into goals. This is also the easiest way to score points. In
order to get more chance to make a ball into the goal, it is better to throw a ball to a goal once you get it. The ball may be
blocked by other player, but the probability is low, because a thrown ball moves at the maximum speed allowed in the
game, and the player can not catch up with it. So the only way it is blocked is that some player is just on the direction,
which the ball moves. And because the ball will bounce off the wall when it hits the wall, it is not necessary to throw a ball
straight to a goal (see figure 2). But the more times the ball bounces off the wall, the higher probability that other player
will head off it. So we only consider the ball bounces off the wall no more than once.




Here is our problem. Given the range of the field, the position of the ball and the goals, the size of the goals, your task is to
calculate how many percents of the direction that the team can score points through method (5).

Input
In the first line of input, there is an integer t, which is the number of test cases and followed by the data for
the test cases. The first line of each test case contains four integers: x1, y1, x2, y2, and (x1, y1) and (x2, y2)
(-1000 <= x1, y1, x2, y2 <= 1000) are the coordinates of the diagonally points of the field. In the next line,
there are two integers x and y, and (x, y) is the coordinate of the ball. The third line of each test case
contains an integer n (0 <= n <= 100), which is the number of the goals. In next n lines, each line contains
four integers: xi1, yi1, xi2, yi2, and (xi1, yi1) and (xi2, yi2) are the coordinates of the diagonally points of
the i-th goal. You may assume the goals and the ball are inside the field. And if a ball move into or on the
boundaries of a goal, the team scores points.


Output
The output contains one line per test case containing a number, which is described above and followed a
"%". The number should be rounded up to two decimal digits. See the Sample Output to know the exact
format.


Sample Input
1
100 100 -100 -100
0 0
1
10 10 -10 20

Sample Output
28.34%



                                         Flo's Restaurant
                                Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:497 Accepted:143


Description
Sick and tired of pushing paper in the dreary bleary-eyed world of finance, Flo ditched her desk job and
built her own restaurant.

In the small restaurant, there are several two-seat tables, four-seat tables and six-seat tables. A single diner
or a group of two diners should be arranged to a two-seat table, a group of three or four diners should be
arranged to a four-seat table, and a group of five or six diners should be arranged to a six-seat table.

Flo's restaurant serves delicious food, and many people like to eat here. Every day when lunch time comes,
the restaurant is usually full of diners. If there is no suitable table for a new coming group of diners, they
have to wait until some suitable table is free and there isn't an earlier arrival group waiting for the same kind
of tables. Kind Flo will tell them how long they will get their seat, and if it's longer than half an hour, they
will leave for another restaurant.

Now given the list of coming diners in a day, please calculate how many diners take their food in Flo's
restaurant. You may assume it takes half an hour for every diner from taking a seat to leaving the restaurant.


Input
There are several test cases. The first line of each case contains there positive integers separated by blanks,
A, B and C (A, B, C >0, A + B + C <= 100), which are the number of two-seat tables, the number of
four-seat tables and the number of six-seat tables respectively. From the second line, there is a list of
coming groups of diners, each line of which contains two integers, T and N (0 < N <= 6), representing the
arrival time and the number of diners of each group. The arrival time T is denoted by HH:MM, and fixed
between 08:00 and 22:00 (the restaurant closes at 23:00). The list is sorted by the arrival time of each group
in an ascending order, and you may assume that no groups arrive at the same time. Each test case is ended
by a line of "#".

A test case with A = B = C = 0 ends the input, and should not be processed.
Output
For each test case, you should output an integer, the total number of diners who take their food in Flo's
restaurant, in a separated line.


Sample Input
1 1 1
10:40 1
10:50 2
11:00 4
#
1 1 1
10:40 1
10:50 2
11:00 2
#
1 2 1
10:30 1
10:40 3
10:50 2
11:00 1
11:20 5
#
0 0 0

Sample Output
7
3
12



                                            A Chess Game
                               Time Limit:3000MS Memory Limit:65536K
                                    Total Submit:222 Accepted:83


Description
Let's design a new chess game. There are N positions to hold M chesses in this game. Multiple chesses can
be located in the same position. The positions are constituted as a topological graph, i.e. there are directed
edges connecting some positions, and no cycle exists. Two players you and I move chesses alternately. In
each turn the player should move only one chess from the current position to one of its out-positions along
an edge. The game does not end, until one of the players cannot move chess any more. If you cannot move
any chess in your turn, you lose. Otherwise, if the misfortune falls on me... I will disturb the chesses and
play it again.

Do you want to challenge me? Just write your program to show your qualification!


Input
Input contains multiple test cases. Each test case starts with a number N (1 <= N <= 1000) in one line. Then
the following N lines describe the out-positions of each position. Each line starts with an integer Xi that is
the number of out-positions for the position i. Then Xi integers following specify the out-positions.
Positions are indexed from 0 to N-1. Then multiple queries follow. Each query occupies only one line. The
line starts with a number M (1 <= M <= 10), and then come M integers, which are the initial positions of
chesses. A line with number 0 ends the test case.


Output
There is one line for each query, which contains a string "WIN" or "LOSE". "WIN" means that the player
taking the first turn can win the game according to a clever strategy; otherwise "LOSE" should be printed.


Sample Input
4
2 1 2
0
1 3
0
1 0
2 0 2
0


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

Sample Output
WIN
WIN
WIN
LOSE
WIN
Hint
Huge input,scanf is recommended.


                                                Remainder
                                Time Limit:3000MS Memory Limit:65536K
                                     Total Submit:575 Accepted:80


Description
Coco is a clever boy, who is good at mathematics. However, he is puzzled by a difficult mathematics
problem. The problem is: Given three integers N, K and M, N may adds ('+') M, subtract ('-') M, multiples
('*') M or modulus ('%') M (The definition of '%' is given below), and the result will be restored in N.
Continue the process above, can you make a situation that "[(the initial value of N) + 1] % K" is equal to
"(the current value of N) % K"? If you can, find the minimum steps and what you should do in each step.
Please help poor Coco to solve this problem.

You should know that if a = b * q + r (q > 0 and 0 <= r < q), then we have a % q = r.


Input
There are multiple cases. Each case contains three integers N, K and M (-1000 <= N <= 1000, 1 < K <=
1000, 0 < M <= 1000) in a single line.

The input is terminated with three 0s. This test case is not to be processed.


Output
For each case, if there is no solution, just print 0. Otherwise, on the first line of the output print the
minimum number of steps to make "[(the initial value of N) + 1] % K" is equal to "(the final value of N) %
K". The second line print the operations to do in each step, which consist of '+', '-', '*' and '%'. If there are
more than one solution, print the minimum one. (Here we define '+' < '-' < '*' < '%'. And if A = a1a2...ak and
B = b1b2...bk are both solutions, we say A < B, if and only if there exists a P such that for i = 1, ..., P-1, ai =
bi, and for i = P, ai < bi)


Sample Input
2 2 2
-1 12 10
0 0 0

Sample Output
0
2
*+



                                             Smith's Problem
                                 Time Limit:5000MS Memory Limit:65536K
                               Total Submit:74 Accepted:25 Special Judged


Description
Computer has greatly released scientists from heavy calculation. Before computer is invented, calculation
must be done by hand, which is boring and easy to make mistake. But now, with the help of computer much
calculation can be finished within a second.

But one day Professor Smith met a strange problem. He had tried to find the positive solutions of the
equation with the following form:

                                                  X ^ 2 – N * Y ^ 2 = 1,

in which N is a positive integer. But for many values of N, his poor computer seems cannot find an answer!

"That's strange!" said Professor Smith "There must be something wrong with my program!" And you, the assistant of
Professor Smith, are assigned the work to solve the problem.

Input
The input will contain several test cases; each contains a positive integer N (1 <= N <= 10 ^ 8) in a single
line.


Output
For each test case, in a line output two positive integers X and Y that satisfy the equation and are smaller
than 10 ^ 1000. If there is no such solution, output "No solution!"


Sample Input
52
256
991

Sample Output
649 90
No solution!
379516400906811930638014896080 12055735790331359447442538767



                                      Surface Reconstruction
                                   Time Limit:3000MS Memory Limit:65536K
                                         Total Submit:93 Accepted:38


Description
(3-D) medical imaging devices, such as CT and MRI, typically produce images as a set of slices. From
these slices of images we can reconstruct the surface of the object. People have done much research on this
field, and a classical method to simplify the problem is to just consider the surface reconstruction problem
between two adjacent slices.




We describe the problem as: given two simple polygons (a simple polygon is a polygon from which we cannot find two
boundaries which are intersectant and not adjacent) in two parallel plane, then we can connect segments between the points
from different polygons, and form some triangles; these triangles may construct a close side surface of two polygons (as
show in the figure above). We can easily find that the triangles must obey the following properties: a boundary of the
polygons must belong to one and just one triangle; a triangle must include one and just one boundary of the polygons.

For two simple polygons that are given in two parallel planes, there are a lot of ways to connect the segments, and different
ways may look different. There is also much research in this problem, but to make it simple, your job is just to calculate a
way of connecting such that the area of the side surface is minimum.
Input
The first line contains an integer P (3 <= P <= 100), which is the number of points in the first polygon. The
second line contains P pairs of integers, which give the coordinates of the P points in turn.

The third line contains an integer Q (3 <= Q <= 100), which is the number of points in the second polygon.
The fourth line contains Q pairs of integers, which give the coordinates of the Q points in turn.

It is known that the distance between two planes is 10, and all the coordinates given above are in the range
of [0, 2500].


Output
The output contains only one line, which gives the minimum area of the close side surface. The result
should be round to an integer.


Sample Input
3
0 0 2500 0 0 2500
4
0 0 0 2500 2500 2500 2500 0

Sample Output
3200050



                                      GCD & LCM Inverse
                               Time Limit:2000MS Memory Limit:65536K
                                    Total Submit:711 Accepted:118


Description
Given two positive integers a and b, we can easily calculate the greatest common divisor (GCD) and the
least common multiple (LCM) of a and b. But what about the inverse? That is: given GCD and LCM,
finding a and b.


Input
The input contains multiple test cases, each of which contains two positive integers, the GCD and the LCM.
You can assume that these two numbers are both less than 2^63.
Output
For each test case, output a and b in ascending order. If there are multiple solutions, output the pair with
smallest a + b.


Sample Input
3 60

Sample Output
12 15



                                                     Lazy Cows
                                  Time Limit:1000MS Memory Limit:65536K
                                       Total Submit:294 Accepted:91


Description
Farmer John regrets having applied high-grade fertilizer to his pastures since the grass now grows so
quickly that his cows no longer need to move around when they graze. As a result, the cows have grown
quite large and lazy... and winter is approaching.

Farmer John wants to build a set of barns to provide shelter for his immobile cows and believes that he
needs to build his barns around the cows based on their current locations since they won't walk to a barn, no
matter how close or comfortable.

The cows' grazing pasture is represented by a 2 x B (1 <= B <= 15,000,000) array of cells, some of which
contain a cow and some of which are empty. N (1 <= N <= 1000) cows occupy the cells in this pasture:

-------------------------------------------------------


|       | cow |      |      |      | cow | cow | cow | cow |


-------------------------------------------------------


|       | cow | cow | cow |        |      |      |       |      |


-------------------------------------------------------


Ever the frugal agrarian, Farmer John would like to build a set of just K (1 <= K <= N) rectangular barns (oriented with
walls parallel to the pasture's edges) whose total area covers the minimum possible number of cells. Each barn covers a
rectangular group of cells in their entirety, and no two barns may overlap. Of course, the barns must cover all of the cells
containing cows.
By way of example, in the picture above if K=2 then the optimal solution contains a 2x3 barn and a 1x4 barn and covers a
total of 10 units of area.

Input
* Line 1: Three space-separated integers, N, K, and B.

* Lines 2..N+1: Two space-separated integers in the range (1,1) to (2,B) giving the coordinates of the cell
containing each cow. No cell contains more than one cow.


Output
* Line 1: The minimum area required by the K barns in order to cover all of the cows.


Sample Input
8 2 9
1 2
1 6
1 7
1 8
1 9
2 2
2 3
2 4

Sample Output
10



                                                 Expedition
                                 Time Limit:1000MS Memory Limit:65536K
                                      Total Submit:497 Accepted:174


Description
A group of cows grabbed a truck and ventured on an expedition deep into the jungle. Being rather poor
drivers, the cows unfortunately managed to run over a rock and puncture the truck's fuel tank. The truck
now leaks one unit of fuel every unit of distance it travels.

To repair the truck, the cows need to drive to the nearest town (no more than 1,000,000 units distant) down
a long, winding road. On this road, between the town and the current location of the truck, there are N (1 <=
N <= 10,000) fuel stops where the cows can stop to acquire additional fuel (1..100 units at each stop).
The jungle is a dangerous place for humans and is especially dangerous for cows. Therefore, the cows want
to make the minimum possible number of stops for fuel on the way to the town. Fortunately, the capacity of
the fuel tank on their truck is so large that there is effectively no limit to the amount of fuel it can hold. The
truck is currently L units away from the town and has P units of fuel (1 <= P <= 1,000,000).

Determine the minimum number of stops needed to reach the town, or if the cows cannot reach the town at
all.


Input
* Line 1: A single integer, N

* Lines 2..N+1: Each line contains two space-separated integers describing a fuel stop: The first integer is
the distance from the town to the stop; the second is the amount of fuel available at that stop.

* Line N+2: Two space-separated integers, L and P


Output
* Line 1: A single integer giving the minimum number of fuel stops necessary to reach the town. If it is not
possible to reach the town, output -1.


Sample Input
4
4 4
5 2
11 5
15 10
25 10

Sample Output
2

Hint
INPUT DETAILS:

The truck is 25 units away from the town; the truck has 10 units of fuel. Along the road, there are 4 fuel
stops at distances 4, 5, 11, and 15 from the town (so these are initially at distances 21, 20, 14, and 10 from
the truck). These fuel stops can supply up to 4, 2, 5, and 10 units of fuel, respectively.

OUTPUT DETAILS:
Drive 10 units, stop to acquire 10 more units of fuel, drive 4 more units, stop to acquire 5 more units of fuel,
then drive to the town.


                                        Around the world
                               Time Limit:2000MS Memory Limit:65536K
                                    Total Submit:187 Accepted:48


Description
Over the years, FJ has made a huge number of farmer friends all around the world. Since he hasn't visited
'Farmer Ted' from England and 'Boer Harms' from Holland for a while, he'd like to visit them.

He knows the longitude of the farm where each of his worldwide friends resides. This longitude is an angle
(an integer in the range 0..359) describing the farm's location on the Earth, which we will consider to be a
circle instead of the more complex and traditional spherical representation. Except for the obvious
discontinuity, longitudes increase when traveling clockwise on this circle.

FJ plans to travel by airplane to visit his N (1 <= N <= 5,000) friends (whose farms are uniquely numbered
1..N). He knows the schedules for M (1 <= M <= 25,000) bidirectional flights connecting the different
farms. Airplanes always travel shortest paths on the Earth's surface (i.e., on the shortest arc of a circle).

There will always be a unique shortest path between two farms that are directly connected. No pair of
antipodal farms (exactly opposite each other on the circle) is ever directly connected.

Each airplane flight can be described as traveling in clockwise or counterclockwise direction around the
Earth's surface. For example, a flight from longitude 30 to longitude 35 would be clockwise, as would be a
flight from longitude 350 to longitude 10. However, a flight from longitude 350 to longitude 200 follows a
shortest path counterclockwise around the circle.

FJ would find it very cool if he could make a trip around the world, visiting some of his friends along the
way. He'd like to know if this is possible and if so, what is the minimum number of flights he can take to do
so.

He wants to start and finish his journey at the location of his best friend (the one listed first in the input
below). In order to make sure he actually circles the Earth, he wants to ensure that the clockwise distance he
travels is different from the counterclockwise distance he travels.


Input
* Line 1: Two space-separated integers: N and M

* Lines 2..N+1: Line i+1 contains one integer: the longitude of the i-th farm. Line 2 contains the location of
the farm of his best friend.
* Lines N+2..N+M+1: Line i+N+1 contains two integers giving the indices of two farms that are connected
by a flight.


Output
* Line 1: A single integer specifying the minimum number of flights FJ needs to visit to make a trip around
the world. Every time FJ moves from one farm to another counts as one flight. If it is impossible to make
such a trip, output the integer -1.


Sample Input
3 3
0
120
240
1 2
2 3
1 3

Sample Output
3

Hint
INPUT DETAILS:

Farmer John has three friends at longitudes 0, 120, and 240. There are three flights: 0<->120, 120<->240,
and 0<->240. The journey must start and finish at longitude 0.

OUTPUT DETAILS:

FJ must visit all 3 friends to make a full trip around the world.


                                             Landscaping
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:143 Accepted:52


Description
Farmer John is making the difficult transition from raising mountain goats to raising cows. His farm, while
ideal for mountain goats, is far too mountainous for cattle and thus needs to be flattened out a bit. Since
flattening is an expensive operation, he wants to remove the smallest amount of earth possible.
The farm is long and narrow and is described in a sort of two-dimensional profile by a single array of N (1
<= N <= 1000) integer elevations (range 1..1,000,000) like this:

1 2 3 3 3 2 1 3 2 2 1 2,


which represents the farm's elevations in profile, depicted below with asterisks indicating the heights:
    * * *        *


  * * * * *      * * *    *


* * * * * * * * * * * *


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


A contiguous range of one or more equal elevations in this array is a "peak" if both the left and right hand sides of the range
are either the boundary of the array or an element that is lower in elevation than the peak. The example above has three
peaks.

Determine the minimum volume of earth (each unit elevation reduction counts as one unit of volume) that must be removed
so that the resulting landscape has no more than K (1 <= K <= 25) peaks. Note well that elevations can be reduced but can
never be increased.

If the example above is to be reduced to 1 peak, the optimal solution is to remove 2 + 1 + 1 + 1 = 5 units of earth to obtain
this set of elevations:
    * * *        -


  * * * * *      - - -    -


* * * * * * * * * * * *


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


where '-'s indicate removed earth.

Input
* Line 1: Two space-separated integers: N and K

* Lines 2..N+1: Each line contains a single integer elevation. Line i+1 contains the elevation for index i.


Output
* Line 1: The minimum volume of earth that must be removed to reduce the number of peaks to K.
Sample Input
12 1
1
2
3
3
3
2
1
3
2
2
1
2

Sample Output
5



                                                        Waves
                                   Time Limit:1000MS Memory Limit:65536K
                                         Total Submit:64 Accepted:18


Description
Farmer John's cows thoroughly enjoy throwing pebbles into the lake next to their grazing field. When a
pebble hits the surface of the lake, it generates a wave that propagates across the surface of the lake.

The surface of the lake is represented by a large grid of squares. The water at each square is at some depth,
which is determined by the interaction of the waves. Before any pebbles are dropped, every square (except
those on the original river banks) has a depth of 0. When displayed, each square will be represented as
follows:

        o Square has a depth < 0
        - Square has a depth = 0
        * Square has a depth > 0
        X Square is part of the original river bank



When a pebble in dropped into the lake it causes a wave of raised water to spread out in a diamond pattern that grows every
second. The depth of each square in the diamond is increased by 1 for just one single second. This wave is followed two
seconds later by a wave of lowered water (depth decreased by 1) which also spreads out as a diamond. Each pebble causes
only two waves, the raised wave followed by the lowered wave.
For example, the diagram below shows the effect of a pebble dropped in the middle of the lake at time intervals of 0, 1, 2
and 3 seconds:
after it is dropped:
0 seconds     1 second      2 seconds     3 seconds


 -------       -------       -------        ---*---


 -------       -------       ---*---        --*-*--


 -------       ---*---       --*-*--        -*-o-*-


 ---*---       --*-*--       -*-o-*-        *-o-o-*


 -------       ---*---       --*-*--        -*-o-*-


 -------       -------       ---*---        --*-*--


 -------       -------       -------        ---*---


The river banks have fixed x co-ordinates and run for the entire length (top to bottom) of the lake with a width of a single
square. When a wave reaches a river bank, rather than carrying on, it continues to grow but the part that hits the bank is
reflected.

The early seconds of a wave hitting one of the river banks are shown below. To make the picture clearer, the second wave
of lowered water is not shown:
1 second      2 seconds     3 seconds     4 seconds      5 seconds


 X------       X------       X--*---        X-*-*--       X*---*-


 X------       X--*---       X-*-*--        X*---*-       X*----*


 X--*---       X-*-*--       X*---*-        X*----*       X-*----


 X-*-*--       X*---*-       X*----*        X-*----       X--*---


 X--*---       X-*-*--       X*---*-        X*----*       X-*----


 X------       X--*---       X-*-*--        X*---*-       X*----*


 X------       X------       X--*---        X-*-*--       X*---*-


When sections of waves meet they have no effect on the way each other propagates. In other words, at the next clock tick
the waves will grow as though there was no encounter. Note however that their effects are combined on the lake. For
example:
 1 second        2 seconds        3 seconds        4 seconds
 ---------        ---------       ---------       ---*-----


 ---------        ---------       ---*-----       --*-*-*--


 ---------        ---*-----       --*-*-*--       -*-o-*-*-


 ---*-----        --*-*-*--       -*-o-*-*-       *-o-----*


 --*-*-*--        -*-o-*-*-       *-o-----*       -o-*-o---


 ---*-----        --*-*-*--       -*-o-*-*-       *-o-----*


 ---------        ---*-----       --*-*-*--       -*-o-*-*-


 ---------        ---------       ---*-----       --*-*-*--


 ---------        ---------       ---------       ---*-----


Write a program to help the cows figure out how the waves will spread out over time.

Input
* Line 1: Four space-separated integers: P, B1, B2, and R:

         * P (1 <= P <= 5) indicates the number of pebbles,
         * B1 (-500,000 <= B1 <= 500,000) and B2 (-500,000 <= B2 <= 500,000) are the x co-ordinates of two
         river banks, and
         * R (1 <= R <= 500,000) the time at which you are to display the lake.
         No two pebbles will be dropped at the same position at the same time. The two banks will have different x
         co-ordinates, and no pebble will be dropped on a bank.



* Lines 2..P+1: Each line contains three space-separated integers that describe a pebble: X (-500,000 <= X <= 500,000), Y
(-500,000 <= Y <= 500,000), and and T (1 <= T <= 500,000)
* X and Y are the coordinates where a pebble is dropped
* T is the time at which the pebble is dropped

Output
* Lines 1..9: The output contains a 9 x 9 grid, centered on 0,0. The bottom left of the grid represents (-4, -4)
and the top right represents (4,4). The grid should represent the state of the lake at time R.


Sample Input
2 4 100 4
-3 0 1
0 0 2

Sample Output
--------X
-*------X
*-*-*---X
-o-*-*--X
o-----*-X
-o-*-*--X
*-*-*---X
-*------X
--------X



                                         Navigating the City
                                  Time Limit:1000MS Memory Limit:65536K
                                        Total Submit:95 Accepted:43


Description
A dip in the milk market has forced the cows to move to the city. The only employment available is in the
venerable field of taxi-driving. Help the cows learn their way around the city.

Given a city map with E (1 <= E <= 40) east/west street locations and N (1 <= N <= 30) north/south street
locations, create instructions for a taxi driver to navigate from the start of his route (marked 'S') to the end
(marked 'E'). Each instruction is a direction (one of 'N', 'E', 'S', or 'W') followed by a space followed by an
integer that tells how many blocks to drive in that direction. If multiple routes are available, your program
should output the shortest route. The shortest route is guaranteed to exist and be unique.

The map is depicted as a grid of '+'s that represent intersections and a set of roads depicted as '-' and '|'.
Buildings and other obstacles are shown as '.'s. Here is a typical map:

+-+-+.+-+-+


|...|.....|


+-+.+-+-+-+


..|.......|


S-+-+-+.E-+


The taxi should go east, north, west, north, east two blocks, and so on. See the output format and sample solution below for
its complete route.
Input
* Line 1: Two space-separated integers, N and E.

* Lines 2..2*N: These lines each contain 2*E-1 characters and encode the map of the street. Every other
input line gives the data for the east/west streets; the remaining lines show the north/south streets. The
format should be clear from the example.


Output
* Lines 1..?: Each line contains a direction letter and a number of blocks to travel in that direction.


Sample Input
3 6
+-+-+.+-+-+
|...|.....|
+-+.+-+-+-+
..|.......|
S-+-+-+.E-+

Sample Output
E 1
N 1
W 1
N 1
E 2
S 1
E 3
S 1
W 1



                                      Disease Manangement
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:322 Accepted:165


Description
Alas! A set of D (1 <= D <= 15) diseases (numbered 1..D) is running through the farm. Farmer John would
like to milk as many of his N (1 <= N <= 1,000) cows as possible. If the milked cows carry more than K (1
<= K <= D) different diseases among them, then the milk will be too contaminated and will have to be
discarded in its entirety. Please help determine the largest number of cows FJ can milk without having to
discard the milk.


Input
* Line 1: Three space-separated integers: N, D, and K

* Lines 2..N+1: Line i+1 describes the diseases of cow i with a list of 1 or more space-separated integers.
The first integer, d_i, is the count of cow i's diseases; the next d_i integers enumerate the actual diseases. Of
course, the list is empty if d_i is 0.


Output
* Line 1: M, the maximum number of cows which can be milked.


Sample Input
6 3 2
0
1 1
1 2
1 3
2 2 1
2 2 1

Sample Output
5

Hint
OUTPUT DETAILS:

If FJ milks cows 1, 2, 3, 5, and 6, then the milk will have only two diseases (#1 and #2), which is no greater
than K (2).


                                             Muddy roads
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:208 Accepted:105


Description
Farmer John has a problem: the dirt road from his farm to town has suffered in the recent rainstorms and
now contains (1 <= N <= 10,000) mud pools.

Farmer John has a collection of wooden planks of length L that he can use to bridge these mud pools. He
can overlap planks and the ends do not need to be anchored on the ground. However, he must cover each
pool completely.

Given the mud pools, help FJ figure out the minimum number of planks he needs in order to completely
cover all the mud pools.


Input
* Line 1: Two space-separated integers: N and L

* Lines 2..N+1: Line i+1 contains two space-separated integers: s_i and e_i (0 <= s_i < e_i <=
1,000,000,000) that specify the start and end points of a mud pool along the road. The mud pools will not
overlap. These numbers specify points, so a mud pool from 35 to 39 can be covered by a single board of
length 4. Mud pools at (3,6) and (6,9) are not considered to overlap.


Output
* Line 1: The miminum number of planks FJ needs to use.


Sample Input
3 3
1 6
13 17
8 12

Sample Output
5

Hint
INPUT DETAILS:

FJ needs to use planks of length 3 to cover 3 mud pools. The mud pools cover regions 1 to 6, 8 to 12, and
13 to 17.

OUTPUT DETAILS:

FJ can cover the mud pools with five planks of length 3 in the following way:

                   111222..333444555....
                    .MMMMM..MMMM.MMMM....


                    012345678901234567890



                                        Children's Dining
                               Time Limit:1000MS Memory Limit:65536K
                            Total Submit:350 Accepted:195 Special Judged


Description
Usually children in kindergarten like to quarrel with each other. This situation annoys the child-care women.
For instant, when diner time comes, a fierce conflict may break out when a certain couple of children sitting
side by side who are hostile with each other. Although there aren't too many children dining at the same
round table, but the relationship of "enemy" or "friend" may be very complex. The child-care women do
come across a big problem. Now it is time for you to help them to figure out a proper arrangement of sitting,
with which no two "enemy" children is adjacent.

Now we assume that there are 2 * n children who sit around a big table, and that none has more than n - 1
"enemies".


Input
The input is consisted of several test blocks. For each block, the first line contains two integers n and m (1
<= n <= 200, 0 <= m <= n (n - 1)). We use positive integers from 1 to 2 * n to label the children dining
round table. Then m lines followed. Each contains positive integers i and j ( i is not equal to j, 1 <= i, j <= 2
* n), which indicate that child i and child j consider each other as "enemy". In a input block, a same
relationship isn't given more than once, which means that if "i j" has been given, "j i" will not be given.

There will be a blank line between input blocks. And m = n = 0 indicates the end of input and this case
shouldn't be processed.


Output
For each test block, if the proper arrangement exist, you should print a line with a proper one; otherwise,
print a line with "No solution!".


Sample Input
1 0


2 2
1 2
3 4


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


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


0 0

Sample Output
1 2
4 2 3 1
1 6 3 2 5 4
1 6 7 2 3 4 5 8



                                 Disconnect the Orange!?
                               Time Limit:2000MS Memory Limit:65536K
                                    Total Submit:288 Accepted:138


Description
"In the fresh morning, there always gleams a star in the rosy sky. She is the brightest start - the Phosphor.
Her rays are suspended high, but sometimes tremble around the white walls, as if she would like to share
some touching stories with us. Since there appear the human beings, she has been always there, telling us
everything she has heard and seen for thousands of years in the rolling world." Now let's meet one of its
stories:
"A short time ago" - to her opinion, even thousands of years in men's eyes takes up a blink in her life – "my
beam focused on a prince named Remmarguts, (what a strange language) who is recognized as the wisest
and most kind-hearted man in his country UDF - United Delta of Freedom."




She proceeds to say, "that was a terribly cold day, and flakes of snow were falling outside, while one of them rested on a
large box. The snowflake grew larger and larger; actually turn out to be a maiden in white! 'I am Goddess Uohzgnah and I
am going to tell you the potential tragedy brought from Ahriman (the spirit of evil). The only way to prevent Ahriman's evil
world-rebuilding from happening is to solve her puzzle successfully. We have tried our best, but failed to solve it. Wise guy,
I will give you the only chance to protect your citizens. Take it –' "




That were N (4 <= N <= 269) pieces of the orange skin. Ahriman had made it into a lovely connected figure (the lovelier it
is, the more awful problem we are facing). Look at the picture above as an example.

Ahriman had also tied some HEAVY magic strings between some of them. The strings were of three different colors –
white (peace), light green (nature) and light blue (people) (which are the three basic elements in Ahriman's so-called "ideal
world").

"Goddess Uohzgnah handed two special magic stick to Prince Remmarguts, and told him the usage 'the first stick can make
you sure about what color each string is (these three colors are very much alike); the second stick can disconnect any two
connected pieces as you like' "

His aim was to cut off as many strings as possible (making it lighter) and to make the minimal number among three types
of strings maximal (i.e., if we put the numbers of three different strings X, Y, Z, our aim is to make min{X, Y, Z} as large
as we can). Meanwhile for any K (2 <= K <= N), the first K pieces are required to be connected all the time (i.e., if we
remove other pieces, these K pieces are still connected)!

"Goddess Uohzgnah disappeared in Remmarguts' sight, but I know she was hiding there watching the whole course that our
hero successfully solved the puzzle in a single day!" said the Phosphor, "Uohzgnah was affected by such a clever prince,
and told him that this was only a joke. (Faint to death) Remmarguts didn't mind at all, because both of them fell in love..."

Hearing such an interesting story, dare you solve the puzzle then?

Input
The first line contains two integer numbers N and M (N – 1 <= M <= N * (N - 1) / 2). N denotes number of
pieces of that miraculous orange and M denotes the number of strings. The pieces are numbered from 1 to
N.

Each of the following lines contains three integer numbers A, B and C (1 <= A, B <= N, A is not equal to B,
0 <= C <= 2). It shows that there's a string connecting piece A and piece B in color C.

We ensure at beginning of the puzzle, for any K (2 <= K <= N), the pieces numbered from 1 to K are
connected independently (i.e., without considering the pieces numbered from K + 1 to N, the pieces
numbered from 1 to K are still connected).


Output
After removing the strings, you should print a single line containing a single integer number, which is the
smallest one among the numbers of three different colors in the remainder strings.


Sample Input
10 13
1 2 0
2 3 1
2 4 2
4 5 0
4 6 2
6 7 1
4 7 0
7 8 1
7 9 0
7 10 1
8 9 2
9 10 0
3 8 2

Sample Output
3

Hint




We must cut off exactly (M – N + 1) strings! Enjoy it!


                                                         DNA
                                  Time Limit:1000MS Memory Limit:65536K
                                      Total Submit:1091 Accepted:251


Description
A kind of virus has attacked the X planet, and many lives are infected. After weeks of study, The CHO
(Creature Healthy Organization) of X planet finally finds out that this kind of virus has two kind of very
simple DNA, and can be represented by 101 and 111. Unfortunately, the lives on the planet also have DNA
formed by 0s and 1s. If a creature's DNA contains the virus' DNA, it will be affected; otherwise it will not.
Given an integer L, it is clear that there will be 2 ^ L different lives, of which the length of DNA is L. Your
job is to find out in the 2 ^ L lives how many won't be affected?


Input
The input contains several test cases. For each test case it contains a positive integer L (1 <= L <= 10 ^ 8).
The end of input is indicated by end-of-file.


Output
For each test case, output K mod 2005, here K is the number of lives that will not be affected.


Sample Input
4

Sample Output
9



                                        Arrange the Bulls
                               Time Limit:4000MS Memory Limit:65536K
                                    Total Submit:572 Accepted:181


Description
Farmer Johnson's Bulls love playing basketball very much. But none of them would like to play basketball
with the other bulls because they believe that the others are all very weak. Farmer Johnson has N cows (we
number the cows from 1 to N) and M barns (we number the barns from 1 to M), which is his bulls'
basketball fields. However, his bulls are all very captious, they only like to play in some specific barns, and
don’t want to share a barn with the others.

So it is difficult for Farmer Johnson to arrange his bulls, he wants you to help him. Of course, find one
solution is easy, but your task is to find how many solutions there are.

You should know that a solution is a situation that every bull can play basketball in a barn he likes and no
two bulls share a barn.

To make the problem a little easy, it is assumed that the number of solutions will not exceed 10000000.


Input
In the first line of input contains two integers N and M (1 <= N <= 20, 1 <= M <= 20). Then come N lines.
The i-th line first contains an integer P (1 <= P <= M) referring to the number of barns cow i likes to play in.
Then follow P integers, which give the number of there P barns.


Output
Print a single integer in a line, which is the number of solutions.


Sample Input
3 4
2 1 4
2 1 3
2 2 4

Sample Output
4



                                                Sequence
                               Time Limit:6000MS Memory Limit:65536K
                                   Total Submit:1086 Accepted:136


Description
Given m sequences, each contains n non-negative integer. Now we may select one number from each
sequence to form a sequence with m integers. It's clear that we may get n ^ m this kind of sequences. Then
we can calculate the sum of numbers in each sequence, and get n ^ m values. What we need is the smallest
n sums. Could you help us?


Input
The first line is an integer T, which shows the number of test cases, and then T test cases follow. The first
line of each case contains two integers m, n (0 < m <= 100, 0 < n <= 2000). The following m lines indicate
the m sequence respectively. No integer in the sequence is greater than 10000.


Output
For each test case, print a line with the smallest n sums in increasing order, which is separated by a space.


Sample Input
1
2 3
1 2 3
2 2 3

Sample Output
3 3 4



                                           Set Operation
                               Time Limit:3000MS Memory Limit:65536K
                                    Total Submit:814 Accepted:248


Description
You are given N sets, the i-th set (represent by S(i)) have C(i) element (Here "set" isn't entirely the same as
the "set" defined in mathematics, and a set may contain two same element). Every element in a set is
represented by a positive number from 1 to 10000. Now there are some queries need to answer. A query is
to determine whether two given elements i and j belong to at least one set at the same time. In another word,
you should determine if there exist a number k (1 <= k <= N) such that element i belongs to S(k) and
element j also belong to S(k).


Input
First line of input contains an integer N (1 <= N <= 1000), which represents the amount of sets. Then follow
N lines. Each starts with a number C(i) (1 <= C(i) <= 10000), and then C(i) numbers, which are separated
with a space, follow to give the element in the set (these C(i) numbers needn't be different from each other).
The N + 2 line contains a number Q (1 <= Q <= 200000), representing the number of queries. Then follow
Q lines. Each contains a pair of number i and j (1 <= i, j <= 10000, and i may equal to j), which describe the
elements need to be answer.


Output
For each query, in a single line, if there exist such a number k, print "Yes"; otherwise print "No".


Sample Input
3
3 1 2 3
3 1 2 5
1 10
4
1 3
1 5
3 5
1 10

Sample Output
Yes
Yes
No
No

Hint
The input may be large, and the I/O functions (cin/cout) of C++ language may be a little too slow for this
problem.


                                      Partition a Matrix
                               Time Limit:4000MS Memory Limit:65536K
                                    Total Submit:622 Accepted:164


Description
Given an M * N matrix consisted of non-negative elements, you may partition it into three parts with two
straight line segments. The line segments cannot go through any element of the matrix and they must be
parallel to the row or the column of the matrix, but they need not to be parallel to each other. Each of the
three parts is a non-empty matrix, which means it contains at least one element. We define the value of a
matrix as the sum of all elements in it. We denote the values of the three remaining matrices as X, Y, Z, and
the balance degree as |X - Y| + |Y - Z| + |Z - X|, where |.| means the absolute value. Among all ways of
partition, there is one, which has the least balance degree. Your task is to decide what the least balance
degree is.


Input
The input will consist of several test cases. For each test case, two integers M and N are given in the first
line, indicating the number of rows and columns of the matrix; each of the following M lines contains N
integers, indicating the matrix. The input is terminated by a single line with two zeros. You may assume
that 2 <= M, N <= 500 and all elements of the matrix are integers in the range [0, 65535].

There may be some blank lines between test cases.


Output
For each matrix of the input, print a line containing the least balance degree.


Sample Input
3 3
9 8 7
6 5 4
3 2 1
0 0

Sample Output
10
Hint
The three partitions are: {9, 8}, {6, 5, 3, 2}, {7, 4, 1}, whose values are: 9 + 8 = 17, 6 + 5 + 3 + 2 = 16, 7 +
4 + 1 = 12. The corresponding balance degree is: |17 - 16| + |16 - 12| + |12 - 17| = 10. This is the least
balance degree you can get


                                                       Squares
                                 Time Limit:15000MS Memory Limit:131072K
                                       Total Submit:489 Accepted:198


Description
A children's board game consists of a square array of dots that contains lines connecting some dots. One
part of the game requires that the players count the number of squares that are formed by these lines. For
example, in the figure shown below, there are 3 squares, 2 of size 1 and 1 of size 2 , so the total number of
squares is 3. (The "size" of a square is the number of lines segments required to form a side.)




Your task is to write a program to count the number of all the possible squares.

Input
The input represents a series of game boards. Each board consists of a description of a square array of n ^ 2
dots (where 2 <= n <= 1500) and some interconnecting horizontal and vertical lines. A record of a single
board with n ^ 2 dots and m (m <= 300000 )interconnecting lines is formatted as follows:

Line 1: "n" the number of dots in a single row or column.
Line 2: "m" the number of interconnecting lines.
Each of the next m lines are one of following two types:

"H i j k" (1 <= i, j <= n, k >0, j + k <= n) indicates a horizontal line of length k from the dot in row i,
column j to the dot in row i, column j + k.
or

"V i j k" (1 <= i, j <= n, k >0, i + k <= n) indicates a vertical line of length k from the dot in row i, column j
to the dot in row i + k, column j.

The end of input is indicated by end-of-file.


Output
For each record print only one integer, which is the number of squares.


Sample Input
4
9
H 1 1 1
H 1 3 1
H 2 1 3
H 3 2 1
H 4 2 2
V 1 1 1
V 1 2 3
V 2 3 1
V 1 4 3
4
9
H 1 1 1
H 1 3 1
H 2 1 3
H 3 2 1
H 4 2 2
V 1 1 1
V 1 2 3
V 2 3 1
V 1 4 3

Sample Output
3
3



                                                Chessboard
                                Time Limit:2000MS Memory Limit:65536K
                                    Total Submit:1109 Accepted:262
Description
Alice and Bob often play games on chessboard. One day, Alice draws a board with size M * N. She wants
Bob to use a lot of cards with size 1 * 2 to cover the board. However, she thinks it too easy to bob, so she
makes some holes on the board (as shown in the figure below).




We call a grid, which doesn’t contain a hole, a normal grid. Bob has to follow the rules below:
1. Any normal grid should be covered with exactly one card.
2. One card should cover exactly 2 normal adjacent grids.

Some examples are given in the figures below:




                                                    A VALID solution.




                         An invalid solution, because the hole of red color is covered with a card.
                           An invalid solution, because there exists a grid, which is not covered.

Your task is to help Bob to decide whether or not the chessboard can be covered according to the rules above.

Input
There are 3 integers in the first line: m, n, k (0 < m, n <= 32, 0 <= K < m * n), the number of rows, column
and holes. In the next k lines, there is a pair of integers (x, y) in each line, which represents a hole in the
y-th row, the x-th column.


Output
If the board can be covered, output "YES". Otherwise, output "NO".


Sample Input
4 3 2
2 1
3 3

Sample Output
YES

Hint

                                                           RSA
                                  Time Limit:3000MS Memory Limit:65536K
                                       Total Submit:656 Accepted:118


Description
RSA is the best-known public key encryption algorithm. In this algorithm each participant has a private key
that is shared with no one else and a public key which is published so everyone knows it. To send a secure
message to this participant, you encrypt the message using the widely known public key; the participant
then decrypts the messages using his or her private key. Here is the procedure of RSA:

First, choose two different large prime numbers P and Q, and multiply them to get N (= P * Q).
Second, select a positive integer E (0 < E < N) as the encryption key such that E and T= (P - 1) * (Q - 1) are
relatively prime.
Third, compute the decryption key D such that 0 <= D < T and (E * D) mod T = 1. Here D is a
multiplicative inverse of E, modulo T.

Now the public key is constructed by the pair {E, N}, and the private key is {D, N}. P and Q can be
discarded.

Encryption is defined by C = (M ^ E) mod N, and decryption is defined by M = (C ^ D) mod N, here M,
which is a non-negative integer and smaller than N, is the plaintext message and C is the resulting
ciphertext.

To illustrate this idea, let’s see the following example:
We choose P = 37, Q = 23, So N = P * Q = 851, and T = 792. If we choose E = 5, D will be 317 ((5 * 317)
mod 792 = 1). So the public key is {5, 851}, and the private key is {317, 851}. For a given plaintext M = 7,
we can get the ciphertext C = (7 ^ 5) mod 851 = 638.

As we have known,for properly choosen very large P and Q, it will take thousands of years to break a key,
but for small ones, it is another matter.

Now you are given the ciphertext C and public key {E, N}, can you find the plaintext M?


Input
The input will contain several test cases. Each test case contains three positive integers C, E, N (0 < C < N,
0 < E < N, 0 < N < 2 ^ 62).


Output
Output the plaintext M in a single line.


Sample Input
638 5 851

Sample Output
7



                                  A New Operating System
                              Time Limit:20000MS Memory Limit:65536K
                                     Total Submit:43 Accepted:6
                                       Case Time Limit:5000MS


Description
May is a lovely girl. Due to her filial piety, she wants to give a present on her mother's birthday. Because
both her parents are the top programmer in the world, she decided to design a new program, a special
program that is an Operating System! With the help of her excellent programming skill, May has already
finished the kernel of the new OS. And the birthday is coming, she is afraid that time is not enough to finish
the entire project in time. As her best net-pal, it's your duty to help her.
This is a multitask OS, processes run at the same time. There are following command in the OS:

CreateProcess(PID,Memory,Priority)
A new process is created with the process identification PID and memory size, and a priority. The priority
in this command is called outer priority of a process.

AddMessage(PID,Priority)
That means, add a new message to the message queue of process PID, with the priority of Priority. The
message with higher Priority will run earlier that lower ones. The Priority is called inner priority.

Run
Find out the message with biggest HP. HP is defined as the product of the inner priority of a message and
the corresponding process priority. If two or more messages have the same HP, the one with smallest PID
will run first. Print the information "Run: HP" to the output file, HP will be replaced by the message HP you
found, or print "Empty" instead if the message queue is empty. Finally remove this message if exist.

ChangePriority(PID,NewValue)
Change the outer priority of process PID to NewValue.

GetMemory(PID,Memory)
Process PID memory increases the amount of Memory.

FreeMemory(PID,Memory)
Process PID memory decreases the amount of Memory.

RunProcess(PID)
Similar with Run command. Find out the message in the process PID message queue, print the information
"Run Process: Priority" to the output file, Priority will be replaced by the message priority you found, or
print "Empty" instead if the message queue is empty. Finally remove this message if exist.

CloseMaxMemory
Find out the process that used the largest number of memory and close it if exists (if tie, the one with
smallest PID should be release first), or print "Empty" instead.
CloseProcess(PID)
Close the process with the identification of PID.

Whenever a process' memory is less than or equal to 0, it will be close automatically. In any of the above
commands except the first one, if the PID doesn't exist, please print an "Error" to the output. For the first
command, if the PID is already exist, print an "Error" and ignore this command.


Input
First line in the input is an integer number N (1 <= N <= 100000), which represents the number of
commands. The next N lines, each gives a command described above. Any number given in the input file
will be non-negative integer and will not be more than 1000000000.


Output
The output format has been described above.


Sample Input
11
CloseMaxMemory
CreateProcess(1,100,1)
CreateProcess(2,200,1)
CreateProcess(3,300,1)
AddMessage(1,9)
AddMessage(2,19)
AddMessage(1,10)
GetMemory(2,999)
CloseMaxMemory
Run
RunProcess(1)

Sample Output
Empty
Run: 10
Run Process: 9

Hint
The total size of the input files may be as large as 21.8MB.


                                        Remmarguts' Date
                               Time Limit:4000MS Memory Limit:65536K
                                    Total Submit:424 Accepted:89


Description
"Good man never makes girls wait or breaks an appointment!" said the mandarin duck father. Softly
touching his little ducks' head, he told them a story.

"Prince Remmarguts lives in his kingdom UDF – United Delta of Freedom. One day their neighboring
country sent them Princess Uyuw on a diplomatic mission."

"Erenow, the princess sent Remmarguts a letter, informing him that she would come to the hall and hold
commercial talks with UDF if and only if the prince go and meet her via the K-th shortest path. (in fact,
Uyuw does not want to come at all)"

Being interested in the trade development and such a lovely girl, Prince Remmarguts really became
enamored. He needs you - the prime minister's help!

DETAILS: UDF's capital consists of N stations. The hall is numbered S, while the station numbered T
denotes prince' current place. M muddy directed sideways connect some of the stations. Remmarguts' path
to welcome the princess might include the same station twice or more than twice, even it is the station with
number S or T. Different paths with same length will be considered disparate.


Input
The first line contains two integer numbers N and M (1 <= N <= 1000, 0 <= M <= 100000). Stations are
numbered from 1 to N. Each of the following M lines contains three integer numbers A, B and T (1 <= A, B
<= N, 1 <= T <= 100). It shows that there is a directed sideway from A-th station to B-th station with time T.

The last line consists of three integer numbers S, T and K (1 <= S, T <= N, 1 <= K <= 1000).


Output
A single line consisting of a single integer number: the length (time required) to welcome Princess Uyuw
using the K-th shortest path. If K-th shortest path does not exist, you should output "-1" (without quotes)
instead.


Sample Input
2 2
1 2 5
2 1 4
1 2 2
Sample Output
14



                                         A New Kind of Chess
                                  Time Limit:3000MS Memory Limit:65536K
                                        Total Submit:97 Accepted:13


Description
Prince Remmarguts met Uyuw successfully in our previous story, and after that Princess Uyuw introduced a
new kind of chess to Remmarguts named Nixgnauhc. The only chessman allowed in it was a special type of
Knight.

The chessboard is of (N + 1) * (M + 1). Each of the rows and columns are numbered as the following graph:




Here N + 1 = 5 + 1 is the number of rows and M + 1 = 4 + 1 is the number of columns. We are also given two integer
numbers P and Q, and told that at the beginning of the game, the blocks of (x, y) - (row number, column number) - where x
<= P and y <= Q are already taken up by Knight.
During the game, we can choose a single Knight to move, and the only allowed movements for Knight at (x, y) is to (x + a,
y + b) or to (x + c, y + d). But during the movement, the position it goes must be on the chessboard and NOT be taken up
by another Knight. Our purpose is to move that chessman to the final end (N, M). (The description above means that once
you choose a chessman, you can only move that chessman in the following steps)

Meanwhile, we suppose 3 <= N, M <= 100000, 0 <= P < N, 0 <= Q < M, 1<= a, b, c, d. Princess Uyuw wanted to know the
number of essentially different games. Two games are called ―different‖ if and only if we choose the different chessman at
the beginning or perform a different movement at some time.
WARNING: Even if a = c, b = d, we also call (+a, +b) and (+c, +d) DIFFERENT movements!

Input
You should read the number of test cases Z in the first line – Z <= 100.

Each of the following lines denotes a single test case, consisting of 8 integers N, M, P, Q, a, b, c, and d. The
meanings of such integers are described above.


Output
Output one line per test case, showing the total possibilities of games. We guarantee this number is less than
10^500.


Sample Input
2
3 3 0 0 1 1 1 1
5 4 2 1 1 1 2 1

Sample Output
8
7



                                          Uyuw's Concert
                               Time Limit:6000MS Memory Limit:65536K
                                    Total Submit:180 Accepted:52


Description
Prince Remmarguts solved the CHESS puzzle successfully. As an award, Uyuw planned to hold a concert
in a huge piazza named after its great designer Ihsnayish.

The piazza in UDF - United Delta of Freedom’s downtown was a square of [0, 10000] * [0, 10000]. Some
basket chairs had been standing there for years, but in a terrible mess. Look at the following graph.
In this case we have three chairs, and the audiences face the direction as what arrows have pointed out. The chairs were
old-aged and too heavy to be moved. Princess Remmarguts told the piazza's current owner Mr. UW, to build a large stage
inside it. The stage must be as large as possible, but he should also make sure the audience in every position of every chair
would be able to see the stage without turning aside (that means the stage is in the forward direction of their own).

To make it simple, the stage could be set highly enough to make sure even thousands of chairs were in front of you, as long
as you were facing the stage, you would be able to see the singer / pianist – Uyuw.

Being a mad idolater, can you tell them the maximal size of the stage?

Input
In the first line, there's a single non-negative integer N (N <= 20000), denoting the number of basket chairs.
Each of the following lines contains four floating numbers x1, y1, x2, y2, which means there’s a basket
chair on the line segment of (x1, y1) – (x2, y2), and facing to its LEFT (That a point (x, y) is at the LEFT
side of this segment means that (x – x1) * (y – y2) – (x – x2) * (y – y1) >= 0).


Output
Output a single floating number, rounded to 1 digit after the decimal point. This is the maximal area of the
stage.


Sample Input
3
10000 10000 0 5000
10000 5000 5000 10000
0 5000 5000 0

Sample Output
54166666.7

Hint
Sample input is the same as the graph above, while the correct solution for it is as below:




I suggest that you use Extended in pascal and long double in C / C++ to avoid precision error. But the standard program
only uses double.




A possible solution for the sample input.


                                             Sticks Problem
                                 Time Limit:6000MS Memory Limit:65536K
                                     Total Submit:1544 Accepted:384


Description
Xuanxuan has n sticks of different length. One day, she puts all her sticks in a line, represented by S1, S2,
S3, ...Sn. After measuring the length of each stick Sk (1 <= k <= n), she finds that for some sticks Si and Sj
(1<= i < j <= n), each stick placed between Si and Sj is longer than Si but shorter than Sj.

Now given the length of S1, S2, S3, …Sn, you are required to find the maximum value j - i.
Input
The input contains multiple test cases. Each case contains two lines.
Line 1: a single integer n (n <= 50000), indicating the number of sticks.
Line 2: n different positive integers (not larger than 100000), indicating the length of each stick in order.


Output
Output the maximum value j - i in a single line. If there is no such i and j, just output -1.


Sample Input
4
5 4 3 6
4
6 5 4 3

Sample Output
1
-1



                                          An Easy Problem
                                Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:794 Accepted:368


Description
As we known, data stored in the computers is in binary form. The problem we discuss now is about the
positive integers and its binary form.

Given a positive integer I, you task is to find out an integer J, which is the minimum integer greater than I,
and the number of '1's in whose binary form is the same as that in the binary form of I.

For example, if "78" is given, we can write out its binary form, "1001110". This binary form has 4 '1's. The
minimum integer, which is greater than "1001110" and also contains 4 '1's, is "1010011", i.e. "83", so you
should output "83".


Input
One integer per line, which is I (1 <= I <= 1000000).

A line containing a number "0" terminates input, and this line need not be processed.


Output
One integer per line, which is J.


Sample Input
1
2
3
4
78
0

Sample Output
2
4
5
8
83



                                            Jersey Politics
                               Time Limit:1000MS Memory Limit:65536K
                            Total Submit:785 Accepted:194 Special Judged


Description
In the newest census of Jersey Cows and Holstein Cows, Wisconsin cows have earned three stalls in the
Barn of Representatives. The Jersey Cows currently control the state's redistricting committee. They want to
partition the state into three equally sized voting districts such that the Jersey Cows are guaranteed to win
elections in at least two of the districts.

Wisconsin has 3*K (1 <= K <= 60) cities of 1,000 cows, numbered 1..3*K, each with a known number
(range: 0..1,000) of Jersey Cows. Find a way to partition the state into three districts, each with K cities,
such that the Jersey Cows have the majority percentage in at least two of districts.

All supplied input datasets are solvable.


Input
* Line 1: A single integer, K

* Lines 2..3*K+1: One integer per line, the number of cows in each city that are Jersey Cows. Line i+1
contains city i's cow census.


Output
* Lines 1..K: K lines that are the city numbers in district one, one per line

* Lines K+1..2K: K lines that are the city numbers in district two, one per line

* Lines 2K+1..3K: K lines that are the city numbers in district three, one per line


Sample Input
2
510
500
500
670
400
310

Sample Output
1
2
3
6
5
4

Hint
Other solutions might be possible. Note that "2 3" would NOT be a district won by the Jerseys, as they
would be exactly half of the cows.


Source
USACO 2005 February Gold


                                   Secret Milking Machine
                                Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:564 Accepted:135
Description
Farmer John is constructing a new milking machine and wishes to keep it secret as long as possible. He has
hidden in it deep within his farm and needs to be able to get to the machine without being detected. He must
make a total of T (1 <= T <= 200) trips to the machine during its construction. He has a secret tunnel that he
uses only for the return trips.

The farm comprises N (2 <= N <= 200) landmarks (numbered 1..N) connected by P (1 <= P <= 40,000)
bidirectional trails (numbered 1..P) and with a positive length that does not exceed 1,000,000. Multiple
trails might join a pair of landmarks.

To minimize his chances of detection, FJ knows he cannot use any trail on the farm more than once and that
he should try to use the shortest trails.

Help FJ get from the barn (landmark 1) to the secret milking machine (landmark N) a total of T times. Find
the minimum possible length of the longest single trail that he will have to use, subject to the constraint that
he use no trail more than once. (Note well: The goal is to minimize the length of the longest trail, not the
sum of the trail lengths.)

It is guaranteed that FJ can make all T trips without reusing a trail.


Input
* Line 1: Three space-separated integers: N, P, and T

* Lines 2..P+1: Line i+1 contains three space-separated integers, A_i, B_i, and L_i, indicating that a trail
connects landmark A_i to landmark B_i with length L_i.


Output
* Line 1: A single integer that is the minimum possible length of the longest segment of Farmer John's
route.


Sample Input
7 9 2
1 2 2
2 3 5
3 7 5
1 4 1
4 3 1
4 5 7
5 7 1
1 6 3
6 7 3

Sample Output
5

Hint
Farmer John can travel trails 1 - 2 - 3 - 7 and 1 - 6 - 7. None of the trails travelled exceeds 5 units in length.
It is impossible for Farmer John to travel from 1 to 7 twice without using at least one trail of length 5.

Huge input data,scanf is recommended


                                          Aggressive cows
                                Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:681 Accepted:184


Description
Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a
straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).

His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put
into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that
the minimum distance between any two of them is as large as possible. What is the largest minimum
distance?


Input
* Line 1: Two space-separated integers: N and C

* Lines 2..N+1: Line i+1 contains an integer stall location, xi


Output
* Line 1: One integer: the largest minimum distance


Sample Input
5 3
1
2
8
4
9

Sample Output
3

Hint
OUTPUT DETAILS:

FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.

Huge input data,scanf is recommended.


                                        Part Acquisition
                              Time Limit:1000MS Memory Limit:65536K
                           Total Submit:310 Accepted:130 Special Judged


Description
The cows have been sent on a mission through space to acquire a new milking machine for their barn. They
are flying through a cluster of stars containing N (1 <= N <= 50,000) planets, each with a trading post.

The cows have determined which of K (1 <= K <= 1,000) types of objects (numbered 1..K) each planet in
the cluster desires, and which products they have to trade. No planet has developed currency, so they work
under the barter system: all trades consist of each party trading exactly one object (presumably of different
types).

The cows start from Earth with a canister of high quality hay (item 1), and they desire a new milking
machine (item K). Help them find the best way to make a series of trades at the planets in the cluster to get
item K. If this task is impossible, output -1.


Input
* Line 1: Two space-separated integers, N and K.

* Lines 2..N+1: Line i+1 contains two space-separated integers, a_i and b_i respectively, that are planet i's
trading trading products. The planet will give item b_i in order to receive item a_i.


Output
* Line 1: One more than the minimum number of trades to get the milking machine which is item K (or -1
if the cows cannot obtain item K).

* Lines 2..T+1: The ordered list of the objects that the cows possess in the sequence of trades.


Sample Input
6 5
1 3
3 2
2 3
3 1
2 5
5 4

Sample Output
4
1
3
2
5

Hint
OUTPUT DETAILS:

The cows possess 4 objects in total: first they trade object 1 for object 3, then object 3 for object 2, then
object 2 for object 5.


                              Rigging the Bovine Election
                                Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:262 Accepted:105


Description
It's election time. The farm is partitioned into a 5x5 grid of cow locations, each of which holds either a
Holstein ('H') or Jersey ('J') cow. The Jerseys want to create a voting district of 7 contiguous (vertically or
horizontally) cow locations such that the Jerseys outnumber the Holsteins. How many ways can this be
done for the supplied grid?


Input
* Lines 1..5: Each of the five lines contains five characters per line, each 'H' or 'J'. No spaces are present.
Output
* Line 1: The number of distinct districts of 7 connected cows such that the Jerseys outnumber the
Holsteins in the district.


Sample Input
HHHHH
JHJHJ
HHHHH
HJHHJ
HHHHH

Sample Output
2

Hint
OUTPUT DETAILS:
The two possible districts are:

.....                   .....


JHJHJ                   JHJHJ


....H         and       .H...


....J                   .J...


.....                   .....


Any other possible district with seven cows has fewer than 4 Jerseys.


                                             Feed Accounting
                                  Time Limit:1000MS Memory Limit:65536K
                                       Total Submit:291 Accepted:144


Description
Farmer John is trying to figure out when his last shipment of feed arrived. Starting with an empty grain bin,
he ordered and received F1 (1 <= F1 <= 1,000,000) kilograms of feed. Regrettably, he is not certain exactly
when the feed arrived. Of the F1 kilograms, F2 (1 <= F2 <= F1) kilograms of feed remain on day D (1 <= D
<= 2,000). He must determine the most recent day that his shipment could have arrived.
Each of his C (1 <= C <= 100) cows eats exactly 1 kilogram of feed each day. For various reasons, cows
arrive on a certain day and depart on another, so two days might have very different feed consumption. The
input data tells which days each cow was present. Every cow ate feed from Farmer John's bin on the day she
arrived and also on the day she left.

Given that today is day D, determine the minimum number of days that must have passed since his last
shipment. The cows have already eaten today, and the shipment arrived before the cows had eaten.


Input
* Line 1: Four space-separated integers: C, F1, F2, and D

* Lines 2..C+1: Line i+1 contains two space-separated integers describing the presence of a cow. The first
integer tells the first day the cow was on the farm; the second tells the final day of the cow's presence. Each
day is in the range 1..2,000.


Output
The last day that the shipment might have arrived, an integer that will always be positive.


Sample Input
3 14 4 10
1 9
5 8
8 12

Sample Output
6

Hint
INPUT DETAILS:

The shipment was 14 kilograms of feed, and Farmer John has 4 kilograms left. He had three cows that ate
feed for some amount of time in the last 10 days.

OUTPUT DETAILS:

If Farmer John started with 14 kg of feed on day 6, then on days 6 and 7, two kilograms would be eaten
each day. On day 8, three kilograms would be eaten. On day 9, two kilograms would be eaten. On day 10,
one kilogram would be eaten. Thus, the total eaten would be 2 + 2 + 3 + 2 + 1 = 10, leaving him with 4
kilograms.
                                        Brownie Points I
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:337 Accepted:188


Description
Stan and Ollie play the game of Odd Brownie Points. Some brownie points are located in the plane, at
integer coordinates. Stan plays first and places a vertical line in the plane. The line must go through a
brownie point and may cross many (with the same x-coordinate). Then Ollie places a horizontal line that
must cross a brownie point already crossed by the vertical line.
Those lines divide the plane into four quadrants. The quadrant containing points with arbitrarily large
positive coordinates is the top-right quadrant.

The players score according to the number of brownie points in the quadrants. If a brownie point is crossed
by a line, it doesn't count. Stan gets a point for each (uncrossed) brownie point in the top-right and
bottom-left quadrants. Ollie gets a point for each (uncrossed) brownie point in the top-left and bottom-right
quadrants.

Your task is to compute the scores of Stan and Ollie given the point through which they draw their lines.


Input
Input contains a number of test cases. The data of each test case appear on a sequence of input lines. The
first line of each test case contains a positive odd integer 1 < n < 200000 which is the number of brownie
points. Each of the following n lines contains two integers, the horizontal (x) and vertical (y) coordinates of
a brownie point. No two brownie points occupy the same place. The input ends with a line containing 0
(instead of the n of a test).


Output
For each test case of input, print a line with two numbers separated by a single space. The first number is
Stan's score, the second is the score of Ollie when their lines cross the point whose coordinates are given at
the center of the input sequence of points for this case.


Sample Input
11
3 2
3 3
3 4
3 6
2 -2
1 -3
0 0
-3 -3
-3 -2
-3 -4
3 -7
0

Sample Output
6 3



                                               Magic Bitstrings
                                    Time Limit:1000MS Memory Limit:65536K
                                         Total Submit:196 Accepted:71


Description
A bitstring, whose length is one less than a prime, might be magic. 1001 is one such string. In order to see
the magic in the string let us append a non-bit x to it, regard the new thingy as a cyclic string, and make this
square matrix of bits


                                                        each bit        1001

                                                      every 2nd bit     0110

                                                      every 3rd bit     0110

                                                      every 4th bit     1001


This matrix has the same number of rows as the length of the original bitstring. The m-th row of the matrix has every m-th
bit of the original string starting with the m-th bit. Because the enlarged thingy has prime length, the appended x never gets
used.

If each row of the matrix is either the original bitstring or its complement, the original bitstring is magic.

Input
Each line of input (except last) contains a prime number p <= 100000. The last line contains 0 and this line
should not be processed.


Output
For each prime number from the input produce one line of output containing the lexicographically smallest,
non-constant magic bitstring of length p-1, if such a string exists, otherwise output Impossible.


Sample Input
5
3
17
47
2
79
0

Sample Output
0110
01
0010111001110100
0000100001101010001101100100111010100111101111
Impossible
001001100001011010000001001111001110101010100011000011011111101001011110011011



                                       Cutting a polygon
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:190 Accepted:46


Description
Given is a simple but not necessarily convex polygon. Given is also a line in the plane. If the polygon is cut
along the line then we may get several smaller polygons. Your task is to find the length of the cut, that is the
total length of the segments in the intersection of the line and the polygon.


Input
Input consists of a number of cases. The data of each case appears on a number of input lines, the first of
which contains two non negative integers n and m giving the number of the vertices of the polygon and the
number of cutting lines to consider, 3 <= n <= 1000. The following n lines contain coordinates of the
vertices of the polygon; each line contains the x and y coordinates of a vertex. The vertices are given either
in clockwise or counterclockwise order. Each of the following m lines of input contains four numbers; these
are x and y coordinates of the two points defining the cutting line. If a vertex of the polygon is closer than
1e-8 to the cutting line then we consider that the vertex lies on the cutting line.

Input is terminated by a line with n and m equal to 0.
Output




For each cutting line, print the total length of the segments in the intersection of the line and the polygon defined for this
test case, with 3 digits after the decimal point. Note: the perimiter of a polygon belongs to the polygon.

The picture above illustrates the first cutting line for the polygon from the sample.

Sample Input
9 5
0 0
0 2
1 1
2 2
3 1
4 2
5 1
6 2
6 0
-1 2 7.5 1
0 1 6 1
0 1.5 6 1.5
0 2 6 1
0 0 0 2
0 0

Sample Output
2.798
6.000
3.000
2.954
2.000



                                                 Bungee Jumping
                                    Time Limit:1000MS Memory Limit:65536K
                                         Total Submit:355 Accepted:131


Description
Once again, James Bond is fleeing from some evil people who want to see him dead. Fortunately, he has
left a bungee rope on a nearby highway bridge which he can use to escape from his enemies. His plan is to
attach one end of the rope to the bridge, the other end of the rope to his body and jump off the bridge. At the
moment he reaches the ground, he will cut the rope, jump into his car and be gone.

Unfortunately, he had not had enough time to calculate whether the bungee rope has the right length, so it is
not clear at all what is going to happen when he jumps off the bridge. There are three possible scenarios:

       The rope is too short (or too strong), and James Bond will never reach the ground.
       The rope is too long (or too weak), and James Bond will be going too fast when he touches the ground. Even for a
       special agent, this can be very dangerous. You may assume that if he collides at a speed of more than 10 m/s, he
        will not survive the impact.



The rope's length and strength are good. James Bond touches the ground at a comfortable speed and can escape.
As his employer, you would like to know whether James Bond survives or whether you should place a job ad for the
soon-to-be vacant position in the local newspaper. Your physicists claim that:

       The force with which James is pulled towards the earth is
        9.81 * w,
        where w is his weight in kilograms and 9.81 is the Earth acceleration in meters over squared seconds.
       Mr. Bond falls freely until the rope tautens. Then the force with which the bungee rope pulls him back into the sky
        depends on the current length of the rope and is
        k * Δl,
        where Δl is the difference between the rope's current length and its nominal, unexpanded length, and k is a
        rope-specific constant.



Given the rope's strength k, the nominal length of the rope l in meters, the height of the bridge s in meters, and James
Bond's body weight w, you have to determine what is going to happen to our hero. For all your calculations, you may
assume that James Bond is a point at the end of the rope and the rope has no mass. You may further assume that k, l, s, and
w are non-negative and that s < 200.

Input
The input contains several test cases, one test case per line. Each test case consists of four floating-point
numbers (k, l, s, and w) that describe the situation.


Output
Depending on what is going to happen, your program must print "Stuck in the air.", "Killed by the impact.",
or "James Bond survives.". Input is terminated by a line containing four 0s, this line should not be
processed.


Sample Input
350 20 30 75
375 20 30 75
400 20 30 75
425 20 30 75
450 20 30 75
400 20 30 50
400 20 30 80
400 20 30 85
0 0 0 0

Sample Output
Killed by the impact.
James Bond survives.
James Bond survives.
James Bond survives.
Stuck in the air.
Stuck in the air.
James Bond survives.
Killed by the impact.



                                      Brownie Points II
                              Time Limit:5000MS Memory Limit:65536K
                                   Total Submit:206 Accepted:74


Description
Stan and Ollie play the game of Odd Brownie Points. Some brownie points are located in the plane, at
integer coordinates. Stan plays first and places a vertical line in the plane. The line must go through a
brownie point and may cross many (with the same x-coordinate). Then Ollie places a horizontal line that
must cross a brownie point already crossed by the vertical line.
Those lines divide the plane into four quadrants. The quadrant containing points with arbitrarily large
positive coordinates is the top-right quadrant.

The players score according to the number of brownie points in the quadrants. If a brownie point is crossed
by a line, it doesn't count. Stan gets a point for each (uncrossed) brownie point in the top-right and
bottom-left quadrants. Ollie gets a point for each (uncrossed) brownie point in the top-left and bottom-right
quadrants.

Stan and Ollie each try to maximize his own score. When Stan plays, he considers the responses, and
chooses a line which maximizes his smallest-possible score.


Input
Input contains a number of test cases. The data of each test case appear on a sequence of input lines. The
first line of each test case contains a positive odd integer 1 < n < 200000 which is the number of brownie
points. Each of the following n lines contains two integers, the horizontal (x) and vertical (y) coordinates of
a brownie point. No two brownie points occupy the same place. The input ends with a line containing 0
(instead of the n of a test).


Output
For each input test, print a line of output in the format shown below. The first number is the largest score
which Stan can assure for himself. The remaining numbers are the possible (high) scores of Ollie, in
increasing order.


Sample Input
11
3 2
3 3
3 4
3 6
2 -2
1 -3
0 0
-3 -3
-3 -2
-3 -4
3 -7
0

Sample Output
Stan: 7; Ollie: 2 3;



                           Adventures in Moving - Part IV
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:555 Accepted:177


Description
To help you move from Waterloo to the big city, you are considering renting a moving truck. Gas prices
being so high these days, you want to know how much the gas for such a beast will set you back.
The truck consumes a full litre of gas for each kilometre it travels. It has a 200 litre gas tank. When you rent
the truck in Waterloo, the tank is half full. When you return it in the big city, the tank must be at least half
full, or you'll get gouged even more for gas by the rental company. You would like to spend as little as
possible on gas, but you don't want to run out along the way.
Input
Input is all integers. The first integer is the distance in kilometres from Waterloo to the big city, at most
10000. Next comes a set of up to 100 gas station specifications, describing all the gas stations along your
route, in non-decreasing order by distance. Each specification consists of the distance in kilometres of the
gas station from Waterloo, and the price of a litre of gas at the gas station, in tenths of a cent, at most 2000.


Output
Output is the minimum amount of money that you can spend on gas to get you from Waterloo to the big city.
If it is not possible to get from Waterloo to the big city without running out of gas along the way, output
"Impossible".


Sample Input
500
100 999
150 888
200 777
300 999
400 1009
450 1019
500 1399

Sample Output
450550



                                    Pairsumonious Numbers
                               Time Limit:1000MS Memory Limit:65536K
                            Total Submit:227 Accepted:119 Special Judged


Description
For 10 > N > 2 numbers we form N*(N-1)/2 sums by adding every pair of the numbers. Your task is to find
the N numbers given the sums.


Input
Each line of input contains N followed by N*(N-1)/2 integer numbers separated by a space.


Output
For each line of input, output one line containing N integers in non-descending order such that the input
numbers are pairwise sums of the N numbers. If there is more than one solution, any one will do; if there is
no solution, print "Impossible".


Sample Input
3 1269 1160 1663
3 1 1 1
5 226 223 225 224 227 229 228 226 225 227
5 216 210 204 212 220 214 222 208 216 210
5 -1 0 -1 -2 1 0 -1 1 0 -1
5 79950 79936 79942 79962 79954 79972 79960 79968 79924 79932

Sample Output
383 777 886
Impossible
111 112 113 114 115
101 103 107 109 113
-1 -1 0 0 1
39953 39971 39979 39983 39989



                                           Snow Clearing
                                Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:216 Accepted:93


Description
As the days become shorter and the nights become longer we turn our thoughts to snow clearing. Due to
budget cuts, the Big Noisy City has exactly one snow plow. The plow can clear exactly one lane of a road in
a single pass. Whenever there is snow on the ground, the plow departs from its hangar and tours the city,
plowing as it goes. What is the minimum time that the plow needs to clear every lane of every road?


Input
The first line of input contains two integers: the x,y coordinates of the hangar (in metres). Up to 100 lines
follow. Each gives the coordinates (in metres) of the beginning and end of a street. All roads are perfectly
straight, with one lane in each direction. The plow can turn any direction (including a U-turn) at any
intersection, and can turn around at the end of any street. The plow travels at 20 km/h if it is plowing, and
50 km/h if the lane it is driving on has already been plowed. It is possible to reach all streets from the
hangar.


Output
Your output should be the time, in hours and minutes, required to clear the streets and return to the hangar.
Round to the nearest minute.


Sample Input
0 0
0 0 10000 10000
5000 -10000 5000 10000
5000 10000 10000 10000

Sample Output
3:55



                                Adventures in Moving - Part V
                                    Time Limit:1000MS Memory Limit:65536K
                                          Total Submit:53 Accepted:14


Description
To save money you are considering renting a small cube van to transport your belongings to the Big City.
The interior of the van is a rectangular box with width w, height h, and length l. The box has a sliding door
that lifts but only to height H. That is, there is an immovable overhang of height H-h at the top of the door.
You have a large rectangular box that you wish to load on the truck. Can you get it on the truck subject to
the following constraints:

         The box must fit through the door, tilting it forward or sideways (but not both) as necessary (see figure below).
         The box must be placed with one side flat against the floor.
         The box must be placed with one side flat against the front wall.
         The door must close once the box is in place.



You may assume there are no obstructions (such as a ceiling or the ground) outside the truck that might interfere with
loading.

Input
There are several test cases, each represented by two lines of input. The first line of each contains 4 integers:
w, h, l, H. The next line contains 3 integers - the dimensions of the box.


Output
For each test case, print "The box goes on the truck." if it is possible to load the box on the truck; otherwise
print "The box will not go on the truck." You may assume that you start with an empty truck for each test
case.


Sample Input
8 8 12 7
8 12 8
8 8 12 7
7 12 8
8 8 12 7
1 7 13
100 200 99 190
100 195 30

Sample Output
The box will not go on the truck.
The box goes on the truck.
The box will not go on the truck.
The box goes on the truck.



                                            Stack 'em Up
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:301 Accepted:124


Description
A standard playing card deck contains 52 cards, 13 values in each of four suits. The values are named 2, 3,
4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace. The suits are named Clubs, Diamonds, Hearts, Spades. A
particular card in the deck can be uniquely identified by its value and suit, typically denoted <value> of
<suit>. For example, "9 of Hearts" or "King of Spades". Traditionally a new deck is ordered first
alphabetically by suit, then by value in the order given above.
The Big City has many Casinos. In one such casino the dealer is a bit crooked. She has perfected several
shuffles; each shuffle rearranges the cards in exactly the same way whenever it is used. A very simple
example is the "bottom card" shuffle which removes the bottom card and places it at the top. By using
various combinations of these known shuffles, the crooked dealer can arrange to stack the cards in just
about any particular order.

You have been retained by the security manager to track this dealer. You are given a list of all the shuffles
performed by the dealer, along with visual cues that allow you to determine which shuffle she uses at any
particular time. Your job is to predict the order of the cards after each in a sequence of shuffles.


Input
Input consists of an integer n <= 100, the number of shuffles that the dealer knows. 52n integers follow.
Each consecutive 52 integers will comprise all the integers from 1 to 52 in some order. Within each set of
52 integers, i in position j means that the shuffle moves the ith card in the deck to position j.

Several lines follow; each containing an integer k between 1 and n indicating that you have observed the
dealer applying the kth shuffle given in the input.


Output
Assume the dealer starts with a new deck ordered as described above. After each shuffle, give the names of
the cards in the deck, in the new order, followed by an empty line.


Sample Input
2
2 1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 52 51
52 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 1
1
2

Sample Output
3 of Clubs
2 of Clubs
4 of Clubs
5 of Clubs
6 of Clubs
7 of Clubs
8 of Clubs
9 of Clubs
10 of Clubs
Jack of Clubs
Queen of Clubs
King of Clubs
Ace of Clubs
2 of Diamonds
3 of Diamonds
4 of Diamonds
5 of Diamonds
6 of Diamonds
7 of Diamonds
8 of Diamonds
9 of Diamonds
10 of Diamonds
Jack of Diamonds
Queen of Diamonds
King of Diamonds
Ace of Diamonds
2 of Hearts
3 of Hearts
4 of Hearts
5 of Hearts
6 of Hearts
7 of Hearts
8 of Hearts
9 of Hearts
10 of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Hearts
2 of Spades
3 of Spades
4 of Spades
5 of Spades
6 of Spades
7 of Spades
8 of Spades
9 of Spades
10 of Spades
Jack of Spades
Queen of Spades
Ace of Spades
King of Spades


King of Spades
2 of Clubs
4 of Clubs
5 of Clubs
6 of Clubs
7 of Clubs
8 of Clubs
9 of Clubs
10 of Clubs
Jack of Clubs
Queen of Clubs
King of Clubs
Ace of Clubs
2 of Diamonds
3 of Diamonds
4 of Diamonds
5 of Diamonds
6 of Diamonds
7 of Diamonds
8 of Diamonds
9 of Diamonds
10 of Diamonds
Jack of Diamonds
Queen of Diamonds
King of Diamonds
Ace of Diamonds
2 of Hearts
3 of Hearts
4 of Hearts
5 of Hearts
6 of Hearts
7 of Hearts
8 of Hearts
9 of Hearts
10 of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Hearts
2 of Spades
3 of Spades
4 of Spades
5 of Spades
6 of Spades
7 of Spades
8 of Spades
9 of Spades
10 of Spades
Jack of Spades
Queen of Spades
Ace of Spades
3 of Clubs



                      Ambiguous permutations
                    Time Limit:1000MS Memory Limit:65536K
                         Total Submit:665 Accepted:376


Description
Some programming contest problems are really tricky: not only do they require a different output format
from what you might have expected, but also the sample output does not show the difference. For an
example, let us look at permutations.
A permutation of the integers 1 to n is an ordering of these integers. So the natural way to represent a
permutation is to list the integers in this order. With n = 5, a permutation might look like 2, 3, 4, 5, 1.
However, there is another possibility of representing a permutation: You create a list of numbers where the
i-th number is the position of the integer i in the permutation. Let us call this second possibility an inverse
permutation. The inverse permutation for the sequence above is 5, 1, 2, 3, 4.
An ambiguous permutation is a permutation which cannot be distinguished from its inverse permutation.
The permutation 1, 4, 3, 2 for example is ambiguous, because its inverse permutation is the same. To get rid
of such annoying sample test cases, you have to write a program which detects if a given permutation is
ambiguous or not.


Input
The input contains several test cases.
The first line of each test case contains an integer n (1 <= n <= 100000). Then a permutation of the integers
1 to n follows in the next line. There is exactly one space character between consecutive integers. You can
assume that every integer between 1 and n appears exactly once in the permutation.
The last test case is followed by a zero.


Output
For each test case output whether the permutation is ambiguous or not. Adhere to the format shown in the
sample output.


Sample Input
4
1 4 3 2
5
2 3 4 5 1
1
1
0

Sample Output
ambiguous
not ambiguous
ambiguous

Hint
Huge input,scanf is recommended.
                                               Bullshit Bingo
                                  Time Limit:1000MS Memory Limit:65536K
                                       Total Submit:611 Accepted:201


Description
Bullshit Bingo is a game to make lectures, seminars or meetings less boring. Every player has a card with 5
rows and 5 columns. Each of the 25 cells contains a word (the cell in the middle has always the word
"BINGO" written in it). Whenever a player hears a word which is written on his card, he can mark it. The
cell in the middle is already marked when the game starts. If a player has marked all the words in a row, a
column or a diagonal, he stands up and shouts "BULLSHIT". After this, the game starts over again.

Sitting in a lecture, you observe that some students in the audience are playing Bullshit Bingo. You wonder
what the average number of different words is until "BULLSHIT" is exclaimed. For the purpose of this
problem, a word consists of letters of the English alphabet ('a' to 'z' or 'A' to 'Z'). Words are separated by
characters other than letters (for example spaces, digits or punctuation). Do the comparison of words
case-insensitively, i.e., "Bingo" is the same word as "bingo". When counting the number of different words,
ignore the word BULLSHIT (indicating the end of the game), and consider only the words of the current
game, i.e., if a word has already occurred in a previous game, you may still count it in the current game. If
the last game is unfinished, ignore the words of that game.


Input
The input consists of the text of the lecture, with "BULLSHIT" occurring occasionally. The first game starts
with the first word in the input. Each occurrence of "BULLSHIT" indicates the end of one game.
You may assume, that

      the word "BULLSHIT" occurs only in uppercase letters
      every word has at most 25 characters, and each line has at most 100 characters
      there are at most 500 different words before a game ends
      the players follow the rules, so there is no need to check if a game is valid or not


Output
The output consists of one number: the average number of different words needed to win a game. Write the
number as a reduced fraction in the format shown below. Reduced fraction means that there should be no
integer greater than 1 which divides both the numerator and denominator. For example if there were 10
games, and the number of different words in each game summed up to 55, print "11 / 2".


Sample Input
Programming languages can be classified BULLSHIT into following types:
- imperative and BULLSHIT procedural languages
- functional languages
- logical BULLSHIT programming languages
- object-oriented BULLSHIT languages

Sample Output
9 / 2

Hint
In the sample input, there are 4 completed games. The number of different words is 5, 5, 4 and 4,
respectively.


                                    106 miles to Chicago
                              Time Limit:2000MS Memory Limit:65536K
                           Total Submit:498 Accepted:223 Special Judged


Description
In the movie "Blues Brothers", the orphanage where Elwood and Jack were raised may be sold to the Board
of Education if they do not pay 5000 dollars in taxes at the Cook Country Assessor's Office in Chicago.
After playing a gig in the Palace Hotel ballroom to earn these 5000 dollars, they have to find a way to
Chicago. However, this is not so easy as it sounds, since they are chased by the Police, a country band and a
group of Nazis. Moreover, it is 106 miles to Chicago, it is dark and they are wearing sunglasses.
As they are on a mission from God, you should help them find the safest way to Chicago. In this problem,
the safest way is considered to be the route which maximises the probability that they are not caught.


Input
The input contains several test cases.
Each test case starts with two integers n and m (2 <= n <= 100 , 1 <= m <= n*(n-1)/2). n is the number of
intersections, m is the number of streets to be considered.
The next m lines contain the description of the streets. Each street is described by a line containing 3
integers a, b and p (1 <= a, b <= n , a != b, 1 <= p <= 100): a and b are the two end points of the street and p
is the probability in percent that the Blues Brothers will manage to use this street without being caught.
Each street can be used in both directions. You may assume that there is at most one street between two end
points.
The last test case is followed by a zero.


Output
For each test case, calculate the probability of the safest path from intersection 1 (the Palace Hotel) to
intersection n (the Honorable Richard J. Daley Plaza in Chicago). You can assume that there is at least one
path between intersection 1 and n.
Print the probability as a percentage with exactly 6 digits after the decimal point. The percentage value is
considered correct if it differs by at most 10-6 from the judge output. Adhere to the format shown below
and print one line for each test case.


Sample Input
5 7
5 2 100
3 5 80
2 3 70
2 1 50
3 4 90
4 1 85
3 1 70
0

Sample Output
61.200000 percent



                                        Decorate the wall
                               Time Limit:3000MS Memory Limit:65536K
                                    Total Submit:356 Accepted:103


Description
After building his huge villa, Mr. Rich cannot help but notice that the interior walls look rather blank. To
change that, he starts to hang paintings from his wonderful collection. But soon he realizes that it becomes
quite difficult to find a place on the wall where a painting can be placed without overlapping other paintings.
Now he needs a program which would tell him, given the already placed paintings, where to place the next
painting without moving any other paintings (or indicating that this is impossible). Paintings have a
rectangular shape and are to be placed parallel to the side of the wall. If you do not mind a nice reward from
Mr. Rich, go on and solve the problem.


Input
The first line of the input file contains a number representing the number of test cases to follow. Each test
case starts with a line containing three numbers n, w and h. n is the number of paintings already hanging on
the wall, w is the width of the wall and h is the height of the wall. The next n lines contain 4 integers x1, y1,
x2, y2 each (0 <= x1 < x2 <= w, 0 <= y1 < y2 <= h); the x-coordinates give the distance to the left end of
the wall, the y-coordinates give the distance to the bottom of the wall. (x1, y1) is the position of the lower
left corner of a painting, (x2, y2) is the position of the upper right corner. The last line of each test case
contains the dimensions of the next painting to be placed, first its width w', then its height h' (1 <= w' <= w,
1 <= h' <= h). You are not allowed to rotate the painting.
You can assume that 0 <= n <= 200 and 1 <= w, h <= 1000000. Moreover, all paintings already hanging do
not overlap.


Output
Produce one line of output for each test case. Write "Fail!" if there is no place left on the wall where the
painting could be placed without overlapping other paintings. Otherwise, write the coordinates where the
lower left corner of the painting should be placed. In case there is more than one solution, select the solution
with a minimum y-coordinate, and break ties using the minimum x-coordinate.


Sample Input
2
1 10 9
5 4 10 9
9 5
2 10 10
5 5 10 10
0 0 4 3
3 4

Sample Output
Fail!
4 0

Hint
The following image illustrates the second sample test case:
                                      European railroad tracks
                                    Time Limit:1000MS Memory Limit:65536K
                                 Total Submit:340 Accepted:94 Special Judged


Description
As you may already know, different countries in Europe use different railroad systems. Not only do they
use different voltages for their trains, but also the distance between the two rails (gauge) differs. The
following table shows some railway gauges used:

                                               Broad gauge (Spain):          1674 mm
                                              Broad gauge (Portugal):        1665 mm
                                              Broad gauge (Ireland):         1600 mm
                                              Broad gauge (Finland):         1524 mm
                                           Broad gauge (former USSR): 1520 mm
                                                  Standard gauge:            1435 mm
                                           Narrow gauge (meter gauge): 1000 mm


A museum has trains from several countries. It needs tracks for every train type in order to show visitors the trains in use.
However, since only one train is used at a time, a rail can be used by trains of different types. It follows that for n trains,
each requiring a different railway gauge, n + 1 rails are sufficient (each train uses the leftmost rail and a rail that has exactly
the required distance to it). But sometimes it is possible to save even more rails.

Given the required railway gauges, your task is to construct a railway track that can be used by every train and requires the
least number of rails. Note that a train can use any two rails, provided the distance between them is right.

Input
The first line of the input contains a number representing the number of test cases to follow. Each test case
starts with an integer n (the number of different railway gauges required). The next line contains n integers
between 1000 and 5000, each defining one required railway gauge.
You can assume that 1 <= n <= 8. Moreover, for every test case in the input file, there will be a solution
requiring at most 5 rails.


Output
The output for each test case consists of three lines:
The first line is of the form "Scenario #X", where X is the test case number starting with 1. The second line
describes the solution your program has found; first your program should print how many rails are needed,
followed by a colon, then the positions of each rail in increasing order (the first rail should be at position 0).
The third line should be blank. If there are several solutions with the minimum number of rails, any one will
do.


Sample Input
3
4
1524 1520 1609 1435
3
1000 1520 1600
6
1000 2000 3000 4000 1500 2500

Sample Output
Scenario #1
4: 0 1520 1609 3044


Scenario #2
4: 0 1000 1520 1600


Scenario #3
5: 0 1500 3000 4000 5000



                                            Any fool can do it
                                    Time Limit:1000MS Memory Limit:65536K
                                         Total Submit:463 Accepted:128


Description
Surely you know someone who thinks he is very clever. You decide to let him down with the following
problem:

         "Can you tell me what the syntax for a set is?", you ask him.
         "Sure!", he replies, "a set encloses a possibly empty list of elements within two curly braces. Each element is either
          another set or a letter of the given alphabet. Elements in a list are separated by a comma."
         "So if I give you a word, can you tell me if it is a syntactically correct representation of a set?"
         "Of course, any fool can do it!" is his answer.



Now you got him! You present him with the following grammar, defining formally the syntax for a set (which was
described informally by him):
Set              ::= "{" Elementlist "}"


Elementlist      ::= <empty> | List
List           ::= Element | Element "," List


Element        ::= Atom | Set


Atom           ::= "{" | "}" | ","



<empty> stands for the empty word, i.e., the list in a set can be empty.
Soon he realizes that this task is much harder than he has thought, since the alphabet consists of the characters which are
also used for the syntax of the set. So he claims that it is not possible to decide efficiently if a word consisting of "{", "}"
and "," is a syntactically correct representation of a set or not.
To disprove him, you need to write an efficient program that will decide this problem.

Input
The first line of the input contains a number representing the number of lines to follow.
Each line consists of a word, for which your program has to decide if it is a syntactically correct
representation of a set. You may assume that each word consists of between 1 and 200 characters from the
set { "{", "}", "," }.


Output
Output for each test case whether the word is a set or not. Adhere to the format shown in the sample output.


Sample Input
4
{}
{{}}
{{}},{,}}
{,,}

Sample Output
Word #1: Set
Word #2: Set
Word #3: Set
Word #4: No Set



                                       Game schedule required
                                   Time Limit:1500MS Memory Limit:65536K
                                Total Submit:217 Accepted:66 Special Judged
Description
Sheikh Abdul really loves football. So you better don't ask how much money he has spent to make famous
teams join the annual tournament. Of course, having spent so much money, he would like to see certain
teams play each other. He worked out a complete list of games he would like to see. Now it is your task to
distribute these games into rounds according to following rules:

       In each round, each remaining team plays at most one game
       If there is an even number of remaining teams, every team plays exactly one game
       If there is an odd number of remaining teams, there is exactly one team which plays no game (it advances with a
        wildcard to the next round)
       The winner of each game advances to the next round, the loser is eliminated from the tournament
       If there is only one team left, this team is declared the winner of the tournament



As can be proved by induction, in such a tournament with n teams, there are exactly n - 1 games required until a winner is
determined.
Obviously, after round 1, teams may already have been eliminated which should take part in another game. To prevent this,
for each game you also have to tell which team should win.

Input
The input contains several test cases. Each test case starts with an integer n (2 <= n <= 1000), the number of
teams participating in the tournament. The following n lines contain the names of the teams participating in
the tournament. You can assume that each team name consists of up to 25 letters of the English alphabet ('a'
to 'z' or 'A' to 'Z').
Then follow n - 1 lines, describing the games the sheikh would like to see (in any order). Each line consists
of the two names of the teams which take part in that game. You can assume that it is always possible to
find a tournament schedule consisting of the given games.
The last test case is followed by a zero.


Output
For each test case, write the game schedule, distributed in rounds.
For each round, first write "Round #X" (where X is the round number) in a line by itself. Then write the
games scheduled in this round in the form: "A defeats B", where A is the name of the advancing team and B
is the name of the team being eliminated. You may write the games of a round in any order. If a wildcard is
needed for the round, write "A advances with wildcard" after the last game of the round, where A is the
name of the team which gets the wildcard. After the last round, write the winner in the format shown below.
Print a blank line after each test case.


Sample Input
3
A
B
C
A B
B C
5
A
B
C
D
E
A B
C D
A E
C E
0

Sample Output
Round #1
B defeats A
C advances with wildcard
Round #2
C defeats B
Winner: C


Round #1
A defeats B
C defeats D
E advances with wildcard
Round #2
E defeats A
C advances with wildcard
Round #3
E defeats C
Winner: E

Hint
Note that there is always more than one possible game schedule; you may print any of them.
Huge input and output,scanf and printf is recommended.


                               Help the problem setter
                              Time Limit:1000MS Memory Limit:65536K
                           Total Submit:161 Accepted:53 Special Judged
Description
Preparing a problem for a programming contest takes a lot of time. Not only do you have to write the
problem description and write a solution, but you also have to create difficult input files. In this problem,
you get the chance to help the problem setter to create some input for a certain problem.
For this purpose, let us select the problem which was not solved during last year's local contest. The
problem was about finding the optimal binary search tree, given the probabilities that certain nodes are
accessed. Your job will be: given the desired optimal binary search tree, find some access probabilities for
which this binary search tree is the unique optimal binary search tree. Don't worry if you have not read last
year's problem, all required definitions are provided in the following.
Let us define a binary search tree inductively as follows:

       The empty tree which has no node at all is a binary search tree
       Each non-empty binary search tree has a root, which is a node labelled with an integer, and two binary search trees
        as left and right subtree of the root
       A left subtree contains no node with a label >= than the label of the root
       A right subtree contains no node with a label <= than the label of the root



Given such a binary search tree, the following search procedure can be used to locate a node in the tree:
Start with the root node. Compare the label of the current node with the desired label. If it is the same, you have found the
right node. Otherwise, if the desired label is smaller, search in the left subtree, otherwise search in the right subtree.
The access cost to locate a node is the number of nodes you have to visit until you find the right node. An optimal binary
search tree is a binary search tree with the minimum expected access cost.

Input
The input contains several test cases. Each test case starts with an integer n (1 <= n <= 50), the number of
nodes in the optimal binary search tree. For simplicity, the labels of the nodes will be integers from 1 to n.
The following n lines describe the structure of the tree. The i-th line contains the labels of the roots of the
left and right subtree of the node with label i (or -1 for an empty subtree). You can assume that the input
always defines a valid binary search tree.
The last test case is followed by a zero.


Output
For each test case, write one line containing the access frequency for each node in increasing order of the
labels of the nodes. To avoid problems with floating point precision, the frequencies should be written as
integers, meaning the access probability for a node will be the frequency divided by the sum of all
frequencies. Make sure that you do not write any integer bigger than 263 - 1 (the maximum value fitting in
the GCC/G++ data type long long , the Java data type long or VC data type __int64). Otherwise, you may
produce any solution ensuring that there is exactly one optimal binary search tree: the binary search tree
given in the input.
Sample Input
3
-1 -1
1 3
-1 -1
10
-1 2
-1 3
-1 4
-1 5
-1 6
-1 7
-1 8
-1 9
-1 10
-1 -1
0

Sample Output
1 1 1
512 256 128 64 32 16 8 4 2 1

Hint
Note that the first test case in the sample input describes a tree looking like

     2


    / \


1        3




     Make sure the sum of your frequency won't exceed 263 - 1, as special judge may sum all frequency up.

                                           Farey Sequence
                                Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:1231 Accepted:321


Description
The Farey Sequence Fn for any integer n with n >= 2 is the set of irreducible rational numbers a/b with 0 <
a < b <= n and gcd(a,b) = 1 arranged in increasing order. The first few are
F2 = {1/2}
F3 = {1/3, 1/2, 2/3}
F4 = {1/4, 1/3, 1/2, 2/3, 3/4}
F5 = {1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5}

You task is to calculate the number of terms in the Farey sequence Fn.


Input
There are several test cases. Each test case has only one line, which contains a positive integer n (2 <= n <=
106). There are no blank lines between cases. A line with a single 0 terminates the input.


Output
For each test case, you should output one line, which contains N(n) ---- the number of terms in the Farey
sequence Fn.


Sample Input
2
3
4
5
0

Sample Output
1
3
5
9



                                               Maximum sum
                                Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:1308 Accepted:394


Description
Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:

                       t1      t2


          d(A) = max{ ∑ai + ∑aj | 1 <= s1 <= t1 < s2 <= t2 <= n }
                        i=s1      j=s2


Your task is to calculate d(A).

Input
The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n
integers: a1, a2, ..., an. (|ai| <= 10000).There is an empty line after each case.


Output
Print exactly one line for each test case. The line should contain the integer d(A).


Sample Input
1


10
1 -1 2 2 3 -3 4 -4 5 -5

Sample Output
13

Hint
In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.

Huge input,scanf is recommended.


                                          Longge's problem
                                    Time Limit:1000MS Memory Limit:65536K
                                         Total Submit:460 Accepted:139


Description
Longge is good at mathematics and he likes to think about hard mathematical problems which will be
solved by some graceful algorithms. Now a problem comes: Given an integer N(1 < N < 2^31),you are to
calculate ∑gcd(i, N) 1<=i <=N.

"Oh, I know, I know!" Longge shouts! But do you know? Please solve it.
Input
Input contain several test case.
A number N per line.


Output
For each N, output ,∑gcd(i, N) 1<=i <=N, a line


Sample Input
2
6

Sample Output
3
15



                                                     Cows
                                Time Limit:3000MS Memory Limit:65536K
                                     Total Submit:666 Accepted:156


Description
Farmer John's cows have discovered that the clover growing along the ridge of the hill (which we can think
of as a one-dimensional number line) in his field is particularly good.

Farmer John has N cows (we number the cows from 1 to N). Each of Farmer John's N cows has a range of
clover that she particularly likes (these ranges might overlap). The ranges are defined by a closed interval
[S,E].

But some cows are strong and some are weak. Given two cows: cowi and cowj, their favourite clover range
is [Si, Ei] and [Sj, Ej]. If Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj, we say that cowi is stronger than cowj.

For each cow, how many cows are stronger than her? Farmer John needs your help!


Input
The input contains multiple test cases.
For each test case, the first line is an integer N (1 <= N <= 105), which is the number of cows. Then come N
lines, the i-th of which contains two integers: S and E(0 <= S < E <= 105) specifying the start end location
respectively of a range preferred by some cow. Locations are given as distance from the start of the ridge.

The end of the input contains a single 0.


Output
For each test case, output one line containing n space-separated integers, the i-th of which specifying the
number of cows that are stronger than cowi.


Sample Input
3
1 2
0 3
3 4
0

Sample Output
1 0 0

Hint
Huge input and output,scanf and printf is recommended.


                                    Stars in Your Window
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:496 Accepted:90


Description
Fleeting time does not blur my memory of you. Can it really be 4 years since I first saw you? I still
remember, vividly, on the beautiful Zhuhai Campus, 4 years ago, from the moment I saw you smile, as you
were walking out of the classroom and turned your head back, with the soft sunset glow shining on your
rosy cheek, I knew, I knew that I was already drunk on you. Then, after several months’ observation and
prying, your grace and your wisdom, your attitude to life and your aspiration for future were all strongly
impressed on my memory. You were the glamorous and sunny girl whom I always dream of to share the
rest of my life with. Alas, actually you were far beyond my wildest dreams and I had no idea about how to
bridge that gulf between you and me. So I schemed nothing but to wait, to wait for an appropriate
opportunity. Till now — the arrival of graduation, I realize I am such an idiot that one should create the
opportunity and seize it instead of just waiting.

These days, having parted with friends, roommates and classmates one after another, I still cannot believe
the fact that after waving hands, these familiar faces will soon vanish from our life and become no more
than a memory. I will move out from school tomorrow. And you are planning to fly far far away, to pursue
your future and fulfill your dreams. Perhaps we will not meet each other any more if without fate and luck.
So tonight, I was wandering around your dormitory building hoping to meet you there by chance. But
contradictorily, your appearance must quicken my heartbeat and my clumsy tongue might be not able to
belch out a word. I cannot remember how many times I have passed your dormitory building both in Zhuhai
and Guangzhou, and each time aspired to see you appear in the balcony or your silhouette that cast on the
window. I cannot remember how many times this idea comes to my mind: call her out to have dinner or at
least a conversation. But each time, thinking of your excellence and my commonness, the predominance of
timidity over courage drove me leave silently.

Graduation, means the end of life in university, the end of these glorious, romantic years. Your lovely smile
which is my original incentive to work hard and this unrequited love will be both sealed as a memory in the
deep of my heart and my mind. Graduation, also means a start of new life, a footprint on the way to bright
prospect. I truly hope you will be happy everyday abroad and everything goes well. Meanwhile, I will try to
get out from puerility and become more sophisticated. To pursue my own love and happiness here in reality
will be my ideal I never desert.

Farewell, my princess!

If someday, somewhere, we have a chance to gather, even as gray-haired man and woman, at that time, I
hope we can be good friends to share this memory proudly to relight the youthful and joyful emotions. If
this chance never comes, I wish I were the stars in the sky and twinkling in your window, to bless you far
away, as friends, to accompany you every night, sharing the sweet dreams or going through the nightmares
together.




Here comes the problem: Assume the sky is a flat plane. All the stars lie on it with a location (x, y). for each star, there is a
grade ranging from 1 to 100, representing its brightness, where 100 is the brightest and 1 is the weakest. The window is a
rectangle whose edges are parallel to the x-axis or y-axis. Your task is to tell where I should put the window in order to
maximize the sum of the brightness of the stars within the window. Note, the stars which are right on the edge of the
window does not count. The window can be translated but rotation is not allowed.

Input
There are several test cases in the input. The first line of each case contains 3 integers: n, W, H, indicating
the number of stars, the horizontal length and the vertical height of the rectangle-shaped window. Then n
lines follow, with 3 integers each: x, y, c, telling the location (x, y) and the brightness of each star. No two
stars are on the same point.

There are at least 1 and at most 10000 stars in the sky. 1<=W,H<=1000000, 0<=x,y<2^31.


Output
For each test case, output the maximum brightness in a single line.


Sample Input
3 5 4
1 2 3
2 3 2
6 3 1
3 5 4
1 2 3
2 3 2
5 3 1

Sample Output
5
6



                                  Greatest Common Subtree
                                Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:120 Accepted:61


Description
We say tree T1 is a top-bottom subtree of tree T if
1. T1 is a tree and its nodes and edges are respectively the subsets of T’s nodes and edges, and
2. w is node of tree T1 but not the root of T, then w’s parent is also in tree T1.
We say two rooted unordered trees are isomorphic if
1. a tree with a single node (the root) is only isomorphic to a tree with a single node;
2. two trees with roots A and B, none of which is a single-node tree, are isomorphic iff there is a 1-1 correspondence
between the subtrees of A and the subtrees of B such that corresponding subtrees are isomorphic.




Given two rooted unordered trees, your task is to find out their top-bottom subtrees respectively which are isomorphic, and
maximize the number of nodes of the subtrees, i.e., the Greatest Common Subtree.
Input
There are several test cases in the input file. The first line of each case contains two integers: n and m,
representing the number of nodes of the first tree and the second. 1<=n, m<=50. n-1 lines follow, with two
integers each, indicating the label of the node and its parent in the first tree. Then m-1 lines follow, with two
integers each line, indicating the label of the node and its parent in the second tree. Nodes are labeled from
1 and the node labeled 1 is always the root.There is an empty line after each case.


Output
For each test case, output the number of nodes of the Greatest Common Subtree in a line.


Sample Input
13 14
2 1
3 1
4 1
5 3
6 3
7 3
8 4
9 4
10 4
11 6
12 9
13 9
2 1
3 1
4 2
5 2
6 2
7 3
8 4
9 4
10 5
11 6
12 9
13 10
14 10

Sample Output
9



                                                 A Funny Game
                                  Time Limit:1000MS Memory Limit:65536K
                                       Total Submit:525 Accepted:285


Description
Alice and Bob decide to play a funny game. At the beginning of the game they pick n(1 <= n <= 106) coins
in a circle, as Figure 1 shows. A move consists in removing one or two adjacent coins, leaving all other
coins untouched. At least one coin must be removed. Players alternate moves with Alice starting. The
player that removes the last coin wins. (The last player to move wins. If you can't move, you lose.)




                                                         Figure 1

Note: For n > 3, we use c1, c2, ..., cn to denote the coins clockwise and if Alice remove c2, then c1 and c3 are NOT
adjacent! (Because there is an empty place between c1 and c3.)

Suppose that both Alice and Bob do their best in the game.
You are to write a program to determine who will finally win the game.

Input
There are several test cases. Each test case has only one line, which contains a positive integer n (1 <= n <=
106). There are no blank lines between cases. A line with a single 0 terminates the input.
Output
For each test case, if Alice win the game,output "Alice", otherwise output "Bob".


Sample Input
1
2
3
0

Sample Output
Alice
Alice
Bob



                                                Highways
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:655 Accepted:250


Description
The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has no public highways. So the traffic
is difficult in Flatopia. The Flatopian government is aware of this problem. They're planning to build some
highways so that it will be possible to drive between any pair of towns without leaving the highway system.

Flatopian towns are numbered from 1 to N. Each highway connects exactly two towns. All highways follow
straight lines. All highways can be used in both directions. Highways can freely cross each other, but a
driver can only switch between highways at a town that is located at the end of both highways.

The Flatopian government wants to minimize the length of the longest highway to be built. However, they
want to guarantee that every town is highway-reachable from every other town.


Input
The first line of input is an integer T, which tells how many test cases followed.
The first line of each case is an integer N (3 <= N <= 500), which is the number of villages. Then come N
lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance
should be an integer within [1, 65536]) between village i and village j. There is an empty line after each test
case.
Output
For each test case, you should output a line contains an integer, which is the length of the longest road to be
built such that all the villages are connected, and this value is minimum.


Sample Input
1


3
0 990 692
990 0 179
692 179 0

Sample Output
692

Hint
Huge input,scanf is recommended.


                                              Apple Tree
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:288 Accepted:91


Description
Wshxzt is a lovely girl. She likes apple very much. One day HX takes her to an apple tree. There are N
nodes in the tree. Each node has an amount of apples. Wshxzt starts her happy trip at one node. She can eat
up all the apples in the nodes she reaches. HX is a kind guy. He knows that eating too many can make the
lovely girl become fat. So he doesn’t allow Wshxzt to go more than K steps in the tree. It costs one step
when she goes from one node to another adjacent node. Wshxzt likes apple very much. So she wants to eat
as many as she can. Can you tell how many apples she can eat in at most K steps.


Input
There are several test cases in the input
Each test case contains three parts.
The first part is two numbers N K, whose meanings we have talked about just now. We denote the nodes by
1 2 ... N. Since it is a tree, each node can reach any other in only one route. (1<=N<=100, 0<=K<=200)
The second part contains N integers (All integers are nonnegative and not bigger than 1000). The ith
number is the amount of apples in Node i.
The third part contains N-1 line. There are two numbers A,B in each line, meaning that Node A and Node B
are adjacent.
Input will be ended by the end of file.

Note: Wshxzt starts at Node 1.


Output
For each test case, output the maximal numbers of apples Wshxzt can eat at a line.


Sample Input
2 1
0 11
1 2
3 2
0 1 2
1 2
1 3

Sample Output
11
2



                                                Stamps
                              Time Limit:2000MS Memory Limit:65536K
                                  Total Submit:1183 Accepted:559


Description
Background
Everybody hates Raymond. He's the largest stamp collector on planet earth and because of that he always
makes fun of all the others at the stamp collector parties. Fortunately everybody loves Lucy, and she has a
plan. She secretly asks her friends whether they could lend her some stamps, so that she can embarrass
Raymond by showing an even larger collection than his.
Problem
Raymond is so sure about his superiority that he always tells how many stamps he'll show. And since Lucy
knows how many she owns, she knows how many more she needs. She also knows how many friends
would lend her some stamps and how many each would lend. But she'd like to borrow from as few friends
as possible and if she needs too many then she'd rather not do it at all. Can you tell her the minimum
number of friends she needs to borrow from?
Input
The first line contains the number of scenarios. Each scenario describes one collectors party and its first line
tells you how many stamps (from 1 to 1000000) Lucy needs to borrow and how many friends (from 1 to
1000) offer her some stamps. In a second line you’ll get the number of stamps (from 1 to 10000) each of her
friends is offering.


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. Then print a single line with the minimum number of friends Lucy needs to borrow
stamps from. If it’s impossible even if she borrows everything from everybody, write impossible. Terminate
the output for the scenario with a blank line.


Sample Input
3
100 6
13 17 42 9 23 57
99 6
13 17 42 9 23 57
1000 3
314 159 265

Sample Output
Scenario #1:
3


Scenario #2:
2


Scenario #3:
impossible



                                      A Knight's Journey
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:873 Accepted:287


Description
Background
The knight is getting bored of seeing the same black and white squares again and again and has decided to
make a journey
around the world. Whenever a knight moves, it is two squares in one direction and one square perpendicular
to this. The world of a knight is the chessboard he is living on. Our knight lives on a chessboard that has a
smaller area than a regular 8 * 8 board, but it is still rectangular.
Can you help this adventurous knight to make travel plans?

Problem
Find a path such that the knight visits every square once. The
knight can start and end on any square of the board.


Input
The input begins with a positive integer n in the first line. The
following lines contain n test cases. Each test case consists of a
single line with two positive integers p and q, such that 1 <= p * q <= 26. This represents a p * q chessboard,
where p describes how many different square numbers 1, . . . , p exist, q describes how many different
square letters exist. These are the first q letters of the Latin alphabet: A, . . .


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. Then print a single line containing the lexicographically first path that visits all
squares of the chessboard with knight moves followed by an empty line. The path should be given on a
single line by concatenating the names of the visited squares. Each square name consists of a capital letter
followed by a number.
If no such path exist, you should output impossible on a single line.


Sample Input
3
1 1
2 3
4 3

Sample Output
Scenario #1:
A1


Scenario #2:
impossible


Scenario #3:
A1B3C1A2B4C2A3B1C3A4B2C4
                                           Line Segments
                              Time Limit:10000MS Memory Limit:65536K
                                    Total Submit:599 Accepted:90


Description
Background
Line segments are a very common element in computational geometry. A line segment is the set of points
forming the shortest path between two points (including those points). Although they are a very basic
concept it can be hard to work with them if they appear in huge numbers unless you have an efficient
algorithm.
Problem
Given a set of line segments, count how many distinct pairs of line segments are overlapping. Two line
segments are said to be overlapping if they intersect in an infinite number of points.


Input
The first line contains the number of scenarios.
Each scenario starts with the number n of line segments (1 <= n <= 100000). Then follow n lines consisting
of four integers x1, y1, x2, y2 in the range [0, 1000000] each, representing a line segment that connects the
points (x1, y1) and (x2, y2). It is guaranteed that a line segment does not degenerate to a single point.


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. Then print a single line containing the number of distinct pairs of overlapping line
segments followed by an empty line.
Hint: The number of overlapping pairs may not fit into a 32-bit integer.


Sample Input
2
8
1 1 2 2
2 2 3 3
1 3 3 1
10 0 20 0
20 0 30 0
15 0 25 0
50 0 100 0
70 0 80 0
1
0 0 1 1

Sample Output
Scenario #1:
3


Scenario #2:
0

Hint
Huge input,scanf is recommended.


                                               Pimp My Ride
                                 Time Limit:3000MS Memory Limit:65536K
                                      Total Submit:860 Accepted:190


Description
Background
Today, there are quite a few cars, motorcycles, trucks and other vehicles out there on the streets that would
seriously need some refurbishment. You have taken on this job, ripping off a few dollars from a major TV
station along the way.
Of course, there's a lot of work to do, and you have decided that it's getting too much. Therefore you want
to have the various jobs like painting, interior decoration and so on done by garages. Unfortunately, those
garages are very specialized, so you need different garages for different jobs. More so, they tend to charge
you the more the better the overall appearance of the car is. That is, a painter might charge more for a car
whose interior is all leather. As those "surcharges" depend on what job is done and which jobs have been
done before, you are currently trying to save money by finding an optimal order for those jobs.
Problem
Individual jobs are numbered 1 through n. Given the base price p for each job and a surcharge s (in US$)
for every pair of jobs (i, j) with i != j, meaning that you have to pay additional $s for job i, if and only if job
j was completed before, you are to compute the minimum total costs needed to finish all jobs.


Input
The first line contains the number of scenarios. For each scenario, an integer number of jobs n, 1 <= n <=
14, is given. Then follow n lines, each containing exactly n integers. The i-th line contains the surcharges
that have to be paid in garage number i for the i-th job and the base price for job i. More precisely, on the
i-th line, the i-th integer is the base price for job i and the j-th integer (j != i) is the surcharge for job i that
applies if job j has been done before. The prices will be non-negative integers smaller than or equal to
100000.
Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. Then print a single line:
"You have officially been pimped for only $p"
with p being the minimum total price. Terminate the output for the scenario with a blank line.


Sample Input
2
2
10 10
9000 10
3
14 23 0
0 14 0
1000 9500 14

Sample Output
Scenario #1:
You have officially been pimped for only $30


Scenario #2:
You have officially been pimped for only $42



                                         Scavenger Hunt
                              Time Limit:1000MS Memory Limit:65536K
                                   Total Submit:711 Accepted:375


Description
Background
Bill has been the greatest boy scout in America and has become quite a superstar because he always
organized the most wonderful scavenger hunts (you know, where the kids have to find a certain route
following certain hints). Bill has retired now, but a nationwide election quickly found a successor for him, a
guy called George. He does a poor job, though, and wants to learn from Bill's routes. Unfortunately Bill has
left only a few notes for his successor.
Problem
Bill never wrote down his routes completely, he only left lots of little sheets on which he had written two
consecutive steps of the routes. He then mixed these sheets and memorized his routes similarly to how some
people learn for exams: practicing again and again, always reading the first step and trying to remember the
following. This made much sense, since one step always required something from the previous step.
George however would like to have a route written down as one long sequence of all the steps in the correct
order. Please help him make the nation happy again by reconstructing the routes.


Input
The first line contains the number of scenarios. Each scenario describes one route and its first line tells you
how many steps (3 <= S <= 333) the route has. The next S-1 lines each contain one consecutive pair of the
steps on the route separated by a single space. The name of each step is always a single string of letters.


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. Then print S lines containing the steps of the route in correct order. Terminate the
output for the scenario with a blank line.


Sample Input
2
4
SwimmingPool OldTree
BirdsNest Garage
Garage SwimmingPool
3
Toilet Hospital
VideoGame Toilet

Sample Output
Scenario #1:
BirdsNest
Garage
SwimmingPool
OldTree


Scenario #2:
VideoGame
Toilet
Hospital



                                            A Bug's Life
                               Time Limit:10000MS Memory Limit:65536K
                                    Total Submit:1622 Accepted:396
Description
Background
Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes that they feature
two different genders and that they only interact with bugs of the opposite gender. In his experiment,
individual bugs and their interactions were easy to identify, because numbers were printed on their backs.
Problem
Given a list of bug interactions, decide whether the experiment supports his assumption of two genders with
no homosexual bugs or if it contains some bug interactions that falsify it.


Input
The first line of the input contains the number of scenarios. Each scenario starts with one line giving the
number of bugs (at least one, and up to 2000) and the number of interactions (up to 1000000) separated by a
single space. In the following lines, each interaction is given in the form of two distinct bug numbers
separated by a single space. Bugs are numbered consecutively starting from one.


Output
The output for every scenario is a line containing "Scenario #i:", where i is the number of the scenario
starting at 1, followed by one line saying either "No suspicious bugs found!" if the experiment is consistent
with his assumption about the bugs' sexual behavior, or "Suspicious bugs found!" if Professor Hopper's
assumption is definitely wrong.


Sample Input
2
3 3
1 2
2 3
1 3
4 2
1 2
3 4

Sample Output
Scenario #1:
Suspicious bugs found!


Scenario #2:
No suspicious bugs found!

Hint
Huge input,scanf is recommended.


                                                    Rdeaalbe
                                  Time Limit:1000MS Memory Limit:65536K
                                       Total Submit:951 Accepted:222


Description
Background
As you probably know, the human information processor is a wonderful text recognizer that can handle
even sentences that are garbled like the following:

        The ACM Itrenntaoial Clloegaite Porgarmmnig Cnotset (IPCC)
        porvdies clolgee stuetnds wtih ooppriuntetiis to itnrecat
        wtih sutednts form ohetr uinevsrtieis.



Problem
People have claimed that understanding these sentences works in general when using the following rule: The first and last
letters of each word remain unmodified and all the characters in the middle can be reordered freely.
Since you are a skeptical ACM programmer, you immediately set on to write the following program:
Given a sentence and a dictionary of words, how many different sentences can you find that could potentially be mapped to
the same encoding?

Input
The first line contains the number of scenarios. Each scenario begins with a line containing the number n of
words in the dictionary (0 <= n <= 10000), which are printed on the following n lines. After this there is a
line containing the numbermof sentences that should be tested with the preceding dictionary (0 <= m <=
10000) and then m lines containing those sentences. The sentences consist of letters from a..z, A..Z and
spaces only and have a maximal length of 10000 characters. For each word in the dictionary a limitation of
100 characters can be assumed.


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. For each sentence output the number of sentences that can be formed on an individual
line. It is guaranteed that this number can be expressed using a signed 32-bit datatype. Terminate the output
for the scenario with a blank line.


Sample Input
2
3
ababa
aabba
abcaa
2
ababa
abbaa
14
bakers
brakes
breaks
binary
brainy
baggers
beggars
and
in
the
blowed
bowled
barn
bran
1
brainy bakers and beggars bowled in the barn

Sample Output
Scenario #1:
2
2


Scenario #2:
48



                                               Acid Text
                              Time Limit:2000MS Memory Limit:65536K
                                   Total Submit:285 Accepted:64


Description
Background
A couple of months ago the web standards project (WaSP) has come up with a test for modern browsers and
their CSS implementation called acid2. This test ensures that all the browsers have similar results when it
comes to parsing and displaying cascaded style sheet files (CSS) for HTML. Since you want to beat all the
other text-based browsers on standard compliance you directly start implementing the CSS capabilities into
your favorite text-browser Lynks.
Problem
Your text-browser will be given a set of graphic files and a simplified css-style-sheet. A graphic is defined
by a name, height, width and a 2-dimensional array of characters. All characters are to be printed except for
the character '.' which denotes a transparent pixel. Here is an example picture:


owl.png 5 7


.-----.


|O...O|


|..v..|


|.<_>.|


.-----.


Given the style-sheet your task is it to produce the graphical result that the browser is supposed to display. A CSS-file is
made up from a number of entries where each entry looks like this:
#<id> {


pos-x : <x> px ;


pos-y : <y> px ;


position : <relative = <id of graphic>|absolute> ;


file : <filename> ;


layer : <layer-number> ;


}


The following rules hold for the CSS-entries:
Lines Each CSS-entry will be given on exactly 7 lines as in the input above.
Ordering Each CSS-entry will contain exactly the 5 attributes pos-x, pos-y, position, file and layer, in this order, each
attribute on a separate line.
Whitespace There may be zero or more white-spaces (spaces and tabs) at the beginning of lines, at the end of lines or
everywhere where the sample above has a space.
Here are the rules for composing the picture:
Background The background is assumed to be black (i.e. just spaces).
Positioning The top left corner of the viewing device is assumed to be x : 0, y : 0. Absolute positioning always is based on
this top-left corner. Relative positioning information is always based on the topleft pixel of another graphic. There will not
be any circular references between CSS elements. All resulting positions will be zero or greater in x and y.
Layering Graphics with a higher layer number are to be printed after graphics with a lower layer number. Graphics with
the same layer number are to be printed in the order they appear in the CSS.

Input
The first line of the input is the number of scenarios that will follow. For each scenario the following
information is given: The first line contains the number of files to follow (at least one, at most 100), each of
which is given by a space separated triple of a filename f, a height h, a width w (1 <= w, h <= 100) and then
h lines, each with exactly w characters. Following the file definition is a single line with a number m (at
least one, at most 500), which is followed by a CSS file of m entries.
You can assume the resulting picture to be at most 1000 x 1000 characters large. All coordinates in CSS
entries will be given as integers with an absolute value less than 1000000. All filenames and identifiers are
made up from alphanumeric characters and dots only. No two files have the same name and no two
identifiers are equal. The layer attribute will be at least 0 and at most 1000000.


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. For each scenario print the resulting picture from overlaying all the given graphics
following the instructions in the CSS file. Your result for each scenario should be rectangular as small as
possible. However, transparent pixels always belong to the resulting picture, even if they are located
directly at the border. The top-left corner of the result should always contain position (0, 0). All empty areas
should be padded with spaces. Terminate the output for every scenario with a blank line.


Sample Input
1
4
bg.png 5 7
.-----.
|.....|
|.....|
|.....|
.-----.
eye.jpg 1 1
O
nose.bmp 1 1
v
mouth.png 1 3
<_>
5
#bg {
           pos-x: 1 px;
           pos-y: 1 px;
           position: absolute;
    file: bg.png;
        layer: 0;
}
#leftEye {
                  pos-x: 1 px;
                  pos-y: 1 px;
                  position: relative=bg;
        file: eye.jpg;
        layer: 1;
}
#rightEye {
                  pos-x: 4 px;
                  pos-y: 0 px;
                  position: relative=leftEye;
        file: eye.jpg;
        layer: 1;
}
#nose {
        pos-x: 2 px;
        pos-y: 1 px;
        position: relative=leftEye;
        file: nose.bmp;
        layer: 1;
}
#mouth {
        pos-x: -1 px;
        pos-y: 1 px;
        position: relative = nose;
        file: mouth.png;
        layer: 1;
}

Sample Output
Scenario #1:


        -----
    |O       O|
    |    v   |
    | <_> |
        -----



                                           Incomplete chess boards
                                      Time Limit:1000MS Memory Limit:65536K
                                           Total Submit:647 Accepted:387
Description
Background
Tom gets a riddle from his teacher showing 42 chess boards from each of which two squares are removed.
The teacher wants to know which boards can be completely covered by 31 dominoes. He promises ten bars
of chocolate for the person who solves the problem correctly. Tom likes chocolate, but he cannot solve this
problem on his own. So he asks his older brother John for help. John (who likes chocolate as well) agrees,
provided that he will get half the prize.
John's abilities lie more in programming than in thinking and so decides to write a program. Can you help
John? Unfortunately you will not win any bars of chocolate, but it might help you win this programming
contest.
Problem
You are given are 31 dominoes and a chess board of size 8 * 8, two distinct squares of which are removed
from the board. The square in row a and column b is denoted by (a, b) with a, b in {1, . . . , 8}.
A domino of size 2 × 1 can be placed horizontally or vertically onto the chess board, so it can cover either
the two squares {(a, b), (a, b + 1)} or {(b, a), (b + 1, a)} with a in {1, . . . , 8} and b in {1, . . . , 7}. The
object is to determine if the so-modified chess board can be completely covered by 31 dominoes.
For example, it is possible to cover the board with 31 dominoes if the squares (8, 4) and (2, 5) are removed,
as you can see in Figure 1.




Input
The first input line contains the number of scenarios k. Each of the following k lines contains four integers a,
b, c, and d, separated by single blanks. These integers in the range {1, . . . , 8} represent the chess board
from which the squares (a, b) and (c, d) are removed. You may assume that (a, b) != (c, d).


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. Then print the number 1 if the board in this scenario can be completely covered by 31
dominoes, otherwise write a 0. Terminate the output of each scenario with a blank line.


Sample Input
3
8 4 2 5
8 8 1 1
4 4 7 1

Sample Output
Scenario #1:
1


Scenario #2:
0


Scenario #3:
0



                                        Military Recruit
                               Time Limit:1000MS Memory Limit:65536K
                                    Total Submit:404 Accepted:184


Description
Background
Tom is a military recruit for an elite army unit. As the last part of his final exams, he will be put into
unknown terrain and has to find his way to a designated exit point, carrying all his heavy military gear.
As Tom is a little bit afraid of this task, he has used Google Maps to obtain satellite images of the training
area. He has identified all the possible entry and exit spots and possible connections with their estimated
length. This relation between sites does not need to be symmetric due to different terrain heights.
However, he does not know, from which site to which site he will have to march. Unfortunately, he quickly
realizes that he won't be able to successfully perform the march in the worst-case of the two sites that have
the maximum distance to each other, no matter how hard he practices.
Common sense tells him that his instructors will always pick distinct sites for the entry and exit sites, and he
assumes that every pair of distinct sites has equal probability to become his task.
Problem
Given a set of sites, possible connections between some of the sites together with their length and Tom's
desired success probability p, you are to compute the minimum distance Tom must be comfortable with so
that he will pass his exam with at least probability p, assuming that every pair of distinct sites is equally
likely.
Input
The first line contains the number of scenarios.
The next line contains an integer p (1 <= p <= 100) specifying Tom's minimum success probability. Then
follows a line with the number of sites n (2 <= n <= 100). The subsequent n lines contain n integers each,
separated by a space. The i-th line contains the distances from site i to all other sites, e.g. the distance from
site i to site j can be found in the i-th line at position j. Distances are non-negative integers less than 1000.
The distance from a site to itself will always be zero. If the distance between two sites is "-1" there is no
direct connection between those sites in the corresponding direction. You can assume that every site can be
reached somehow from every other site.


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1.
Then print a single line with the minimum distance Tom has to practice for followed by an empty line.


Sample Input
2
67
3
0 1 2
1 0 3
2 3 0
50
4
0 1 -1 -1
-1 0 1 999
1 -1 0 -1
-1 999 -1 0

Sample Output
Scenario #1:
3


Scenario #2:
2



                                               Strategies
                                Time Limit:1000MS Memory Limit:65536K
                                     Total Submit:979 Accepted:418
Description
Background
Bill, Steve and Linus participate in programming contests just like the one you're competing in right now.
They have different strategies and we’d like to find out whose strategy is the best.
Problem
Bill simply solves the problems in the order he gets them from the contest organizers. Steve first reads all
the problems and then solves them in increasing order of difficulty. Linus also reads all problems first, but
he's quite ambitious and thus solves them in decreasing order of difficulty.
The difficulty of a problem is measured in minutes it takes the guys to solve it. We have collected statistics
and we've consulted the oracle Larry so we know for all kinds of problems how long the guys will need. We
have also found out that the three of them always need the same time for each problem (which depends on
the difficulty of the problem), so they only differ by their strategies.
For several contests, we'd like you to tell us the winner, the number of problems he solved and his score.
The score for a single problem is the time in minutes from start of the contest until you solve it. The overall
score is the sum of scores of the problems you solved. The guys never make mistakes so you don't have to
deal with penalties. The winner is the one who solved the most problems, and in case of a tie, the one with
the lowest score. If there's still a tie, then they agree that Steve wins because he always brings delicious
apple pie.


Input
The first line contains the number of scenarios. Each scenario describes one contest and its first line tells
you how long the contest lasts (in minutes, from 30 to 1440) and the number of problems (from 3 to 24). In
a second line you'll get the difficulties of the problems, as explained above they tell you how many minutes
(from 1 to 600) the guys need in order to solve the problems.


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. Then print a single line telling who wins, the number of problems he solves and his
score. Use the exact format as shown below in the sample output, even if the winner only solves 0 or 1
problems. Terminate the output for the scenario with a blank line.


Sample Input
2
180 6
23 42 170 33 7 19
60 2
43 17

Sample Output
Scenario #1:
Steve wins with 5 solved problems and a score of 288.


Scenario #2:
Steve wins with 2 solved problems and a score of 77.



                                                        StuPId
                                        Time Limit:3000MS Memory Limit:65536K
                                             Total Submit:952 Accepted:476


Description
Background
At DUT, the Dreamland University of Technology, all students have personal id, numbers with six or seven
digits. But they're not just any numbers. Only those that have a checksum with a zero as last digit can be
valid ids.
Problem
Here's how to compute the checksum of an id number. Multiply the digits from back to front (!) with
repeating factors 9, 3, 7. Then simply add the products. Example:


id number :     1   3   9   0   2   7    2


factors     :   9   7   3   9   7   3    9


products    :   9 21 27     0 14 21 18


Here the checksum is 9+21+27+0+14+21+18 = 110. The last digit is zero, so the id is valid. Sometimes students have very
bad handwriting and the teaching assistents have a hard time identifying the id’s. You're asked to help in special cases,
where exactly one digit is unreadable. In that case, the missing digit can be computed (there's always exactly one correct
digit, thanks to 9, 3 and 7 being relatively prime to 10). Note that the students always begin concentrated and thus the first
digit will always be readable (and not zero).

Input
The first line contains the number of scenarios. Each scenario is a single line that contains an id number
with one digit replaced by a question mark and with six or seven digits length.


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. Then print a single line containing the correct id number. Terminate the output for the
scenario with a blank line.
Sample Input
4
13?0272
3?5678
345?78
314?592

Sample Output
Scenario #1:
1390272


Scenario #2:
335678


Scenario #3:
345778


Scenario #4:
3146592

Hint
Huge input and output,scanf and printf are recommended.


                                                       Binary Tree
                                      Time Limit:1000MS Memory Limit:65536K
                                           Total Submit:868 Accepted:377


Description
Background
Binary trees are a common data structure in computer science. In this problem we will look at an infinite
binary tree where the nodes contain a pair of integers. The tree is constructed like this:

         The root contains the pair (1, 1).
         If a node contains (a, b) then its left child contains (a + b, b) and its right child (a, a + b)



Problem
Given the contents (a, b) of some node of the binary tree described above, suppose you are walking from the root of the tree
to the given node along the shortest possible path. Can you find out how often you have to go to a left child and how often
to a right child?
Input
The first line contains the number of scenarios.
Every scenario consists of a single line containing two integers i and j (1 <= i, j <= 2*109) that represent
a node (i, j). You can assume that this is a valid node in the binary tree described above.


Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the
scenario starting at 1. Then print a single line containing two numbers l and r separated by a single space,
where l is how often you have to go left and r is how often you have to go right when traversing the tree
from the root to the node given in the input. Print an empty line after every scenario.


Sample Input
3
42 1
3 4
17 73

Sample Output
Scenario #1:
41 0


Scenario #2:
2 1


Scenario #3:
4 6

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:9
posted:10/12/2011
language:English
pages:142