You are on page 1of 292

1.

Problem: Quicksum

A checksum is an algorithm that scans a packet of data and returns a single number. The idea is that if the
packet is changed, the checksum will also change, so checksums are often used for detecting transmission
errors, validating document contents, and in many other situations where it is necessary to detect
undesirable changes in data.
For this problem, you will implement a checksum algorithm called Quicksum. A Quicksum packet allows only
uppercase letters and spaces. It always begins and ends with an uppercase letter. Otherwise, spaces and
letters can occur in any combination, including consecutive spaces.
A Quicksum is the sum of the products of each character's position in the packet times the character's value.
A space has a value of zero, while letters have a value equal to their position in the alphabet. So, A=1, B=2,
etc., through Z=26. Here are example Quicksum calculations for the packets "ACM" and "MID CENTRAL":
ACM: 1*1 + 2*3 + 3*13 = 46
MID CENTRAL: 1*13 + 2*9 + 3*4 + 4*0 + 5*3 + 6*5 + 7*14 + 8*20 + 9*18 + 10*1 + 11*12 = 650
Input
The input consists of one or more packets followed by a line containing only # that signals the end of the
input. Each packet is on a line by itself, does not begin or end with a space, and contains from 1 to 255
characters.
Output
For each packet, output its Quicksum on a separate line in the output.
Example Input:

Example Output:

ACM
MID CENTRAL
REGIONAL PROGRAMMING CONTEST
ACN
ACM
ABC
BBC
#

46
650
4690
49
75
14
15

2.

Problem: Linear Pachinko

This problem is inspired by Pachinko, a popular game in Japan. A traditional Pachinko machine is a cross
between a vertical pinball machine and a slot machine. The player launches small steel balls to the top of the
machine using a plunger as in pinball. A ball drops through a maze of pins that deflect the ball, and
eventually the ball either exits at a hole in the bottom and is lost, or lands in one of many gates scattered
throughout the machine which reward the player with more balls in varying amounts. Players who collect
enough balls can trade them in for prizes.
For the purposes of this problem, a linear Pachinko machine is a sequence of one or more of the following:
holes ("."), floor tiles ("_"), walls ("|"), and mountains ("/\"). A wall or mountain will never be adjacent to
another wall or mountain. To play the game, a ball is dropped at random over some character within a
machine. A ball dropped into a hole falls through. A ball dropped onto a floor tile stops immediately. A ball
dropped onto the left side of a mountain rolls to the left across any number of consecutive floor tiles until it
falls into a hole, falls off the left end of the machine, or stops by hitting a wall or mountain. A ball dropped
onto the right side of a mountain behaves similarly. A ball dropped onto a wall behaves as if it were dropped
onto the left or right side of a mountain, with a 50% chance for each. If a ball is dropped at random over the
machine, with all starting positions being equally likely, what is the probability that the ball will fall either
through a hole or off an end?
For example, consider the following machine, where the numbers just indicate character positions and are
not part of the machine itself:
123456789
/\.|__/\.
The probabilities that a ball will fall through a hole or off the end of the machine are as follows, by position:
1=100%, 2=100%, 3=100%, 4=50%, 5=0%, 6=0%, 7=0%, 8=100%, 9=100%. The combined probability for
the whole machine is just the average, which is approximately 61.111%.
Input: The input consists of one or more linear Pachinko machines, each 179 characters long and on a line
by itself, followed by a line containing only "#" that signals the end of the input.
Output: For each machine, compute as accurately as possible the probability that a ball will fall through a
hole or off the end when dropped at random, then output a single line containing that percentage truncated to
an integer by dropping any fractional part.
Example input:

Example output:

/\.|__/\.
_._/\_|.__/\./\_
...
___
./\.
_/\_
_|.|_|.|_|.|_
____|_____
#

61
53
100
0
100
50
53
10

3.

Problem: Surprising Strings

The D-pairs of a string of letters are the ordered pairs of letters that are distance D from each other. A string
is D-unique if all of its D-pairs are different. A string is surprising if it is D-unique for every possible distance D.
Consider the string ZGBG. Its 0-pairs are ZG, GB, and BG. Since these three pairs are all different, ZGBG is
0-unique. Similarly, the 1-pairs of ZGBG are ZB and GG, and since these two pairs are different, ZGBG is 1unique. Finally, the only 2-pair of ZGBG is ZG, so ZGBG is 2-unique. Thus ZGBG is surprising. (Note that
the fact that ZG is both a 0-pair and a 2-pair of ZGBG is irrelevant, because 0 and 2 are different distances.)
Input
The input consists of one or more nonempty strings of at most 79 uppercase letters, each string on a line by
itself, followed by a line containing only an asterisk that signals the end of the input.
Output
For each string of letters, output whether or not it is surprising using the exact output format shown below.
Acknowledgement: This problem is inspired by the "Puzzling Adventures" column in the December 2003
issue of Scientific American.
Example input:

Example output:

ZGBG
X
EE
AAB
AABA
AABB
BCBABCC
*

ZGBG is surprising.
X is surprising.
EE is surprising.
AAB is surprising.
AABA is surprising.
AABB is NOT surprising.
BCBABCC is NOT surprising.

4.

Problem: Falling Ice

Imagine disks of ice falling, one at a time, into a box, each ending up at the lowest point it can reach without
overlapping or moving previous disks. Each disk then freezes into place, so it cannot be moved by later
disks. Your job is to find the overall height of the final combination of disks.
So that the answer is unique, assume that any disk reaching the bottom of the box rolls as far to the left as
possible. Also the data is chosen so there will be a unique lowest position for any disk that does not reach
the bottom. The data is also such that there are no "perfect fits": each disk that lands will be in contact with
only two other points, on previous circles or the sides of the box. The illustrations above show white filled
disks labeled with the order in which they fall into their boxes. The gray circle in the fourth illustration is not
intended to be a disk that fell in. The gray disk is included to demonstrate a point: the gray disk is the same
size as disk 2, so there is space for disk 2 on the very bottom of its box, but disk 2 cannot reach that position
by falling from the top. It gets caught on disk 1 and the side of the box.
One way to find the top intersection point of two intersecting circles is as follows. Suppose circle 1 has center
(x1, y1) and radius r1, and suppose circle 2 has center (x2, y2), and radius r2. Also assume that circle 1 is to
the left of circle 2, i.e., x1 < x2. Let
dx = x2 - x1,
dy = y2 - y1,
D = sqrt(dx*dx + dy*dy),
E = (r1*r1 - r2*r2 + D*D)/(2*D),
F = sqrt(r1*r1 - E*E);
then the upper intersection point is (x1 + (E*dx - F*dy)/D, y1 + (F*dx + E*dy)/D).
Input
The input consists of one or more data sets, followed by a line containing only 0 that signals the end of the
input. Each data set is on a line by itself and contains a sequence of three or more blank-separated positive
integers, in the format w, n, d1, d2, d3, ..., dn, where w is the width of the box, n is the number of disks, and
the remaining numbers are the diameters of the disks, in the order in which they fall into the box. You can
assume that w < 100, that n < 10, and that each diameter is less than w.
Output
For each data set, output a single line containing the height of the pile of disks, rounded to two places
beyond the decimal point.
The example data matches the illustrations above.

Example input:
10 3 5 2 3
8255
11 3 10 2 4
93446

Example output:
5.00
9.00
12.99
9.58

Example input:
10 6 5 4 6 3 5 2
0

Example output:
14.19

5.

Problem: Frugal Search

For this problem you will write a search engine that takes a query, searches a collection of words, and finds
the lexicographically smallest word that matches the query (i.e., the matching word that would appear first in
an English dictionary). A query is a sequence of one or more terms separated by single vertical bars ("|"). A
term is one or more letters followed by zero or more signed letters. A signed letter is either +s ("positive" s)
or -s ("negative" s), where s is a single letter. All letters are lowercase, and no letter will appear more than
once within a term. A query will not contain spaces. A term matches a word if the word contains at least one
of the unsigned letters, all of the positive letters, and none of the negative letters; a query matches a word if
at least one of its terms matches the word.
Input
The input consists of one or more test cases followed by a line containing only "#" that signals the end of the
input. Each test case consists of 1100 words, each on a line by itself, followed by a line containing only "*"
that marks the end of the word list, followed by one or more queries, each on a line by itself, followed by a
line containing only "**" that marks the end of the test case. Each word will consist of 120 lowercase letters.
All words within a test case will be unique. Each query will be as defined above and will be 179 characters
long.
Output
For each query, output a single line containing the lexicographically smallest word within that test case that
matches the query, or the word NONE if there is no matching word. At the end of each test case, output a
dollar sign on a line by itself.
Example input:

Example output:

Elk
cow
bat
*
ea
acm+e
nm+o|jk+l
**
debian
slackware
gentoo
ubuntu
suse
fedora
mepis
*
yts
cab-e+n
r-e|zjq|i+t|vs-p+e-u-c
**
#

bat
NONE
elk
$
gentoo
ubuntu
NONE
$

6.

Problem: Go Go Gorelians

The Gorelians travel through space using warp links. Travel through a warp link is instantaneous, but for
safety reasons, an individual can only warp once every 10 hours. Also, the cost of creating a warp link
increases directly with the linear distance between the link endpoints.
The Gorelians, being the dominant force in the known universe, are often bored, so they frequently conquer
new regions of space in the following manner.
1) The initial invasion force finds a suitable planet and conquers it, establishing a Regional Gorelian Galactic
Government, hereafter referred to as the RGGG, that will govern all Gorelian matters in this region of space.
2) When the next planet is conquered, a single warp link is constructed between the new planet and the
RGGG planet. Planets connected via warp links in this manner are said to be part of the Regional Gorelian
Planetary Network, that is, the RGPN.
3) As additional planets are conquered, each new planet is connected with a single warp link to the nearest
planet already in the RGPN, thus keeping the cost of connecting new planets to the network to a minimum. If
two or more planets are equidistant from the new planet, the new planet is connected to whichever of them
was conquered first.
This causes a problem however. Since planets are conquered in a more-or-less random fashion, after a
while, the RGGG will probably not be in an ideal location. Some Gorelians needing to consult with the RGGG
might only have to make one or two warps, but others might require dozens---very inconvenient when one
considers the 10-hour waiting period between warps.
So, once each Gorelian year, the RGGG analyzes the RGPN and relocates itself to an optimal location. The
optimal location is defined as a planet that minimizes the maximum number of warps required to reach the
RGGG from any planet in the RGPN. As it turns out, there is always exactly one or two such planets. When
there are two, they are always directly adjacent via a warp link, and the RGGG divides itself evenly between
the two planets.
Your job is to write a program that finds the optimal planets for the RGGG. For the purposes of this problem,
the region of space conquered by the Gorelians is defined as a cube that ranges from (0,0,0) to
(1000,1000,1000).
Input
The input consists of a set of scenarios where the Gorelians conquer a region of space. Each scenario is
independent. The first line of the scenario is an integer N that specifies the total number of planets
conquered by the Gorelians. The next N lines of the input specify, in the order conquered, the IDs and
coordinates of the conquered planets to be added to the RGPN, in the format ID X Y Z. An ID is an integer
from 1 to 1000. X, Y, and Z are integers from 0 to 1000. A single space separates the numbers. A value of N
= 0 marks the end of the input.
Output
For each input scenario, output the IDs of the optimal planet or planets where the RGGG should relocate.
For a single planet, simply output the planet ID. For two planets, output the planet IDs, smallest ID first,
separated by a single space.

Example Input:

Example Output:

5
1000
2001
3002
4003
5004
5
1000
2110
3320
4210

3
24
31 97

Example Input:

Example Output:

5300
10
21 71 76 4
97 32 5 69
70 33 19 35
3 79 81 8
31 91 17 67
52 31 48 75
48 90 14 4
41 73 2 21
83 74 41 69
26 32 30 24
0

7.

Problem: Dice

The people of AC Mamia have a tradition of rolling a six sided die to determine who will choose where to dine
that evening.
One person rolls the die, the other calls odd or even. If the caller guesses correctly, then he or she gets
to choose the restaurant; otherwise, the person throwing does. Hopefully, it is obvious that odd wins
when 1, 3 or 5 is rolled, and even with 2, 4 or 6! ACMamians also have a tradition of repeating the same
call (either odd or even) several times in succession. Your task is to check the recorded rolls and
determine how many times each person wins.
Input
Input for this problem consists of a sequence of one or more scenarios. Each scenario contains 3 lines.

The first line contains, in order, the names of two people, and one of the words odd or even
(in lowercase), separated by a space. The first named person will always throw, and the second
named person will always call either odd or even, as indicated. In AC Mamia, a name is a nonempty sequence of up to 20 (inclusive) letters (any of which may be uppercase or lowercase).
The second line will be an integer, N, 1 N 255, representing the number of die throws.
The third line contains N integers, each between 1 and 6 (inclusive), separated by single spaces,
representing die throws.
The input will be terminated by a line consisting of three hash signs (#), separated by single spaces. This
line should not be processed.
Output
Output will be a sequence of lines, one for each input scenario. Each line will contain in order the following
items, separated by single spaces: the name of the first person (exactly as it appears in the input), the
number of times the first person won, the name of the second person (exactly as it appears in the input),
and the number of times the second person won.
SAMPLE INPUT:
Bill Susan even
8
16534255
Sarah Tony odd
15
245436125431256
###

SAMPLE OUTPUT:
Bill 5 Susan 3
Sarah 8 Tony 7

8.

Problem: CD Titles

I found my hard disk quickly filling up with snapshots and videos. I decided to offload a lot of the files to CD.
Each CD is in its own plastic case, and the contents are clearly described on the front of the case. As the
number of CDs increased, I built myself a shelf on which the CDs stand vertically. I need your help! I have
written a title for each CD into a text file, but I need the titles to appear vertically so that I can put them in
the spine of the CD cases and be able to read them easily from the shelf. I want you to write a program that
will output my titles vertically. I need lines between each title so that, when I print them, I can easily cut
along the lines.
I have worked out that I can fit 36 characters into the available space, so all output titles must be 36
characters long, padded with spaces at the end where necessary. If I accidentally make a title too long,
only output the first 36 characters.
Input
Input will be at most 50 titles, one to a line. Each title consists of 1 to 100 arbitrary characters. A single #
on a line by itself indicates the end of input.
Output
Output will be the same titles presented vertically, where the left to right order will be the same as the order
of the input. There will be a column of bar (|) characters at each end, and separating each title, and a row
of minus (-) characters (1 per column) at the beginning and end.
SAMPLE INPUT:
012345678901234567890123456789012345
David and Janes wedding, March 2002, Alexandria
Bahamas Holiday August 2001
#

SAMPLE
OUTPUT:
------|0|D|B|
|1|a|a|
|2|v|h|
|3|i|a|
|4|d|m|
|5| |a|
|6|a|s|
|7|n| |
|8|d|H|
|9| |o|
|0|J|l|
|1|a|i|
|2|n|d|
|3|e|a|
|4||y|
|5|s| |
|6| |A|
|7|w|u|
|8|e|g|
|9|d|u|
|0|d|s|
|1|i|t|
|2|n| |
|3|g|2|
|4|,|0|
|5| |0|
|6|M|1|
|7|a| |
|8|r| |
|9|c| |
|0|h| |
|1| | |
1

|2|2| |
|3|0| |
|4|0| |
|5|2| |
-------

9.

Problem: House Numbering

The government of Acmonia has decided that henceforth all house numbers should be given in binary
instead of decimal notation. Householders will now have to purchase 0 and 1 binary digits to display on their
houses. For reasons much too complicated to discuss here it seems that the cost to a householder of a 0
binary digit and of a 1 binary digit may well differ. Your task is to write a program which will report to
householders the cost of their new numbers.
Input
The input text consists of a number of sets of problems. The first line of a set is of the form COST a b. For
that set:
10. a and b are both integers, 0 a, b 1000,
11. a 0 binary digit costs a dollars,
12. a 1 binary digit costs b dollars.
The first line is followed by one or more lines each consisting of a single integer n.
1 0 n 2 000 000,
2 n indicates a house number, expressed as a standard decimal number.
A single # on a line indicates the end of input.
Output
Each set of output data must begin with a single output line showing consisting of the word Set, followed
by a space ( ), and the current set number (counted from 1). This is followed by the cost of the binary
digits for each house number, each cost being displayed as a decimal number on a separate line.
SAMPLE INPUT:
COST 1 1
1
34
15
COST 1 10
1
34
15
COST 10 1
1
34
15
COST 0 5
1
16
#

SAMPLE OUTPUT:
Set 1
1
6
4
Set 2
10
24
40
Set 3
1
42
4
Set 4
5
5

13.Problem: Vowels Frequencies


The English alphabet consists of 26 letters. Five of these (a, e, i, o and u) are classified as vowels, the
remaining 21 as consonants. Almost every English word contains at least one vowel (rhythm is one of the
few exceptions).
In this problem you will be given a number of pieces of English text. Your task is to determine the frequency
of each vowel that is found in the piece, and to display the answers sorted by frequency, highest
frequency first. Where two vowels are equally frequent, they are to be displayed in alphabetical order.
As you can see from the examples below, upper case and lower case letters are considered to be the same
letter in this problem. Use lower case in your output. As you can see from the second example, a frequency
of zero must still be displayed.
Input
Each piece of text to be analysed is on a separate line of the input file. Each line has at most 200 characters.
A single # on a line indicates the end of input.
Output
Output for a problem must be on a single line. Each vowel must be output in lower case, followed by a
colon, followed by the frequency of that vowel. There must be one space before the next letter, and a dot
at the end.
SAMPLE INPUT:
This piece of text was written in the city of Auckland.
ACM Programming Contest.
#

SAMPLE OUTPUT:
e:5 i:5 a:3 o:2 u:1.
a:2 o:2 e:1 i:1 u:0.

14.Problem: The Double Helix


Two finite, strictly increasing, integer sequences are given. Any common integer
between the two sequences constitute an intersection point. Take for example the
following two sequences where intersection points are printed in bold:
First = 3 5 7 9 20 25 30 40 55 56 57 60 62
Second= 1 4 7 11 14 25 44 47 55 57 100
You can walk over these two sequences in the following way:
You may start at the beginning of any of the two sequences. Now start moving
forward.
At each intersection point, you have the choice of either continuing with the
same sequence youre currently on, or switching to the other sequence.
The objective is finding a path that produces the maximum sum of data you walked
over. In the above example, the largest possible sum is 450 which is the result of
adding 3, 5, 7, 9, 20, 25, 44, 47, 55, 56, 57, 60, and 62.
Input
Your program will be tested on a number of test cases. Each test case will be
specified on two separate lines. Each line denotes a sequence and is specified
using the following format: n v1 v2 . . . vn Where n is the length of the sequence
and vi is the ith element in that sequence. Each sequence will have at least one
element but no more than 10, 000. All elements are between -10, 000 and 10,
000 (inclusive). The last line of the input includes a single zero, which is not part
of the test cases.
Output
For each test case, write on a separate line, the largest possible sum that can be produced.
Sample Input
13 3 5 7 9 20 25 30 40 55 56 57 60 62
11 1 4 7 11 14 25 44 47 55 57 100
4 -5 100 1000 1005
3 -12 1000 1001
0

Sample Output
450
2100

15.Problem: Still Johnny Cant Add


One way for young children in elementary schools to practice addition is to make them write down an
addition table. An addition table of size N is an (N + 1) (N + 1) square matrix, where the top row and the
left column are labeled with some random integers, (except for their intersection cell where we normally put
the plus sign.) The childs task is now to put in each cell the result of adding the label of the row, and the
label of the column. For example, the table on the right is an addition table of size 3.

Once students grow up and enter intermediate-level schools, we can give them the opposite. Give them an
N N table, and let them decide how to add labels for it to be a valid addition table (if it is indeed an addition
table.) Given an N N table, which does not include any labels, your job is to decide whether it is possible
to properly label it or not. Were not interested in the labels themselves, just decide if it is an addition table
or not. For example, the 2 2 table on the left is not an addition table, while the one on the right is not an
addition table, while the one on the right is.

Input
Your program will be tested on one or more test cases. The first line in the input is an integer D representing
the number of cases. The first line of each test case is an integer N, where N 10, representing the size of
the table. Following that, there will be N lines, each with N integers representing the N N table in a rowmajor format. Each number in the table is between -10, 000 and 10, 000 (inclusive).
Output
For each test case, output the result on a single line using the following format: k._result Where k is the
test case number (starting at 1,) and result is "YES" if the test case is an addition table, or "NO" if its not.
Sample Input
add.in
3
3
4 -1 6
729
1 -4 3
2
14
35
2
36
25

Sample Output
1. YES
2. NO
3. YES

16.Problem:

Tag Checker

Markup languages such as HTML use tags to highlight sections with special significance. In this way, a
sentence in boldface can be indicated thus:
<B>This is a sentence in boldface</B>
Typically every tag has an opening tag of the form <TAG> and a closing tag of the form </TAG>, so that
portions of text can be bracketed as above. Tags can then be combined to achieve more than one effect on
a particular piece of text simply by nesting them properly, for instance: <CENTER><B>This text is centred
and in boldface</B></CENTER>
Two of the most common mistakes when tagging text are:
1. getting the nesting wrong: <B><CENTER>This should be centred boldface, but the tags are
wrongly nested</B></CENTER>
2. forgetting a tag: <B><CENTER>This should be centred boldface, but there is a missing
tag</CENTER>
Write a program to check that all the tags in a given piece of text (a paragraph) are correctly nested, and
that there are no missing or extra tags. An opening tag for this problem is enclosed by angle brackets, and
contains exactly one upper case letter, for example <T>, <X>, <S>. The corresponding closing tag will be
the same letter preceded by the symbol /; for the examples above these would be </T>, </X>, </S>.
Input and Output
The input will consist of any number of paragraphs. Each paragraph will consist of a sequence of tagged
sentences, over as many lines as necessary, and terminating with a # which will not occur elsewhere in
the text. The input will never break a tag between two lines and no line will be longer than 80 characters. The
input will be terminated by an empty paragraph, i.e. a line containing only a single #.
If the paragraph is correctly tagged then output the line Correctly tagged paragraph, otherwise output a
line of the form Expected <expected> found <unexpected> where <expected> is the closing tag matching
the most recent unmatched tag and <unexpected> is the closing tag encountered. If either of these is the
end of paragraph, i.e. there is either an unmatched opening tag or no matching closing tag at the end of the
paragraph, then replace the tag or closing tag with #. These points are illustrated in the examples below
which should be followed exactly as far as spacing is concerned.
Sample Input
The following text<C><B>is centred and in boldface</B></C>#
<B>This <\g>is <B>boldface</B> in <<*> a</B> <\6>
<<d>sentence#
<B><C> This should be centred and in boldface, but the tags
are wrongly nested </B></C>#
<B>This should be in boldface, but there is an extra closing
tag</B></C>#
<B><C>This should be centred and in boldface, but there is a
missing closing tag</C>#
#

Sample Output
Correctly tagged paragraph
Correctly tagged paragraph
Expected </C> found </B>
Expected # found </C>
Expected </B> found #

17.Problem: Book Pages


For the purposes of this problem, we will assume that every page in an Acmonian book is numbered
sequentially, and that the first page is numbered 1.
How many digits would you need to use to number the pages of a 10 page book? Pages 1 to 9 would require
1 digit each (total 9), and page 10 would require 2 digits. This makes 11 digits. Similarly, a book of 34
pages would require 59 digits.
Can we work backwards? If you are told that a book requires 13 digits to number its pages, can you work
out how many pages the book has? I hope so, because that is all you have to do for this problem. Each line
in the input file represents the number of digits used in numbering a book. Your answer will be the number of
pages the book has. If the number supplied cannot possibly be valid, your answer should be Impossible!
Beware that Acmonian books can be quite large, and the number of digits required for a given Acmonian
book can reach 2 000 000 000.
Input
Each line in the input file contains a single integer, between 1 and 2000 000 000, representing a number
of digits used in numbering the pages of a book. A single # on a line indicates the end of input.
Output
Output for each input number must be on a single line. If the input value is valid,
pages in the book. Otherwise, output Impossible!
SAMPLE INPUT:
11
13
59
60
1999999998
#

output the number of

SAMPLE OUTPUT:
10
11
34
Impossible!
234567900

18.Problem: Heliport
In these fast-paced times, companies are investing in heliports to reduce travel time for their busy
executives. The heliports are typically circular landing pads, constructed on the roofs of the companies
headquarters.
You must write a program that finds the largest radius for a circular heliport that can be constructed on the
flat roof of a building that is in the form of a simple polygon. Since this is merely the design phase of the
construction effort, your program must find only the radius of the heliport. The maximum radius for a heliport
in the diagram shown is 10.

Input
The input file contains several test cases. Each test case consists of two lines. The first line consists of an
even integer n (4 n 20), which is the number of the sides of the building. The second line consists of n
pairs of the form (m, d), where m is an integer (1 m 50) and d is a letter (U, R, D, L). Assuming the roof is
drawn on the Cartesian plane, m is the length of a roof boundary segment and d is the direction of that
segment as you travel counterclockwise around the roof. U, R, D, and L mean Up, Right, Down, and
Left respectively. The boundary segments of the roof, which are parallel to the x and y axes, are given in
counterclockwise order. The starting position is the origin (0, 0).
Input for the last test case is followed by a line consisting of the number 0.
Output
For each test case, the output consists of a separate line containing the case number (starting with 1) and a
real number (rounded to two digits after the decimal point) representing the radius of the heliport. Print a
blank line between cases as shown in the sample output.
Sample Input
4
2R2U2L2D
10
10 R 10 U 10 L 10 U 10 R 5 U 30 L 20 D 20 R 5 D
0

Sample Output
Case Number 1 radius is: 1.00
Case Number 2 radius is: 10.00

19.Problem: Q
You've got a queue. And you just got to mess with it.
Given a queue of items and a series of queue operations, return the resulting queue.
Queue operations are defined as follows:
starting-position to requested-position
meaning one wants the item at the starting position to be moved to the requested position. So if the queue
of items were:
Item1 Item2 Item3 Item4 Item5
(Item1 being in position 1, Item2 in position 2, etc.)
after applying the queue operation:
5 to 2 the resulting queue would be:
Item1 Item5 Item2 Item3 Item4
as Item5 (the item in position 5) was moved to position 2. Multiple queue operations are applied at the same
time, however; e.g., given the queue of items:
Item1 Item2 Item3 Item4 Item5 Item6 Item7 Item8
If the following queue operations were applied:
2 to 6; 6 to 3; 4 to 5; 5 to 2; 7 to 4; 8 to 1 then the resulting queue would be:
Item8 Item5 Item6 Item7 Item4 Item2 Item1 Item3
As you can see, the queue operations are strictly enforced, with other items (not involved in queue
operations) maintaining their order and moving to vacant positions in the queue. Note that no two queue
operations will have the same starting-position or same requested-position defined.
Input
Input to this problem will begin with a line containing a single integer x indicating the number of datasets.
Each data set consists of three components:
1Start line A single line, "m n" (1 <= m, n <= 20) where m indicates the number of items in the queue and n
indicates the number of queue operations.
2Queue items A line of short (between 1 and 8 characters) alphanumeric names for the items in the queue.
Names are unique for a given data set and contain no whitespace.
3Queue operations n lines of queue operations in the format "starting-position requested position".
Output
For each dataset, output the queue after the queue operations have been applied. Print the elements of the
queue on a single line, starting from the first and ending with the last, with a single space separating each
item.
Sample Input

Sample Output

35
1
alpha beta gamma delta epsilon
52
86
abcdefgh
26
63
45
52
74
81
32
foo bar baz
31
13

alpha epsilon beta gamma delta


hefgdbac
baz bar foo

20.Problem: Intriguing Player Chain


Players in the Hermes sports complex are wearing jerseys imprinted with natural numbers. There are even
number of players. During their practice session they were asked to form a circular chain. The players have
done so but with a mathematical charm. The instructor Mr. Ramanujan, after taking a round around the
player chain, noticed that the sum of any two adjacent jerseys had an interesting property (adjacency
constraint). That number is divisible by itself and one only. This found to be true both in a clockwise or in an
anticlockwise direction. A 6 player ring is illustrated below.

Your job is to automate Mr. Ramanujans brain to see all possible such patterns, given any n (Maximum
value of n is 16). Captain has jersey #1 and hence obviously the point of beginning. Print all possible
formations in ascending numeric ordering e.g. 1 2 5 comes before 1 2 6. Every formation must begin with
captains jersey number. Give priority to clockwise formations i.e. print patterns in clockwise direction and
then all patterns of anticlockwise direction. There are no missing numbers on the jerseys. E.g. if the number
of players is 6, the jerseys are numbered 1, 26.
Input
The first line of the input represents the number of test cases k (at most 5).
The next k lines represent the number of players n (0 < n <= 16).
Output
The output format is shown as sample below. Each row represents a possible formation satisfying the above
adjacency constraint. For each test case, the first line should be the test case number followed by the
arranged patterns, one pattern per row. There should be an empty line separating each test case.
Example Input:

2
6
8

Example Output:
1
143256
165234
2
12385674
12583476
14765832
16743852

21.Problem: Team Arrangement


Barry Bennett, the coach of the Bings football team, wants to arrange his team for an important match
against the Bangs. He decides on the formation he wants to play, for example 4-4-2, meaning that there will
be four defenders, four midfielders, and two strikers (and of course, one goalkeeper). Your task is to
determine the players who will play. For each available player, we know his role (e.g. midfielder). For each
role, the players are selected in ascending order of their numbers. When the players are selected, you must
determine the captain too, who is the player with the longest record in the team play. In case two players
have the same record, the one with bigger number is chosen. Note that the captain is chosen among the
players that are selected in the arrange.
Input
The input consists of multiple test cases. The first 22 lines of each test case contain the data for the 22
available players in this format:
number name role year1year'1 year2year'2 ...
number is the player number (unique positive integer less than 100). name is a string of at most 20 letters.
role is a single character among G, D, M, S, for goalkeeper, defender, midfielder, and striker respectively.
Each yeari year'i pair (yeari year'i) shows the player has been a member of the team between the
specified years (inclusive). The years are in four-digit format. There is at least one and at most 20 such pairs,
and the same year is not repeated more than once in the list. There is a 23rd line describing the desired
formation, like 4-4-2 in that format. Note that there are only three numbers in the formation (so, 4-3-2-1 is not
valid), none of them is zero, and their sum is always 10. The input is terminated by a line containing a single
0.
Output
For each test case, output a list of 11 players chosen in the arrange. Each line must contain the player
number, his name and his role, separated by single blank characters. The players must be sorted according
to their role, in the order of goalkeeper, defenders, midfielders, and strikers. The players with the same role
are sorted according to ascending order of their numbers. There is an exception that the captain always
comes as the first player in the entire list. If it is not possible to arrange the team conforming to the desired
formation, write a single line containing IMPOSSIBLE TO ARRANGE in the output. There should be a blank
line after the output for each test case.

Sample Input

Sample Output

9 PlayerA M 2000-2001 2003-2006


2 PlayerB M 2004-2006
10 PlayerC D 2001-2005
1 PlayerD D 2000-2001 2002-2004
11 PlayerE S 2003-2006
8 PlayerF M 2005-2006
22 PlayerG S 2005-2006
25 PlayerH G 2000-2001 2002-2003 2005-2006
6 PlayerI D 2003-2006
26 PlayerJ D 2003-2004 2000-2001
18 PlayerK M 2003-2004
19 PlayerL M 2000-2001 2003-2006
7 PlayerM S 2003-2006 1999-2001
21 PlayerN S 2003-2006
13 PlayerO S 2005-2006
15 PlayerP G 2001-2006
14 PlayerQ D 2003-2004
5 PlayerR S 2000-2005
20 PlayerS G 2000-2002 2003-2003
12 PlayerT M 2004-2005
3 PlayerU D 2000-2005
4 PlayerV M 2001-2004

7 PlayerM S
15 PlayerP G
1 PlayerD D
3 PlayerU D
6 PlayerI D
10 PlayerC D
2 PlayerB M
4 PlayerV M
8 PlayerF M
9 PlayerA M
5 PlayerR S

4-4-2
0

22.Problem: Barbara Bennett's Wild Numbers


A wild number is a string containing digits and question marks (like 36?1?8). A number X matches a wild
number W if they have the same length, and every non-question mark character in X is equal to the
character in the same position in W (it means that you can replace a question mark with any digit). For
example, 365198 matches the wild number 36?1?8, but 360199, 361028, or 36128 does not. Write a
program that reads a wild number W and a number X from input, both of length n, and determines the
number of n-digit numbers that match W and are greater than X.
Input
There are multiple test cases in the input. Each test case consists of two lines of the same length. The first
line contains a wild number W, and the second line contains an integer number X. The length of input lines is
between 1 and 10 characters. The last line of input contains a single character #.
Output
For each test case, write a single line containing the number of n-digit numbers matching W and greater than
X (n is the length of W and X).
Sample Input
36?1?8
236428
8?3
910
?
5
#

Sample Output
100
0
4

23.Problem: Digital Clock


Digital clocks usually show the time in the form hh:mm:ss, where hh is a number between 00 and 23, and
both mm and ss are numbers between 00 and 59. Removing the colons from hh:mm:ss will result in an
integer hhmmss, which is called a clock integer. For example, the clock integer of 17:05:13 is 170513 and
the clock integer of 00:07:37 is 737.
You are given a time interval and you are to determine the
number of clock integers in it that are multiples of 3. A time
interval will be given by specifying its start and end time. For
example, the time interval [00:59:58, 01:01:24] has a total of
1+1+60+25=87 clock integers, namely, 5958, 5959, 10000
through 10059, and 10100 through 10124. How many of them
are multiples of 3?
Note that a time interval that includes midnight may have a
start time greater than its end time, as in [22:47:03, 01:03:24].
You may assume that a time interval is at least one second
long and shorter than 24 hours.
Write a program that can determine the number of multiples of 3 in a time interval.
Input
Your program is to read from standard input. The input consists of Ttest cases. The number of test cases T
is given in the first line of the input. Each test case consists of a single line that contains the start time and
end time of a time interval, which are separated by a single space.
Output
Your program is to write to standard output. Each test case outputs exactly one line. Print the number of
multiples of 3 among the clock integers in the time interval.
The following shows a sample input with three test cases and its output.
Sample Input

Sample Output

3
00:59:58 01:01:24
22:47:03 01:03:24
00:00:09 00:03:37

29
2727
70

24.Problem: Rounders
For a given number, if greater than ten, round it to the nearest ten, then (if that result is greater than 100)
take the result and round it to the nearest hundred, then (if that result is greater than 1000) take that number
and round it to the nearest thousand, and so on ...
Input
Input to this problem will begin with a line containing a single integer n indicating the number of integers to
round. The next n lines each contain a single integer x (0 <= x <= 99999999).
Output
For each integer in the input, display the rounded integer on its own line.
Note: Round up on fives.

Sample Input:

Sample Output

91
5
14
459
9
12345678
44444445
1445
446

20
10
451
00
10000000
50000000
2000
500

25.Problem: Caterpillar
An undirected graph is called a caterpillar if it is connected, has no cycles, and there is a path in the
graph where every node is either on this path or a neighbor of a node on the path. This path is called
the spine of the caterpillar and the spine may not be unique. You are simply going to check graphs to
see if they are caterpillars.
For example, the left graph below is not a caterpillar, but the right graph is. One possible spine is
shown by dots.

Input
There will be multiple test cases. Each test case starts with a line containing n indicating the number of
nodes, numbered 1 through n (a value of n = 0 indicates end-of-input). The next line will contain an integer e
indicating the number of edges. Starting on the following line will be e pairs n1 n2 indicating an undirected
edge between nodes n1 and n2. This information may span multiple lines. You may assume that n <= 100
and e <= 300. Do not assume that the graphs in the test cases are connected or acyclic.
Output
For each test case generate one line of output. This line should either be
Graph g is a caterpillar.
or
Graph g is not a caterpillar.
as appropriate, where g is the number of the graph, starting at 1.
Sample Input

Sample Output

22
21
1 2 2 3 2 4 2 5 2 6 6 7 6 10 10 8 9 10 10 12 11 12 12
13 12 17
18 17 15 17 15 14 16 15 17 20 20 21 20 22 20 19
16
15
1 2 2 3 5 2 4 2 2 6 6 7 6 8 6 9 9 10 10 12 10 11 10 14
10 13 13 16 13 15
0

Graph 1 is not a caterpillar.


Graph 2 is a caterpillar.

26.Problem: Hie with the Pie


The Pizazz Pizzeria prides itself in delivering pizzas to its customers as fast as possible. Unfortunately, due
to cutbacks, they can afford to hire only one driver to do the deliveries. He will wait for 1 or more (up to 10)
orders to be processed before he starts any deliveries. Needless to say, he would like to take the shortest
route in delivering these goodies and returning to the pizzeria, even if it means passing the same location(s)
or the pizzeria more than once on the way. He has commissioned you to write a program to help him.
Input
Input will consist of multiple test cases. The first line will contain a single integer n indicating the number of
orders to deliver, where 1 <= n <= 10. After this will be n + 1 lines each containing n + 1
integers indicating the times to travel between the pizzeria (numbered 0) and the n locations (numbers 1 to
n). The jth value on the ith line indicates the time to go directly from location i to location j without visiting any
other locations along the way. Note that there may be quicker ways to go from i to j via other locations, due
to different speed limits, traffic lights, etc. Also, the time values may not be symmetric, i.e., the time to go
directly from location i to j may not be the same as the time to go directly from location j to i. An input value of
n = 0 will terminate input.
Output
For each test case, you should output a single number indicating the minimum time to deliver all of the
pizzas and return to the pizzeria.
Sample Input

Sample Output

3
0 1 10 10
1012
10 1 0 10
10 2 10 0
0

27.Problem: Mahershalalhashbaz, Nebuchadnezzar, and Billy Bob Benjamin Go to the Regionals


The Association for Computing Machinery (ACM) is considering new rules for its regional programming
contests, in part to solve some software problems. For instance, the program that prints out the badges for
each team was designed so that the same font size is used to print all badges for that team. However, this
means that if one member of the team has a very long name, then a very small font will be used to print all of
the teams badges, and this wouldnt look very nice for someone with an extremely short name like AL.
The initial solution proposed by the ACM was to put a limit on the length of contestants names.
Someone pointed out that this would discriminate against teams from certain regions where bigger
names are more common (for instance, children in the home towns of well-known actors are more likely to
be named after that actor imagine how many children in Oakland, California have been named after the
actor Mahershalalhashbaz Ali since he became one of the stars of the television series The 4400).
As a compromise, the ACM decided to change the rule to require that no team members name can have
length more than two away from the average length of all the team members names. Using this rule, a team
consisting of MAHERSHALALHASHBAZ, AL, and BILL would be disqualified (average name length is 8,
so AL and BILL are not within 2). However, MAHERSHALALHASHBAZ,
NEBUCHADNEZZAR, and BILLYBOBBENJAMIN would be okay (average name length is 16,
and all team member names have length within 2 of this number).
Given the names of n students, determine whether or not they can be placed into teams of k members
each so that each team meets the requirements of the new ACM rule.
Input
Input will consist of multiple test cases. Each test case begins with a line consisting of two positive integers n
and k, where n <=1000, k <= 8, and n is divisible by k. Following this are n lines, each containing a single
name consisting only of upper case letters with no embedded, leading, or trailing blanks. These are the
names of the n students who need to be organized into teams of size k each. No name will exceed 80
characters. The last test case is followed by a line containing two zeros.
Output
For each test case, output the case number (starting at 1) followed by either the word yes (meaning that it
is possible to organize the students into teams of size k so that no student on that team has a name whose
length is greater than distance 2 from the average name lengths of the members on that team), or no if it is
not possible. Use the format shown in the sample output. Insert a blank line between cases.
Sample Input

Sample Output

33
MAHERSHALALHASHBAZ
AL
BILL
63
MAHERSHALALHASHBAZ
AL
NEBUCHADNEZZAR
BILL
BILLYBOBBENJAMIN
JILL
00

Case 1: no
Case 2: yes

28.Problem: The Mastermind Masters Mind


The Advancement of Collegiate Mastermind (hey, thats ACM again...weird!) is an organization which
(among other things) holds classes for college students to improve their Mastermind skills. Recall that
basic Mastermind is a two-player game which works as follows: The first player the codemaker creates a
secret 4-color code, each color taken from one of six colors (well use A,B,C,D,E and F for the colors). The
other player the codebreaker now must try to guess the codemakers code. After each guess, the
codemaker uses black and white pegs to tell the codebreaker two things: the number of correct colors in the
correct positions (the black pegs), and the number of remaining correct colors that are in the wrong positions
(the white pegs). For example, if the true code is ABCC, and the codebreaker makes the guess ACCD, then
the response would be 2 black and 1 white; if the guess was CCAA, the response would be 3 white. The
codebreaker continues making guesses until he receives 4 blacks. More advanced versions of Mastermind
increase both the length of the code and the number of colors to choose from.
The ACMs master instructor is Dee Sifer, and she has a unique ability: when given a set of n guesses and
responses, she can immediately determine what the best (n+1)st guess should be. For each possible (n +
1)st guess, Dee calculates (in her head) the number of codes left for each possible response she could get
to that guess. The maximum of these numbers over all responses is called the uncertainty of the guess. The
best guess is the one with the minimum uncertainty. For example, suppose that you get to a point in a
game where youve narrowed down the answer to only three possible codes: ABBB, ABBC or ABCB. If your
next guess is ABBB, there would be two possible responses: 4 blacks (leaving 0 remaining possibilities left)
or 3 blacks (leaving 2 remaining possibilities ABBC and ABCB). However, if instead of ABBB you try
ABBC, then there are 3 possible responses: 4 blacks (leaving 0 possibilities), 3 blacks (leaving 1 possibility
ABBB) and 2 blacks and 2 whites (also leaving 1 possibility ABCB).
Thus ABBC would be a better guess in this case, since the uncertainty it leaves is 1, whereas the uncertainty
for ABBB is 2.
This is all well and good, except for one thing. You have been selected as Dees successor, and you do NOT
have Dees ability to pick the minimum uncertainty guess. Dee has been dropping hints (in code) that she
plans to retire soon, so you need a program to help you simulate her ability.
Input
Input will consist of multiple test cases. The first line of the input file will contain a single integer indicating the
number of test cases. Each test case will consist of several lines. The first line will contain three integers: l c
n, where l is the length of the code being guessed, c is the number of colors to choose from, and n is the
number of guesses made so far. These values will satisfy 1 <= l <=15, 1<= c <= 20, 0 <=n <= 10. The values
of l and c will be such that the total possible number of codes will be <= 32768.
After this will come n lines of the form
guess b w
where guess is a length-l character string specifying a guess, and b and w are the number of black and white
pegs in the response. All colors will be uppercase letters taken from the first c letters of the alphabet. For
each test case, the guesses given will limit the total number of possible solutions to <= 1500.
Output
For each test case, output a single line containing the best guess and its uncertainty. Use a single blank to
separate the guess from the uncertainty. If there is more than one guess with the same minimum uncertainty,
use the one which comes first lexicographically.
Sample Input
3
462
AABC 1 2
BEAC 0 3
461
ABCD 0 0

Sample Output
ABCD 4
AEEE 3
IBM 0

3 20 4
ABE 1 0
ROM 1 0
INK 1 0
MOB 0 2

29.Problem: Plaque Pack


The Knick Knack Plaque Shack designs plaques of unusual shapes. All the plaques are 1 inch deep, and
ave a wide variety of shapes, some of which are shown below.

Ben Fitt is one of several workers in the shipping department (part of the Knick Knack Plaque Shack
Pack, as they like to call themselves). Each day he is assigned the task of shipping all the plaques of
a certain width to the various department stores which sell them. He has at his disposal boxes with a
depth of 1 and a width equal to the plaques width. As the plaques come off the assembly line, he fits
them into the boxes one at a time. When placed in a box, each plaque will slide down until some part
of it touches the topmost plaque already in the box (or the bottom of the box if it is the first plaque).
For example, if the leftmost plaque above came off the assembly line first, followed by the middle and
then the rightmost, they would stack up one on top of the other as shown on the left. If they came off
the assembly line in reverse order, they would stack up as shown on the right.

When a plaque comes off the assembly line which will not fit into the box (i.e., it sticks up over the top), Ben
closes that box, ships it off, and starts a new box. In the above examples, the height of the boxes is only 12,
so it would take two boxes for the first ordering of plaques, but only one for the second.
During his free moments between packing plaques, Ben wonders what it would be like if hundreds of
computer programmers tried to write code to simulate this monotonous drudgery.
Input
Input will consist of multiple test cases. Each test case will start with a line containing three integers n w b,
where n indicates the number of plaques to ship, w indicates the width of each plaque, and b indicates the
height of each shipping box. These values will lie in the ranges 1 . . . 100, 1 . . . 10 and 1 . . . 100,
respectively. Following this line will be n specifications of plaque shapes. Each shape specification starts with
a single line containing the integer height h of the plaque (1 <= h <= 10 and h <= b). Following this will be h
lines containing w characters each, where each character is either X (indicating a part of the plaque ) or .,
indicating empty space. The order in which the plaques appear in the input is the order in which they must be
packed in the boxes, and rotating or inverting the plaques is not allowed. The input file will end with the line 0
0 0.
Output
For each test case, output a single line containing the maximum height of the plaques in each box, in the
order in which they are filled.
Sample Input

Sample Output

3 5 12
5
XXXXX
.XXXX
..XXX

96
10

...XX
....X
4
XXX..
..X..
..XXX
..X..
6
X....
X....
X....
X....
X....
XXXXX
3 5 12
6
X....
X....
X....
X....
X....
XXXXX
4
XXX..
..X..
..XXX
..X..
5
XXXXX
.XXXX
..XXX
...XX
....X
000

30.Problem: Roofing It
Bill Eaves owns the Shingle Minded roofing company which is a sub-contracting firm specializing in putting
roofs on buildings. Often, Bill will receive a design for a roof from some young hot-shot architect which,
though it may have some aesthetic appeal, is totally impractical. In these cases, Bill will begin negotiations
with the architect and the client to find a simpler design. Bills only concern is that the roof be convex, to
allow rain, snow and frisbees to roll off easily. The architects main concern is that the maximum height
between his original roof and the compromise roof be as small as possible.
The clients main concern is to get out of this meeting as soon as possible and get back to watching TV.
The architects plans for the roof come in the form of a series of n points (xi, yi) specifying the outline of the
roof as seen from the side of the house. The roofs are always symmetrical, so the architect only shows the
front side of the roof (from its start at the front of the house to its peak). Once Bill gets these plans and a
decision is made on how many sections the convex roof should have, he must decide how to place the
sections so as to 1) make sure that all the original (xi, yi) points lie on or below the new roof, and 2) to
minimize the maximum vertical distance between any of the original (xi, yi) points and the new roof. All
sections must lie on at least two of the initial points specified by the architect.
An example is shown below. On the left are the initial points from the architect. The next two pictures show
an approximation of the roof using only two sections. While both of these are convex, the second of the two
is the one which minimizes the maximum distance.

Input
Input will consist of multiple test cases. Each case will begin with two positive integers n and k
(2 <= n <= 100, 1 <= k < n) indicating the number of points used in the original roof plan and the number of
sections used in the compromise roof. These will be followed by n lines each containing two floating points
numbers xi yi, specifying the n points in the roof plan. These values will be given in increasing order of x, and
the last point will be guaranteed to have the highest y value of any of the points. All values will be between
0.0 and 10000.0. The last case is followed by a line containing 0 0 which indicates end-of-input and should
not be processed.
Output
For each test case, output the maximum distance between the best compromise roof and the initial points,
rounded to the nearest thousandth.

Sample Input
62
0.0 0.0
1.0 3.0
3.0 6.0
6.0 9.0
8.0 10.0
17.0 12.0
00

Sample Output
1.500

31.Problem: Snakes on a Plane


Assume we have an nm grid of squares, each filled with either 0 or 1. A snake is a connected sequence of
grid squares which has the following properties:
1. Each snake square has a 1 in it
2. Each snake square touches exactly two other snake squares (north/south/east/west), except the first and
last square in the sequence (the head and tail of the snake)
A maximal snake is one in which we cannot add a 1 to either end without either lengthening the snake,
combining two snakes together, or violating rule 2 above.
The examples below show grids with and without maximal snakes (all empty squares have 0s in them).
Notice that the second grid does not have a maximal snake since you can add a 1 at the end of either
snake to get a larger snake.

For this problem, you will be given grids and must count the number of maximal snakes in each.
Input
Input will consist of multiple test cases. The first line of each test case will contain two positive integers n m
indicating the number of rows and columns in the grid (the maximum value of each will be 200). The next n
lines will consist of m characters (either 0 or 1) specifying the grid. The last case is followed by a line
containing 0 0 which indicates end-of-input and should not be processed.
Output
For each test case, output a single line containing the number of maximal snakes in the grid.
Sample Input
7 10
1111111110
0000000010
1100000011
1011110001
1010010001
1010010111
1110011100
7 10
1111111110
0000000010
0001010011
1011010001
1010010001
1010010111
1110011100
7 10
1011111110
0100000010
1101011011
1011010001
1010010001
1010010111
1110011100

Sample Output
1
0
3

00

32.Problem: Stake Your Claim


The designers at Gazillion Games Inc. have come up with a new, relatively simple game called Stake Your
Claim. Two players 0 and 1 initially select two values n and m and an nn board is created with m 0s
and m 1s randomly placed on the board. Starting with player 0, each player puts his/her number in one of
the empty squares on the board. After the board is filled, each players score is equal to the largest
connected region on the board filled with that players number (where a connected region is one where for
any two squares in the region a path exists consisting of only N/S/E/W moves). The player with the highest
score wins, and is awarded the difference between his/her score and the score of the other player. Two
examples of finished games are shown below, with the largest connected regions for each player outlined.
Note in the second example that the two sections with 2 0s each are not connected.

In order to test how good this game is, the gang at Gazillion has hired you to write a program which can play
the game. Specifically, given any starting configuration, they would like a program to determine the best
move for the current player, i.e., the score which maximizes the points awarded to that player (or minimizes
those awarded to the players opponent).
Input
Input will consist of multiple test cases. Each test case will start with a line containing a positive integer n (<=
8) indicating the size of the board. Next will come n lines describing the current board layout (row 0 first,
followed by row 1, etc). Each of these lines will contain n characters taken from 0, 1 and ., where .
represents an empty square. The first character will be in column 0, the second in column 1, etc. The number
of 0s on the board will either be equal to the number of 1s or one greater, and there will be between 1 and
10 (inclusive) empty squares. The last case is followed by a line containing 0 which indicates end-of-input
and should not be processed.
Output
For each test case, output a single line containing two items: the coordinates of the best move for the player
and the best point total achieved by that player. In case of ties, print the move which comes first
lexicographically. Use the format shown in the sample output.

Sample Input
4
01.1
00..
.01.
...1
4
0.01
0.01
1..0
.1..

Sample Output
(1,2) 2
(2,2) -1

33.Problem: Weekend Lottery


Some people are against lotteries on moral grounds, some governments forbid lotteries, but with the advent
of Internet this popular form of gambling, which started in China and helped finance the Great Wall, is
thriving. But the odds of winning a national lottery are tiny, and therefore your college classmates decided to
organize a private lottery, with draws every Friday. The lottery is based on a popular style: a student who
wants to bet chooses C distinct numbers from 1 to K and pays US$ 1.00 (notice that traditional lotteries such
as US National Lotto use C = 6 and K = 49). On Friday during lunch C numbers (also from 1 to K) are drawn.
The student whose bet has the largest number of correct guesses receives the amount collected in the bets.
This amount is shared in case of ties and accumulates to next week if no one guessed any of the numbers
drawn.
Some of your colleagues do not believe in the laws of probability and asked you to write a program that
determines the numbers that have been drawn the fewest times considering all previous draws, so that they
can bet on those numbers.
Input
The input contains several test cases. The first line of a test case contains three integers N, C and K which
indicate respectively the number of draws that have already happened (1 <= N <= 10000), how many
numbers comprises a bet (1 <= C <= 10) and the maximum value of the numbers to be chosen in a bet (C <
K <= 100). Each of the next N lines contains C distinct integers Xi indicating the numbers drawn in each
previous contest (1 <= Xi <= K, for 1 <= i <= C). The end of input is indicated by N = C = K = 0.
The input must be read from standard input.
Output
For each test case in the input your program must write one line of output, containing the set of numbers that
have been drawn the fewest times. This set must be printed as a list, in increasing order of numbers. Leave
one blank space between two consecutive numbers in the list.
The output must be written to standard output.
Sample input
546
6234
3465
2365
4526
2364
434
321
214
432
143
000

Sample Output
1
1234

34.Problem: Lazy Jumping Frog


Mr. Frog lives in a grid-like marsh of rectangular shape, composed of equally-sized cells, some of which are
dry, some of which are only watery places. Mr. Frog lives in a dry cell and can jump only from a dry cell to
another dry cell on his wanderings around the marsh. Mr. Frog wants to visit his girlfriend, Ms. Toad, who
also lives in a dry cell in the same marsh. But Mr. Frog is lazy, and wants to spend the minimum amount of
energy in his jumping way to Ms. Toads home. Mr. Frog knows how much energy he spends in any of his
jumps. For any single jump, Mr. Frog always uses the following figure to determine which are the possible
target cells from his current position (the cell marked F), and the corresponding energy spent in the jump, in
calories. Any other cell is unreachable from Mr. Frogs current position with a single jump.

Your task is to determine the minimum amount of energy that Mr. Frog needs to spend to get from his home
to Ms. Toads home.
Input
The input contains several test cases. The first line of a test case contains two integers, C and R, indicating
respectively the number of columns and rows of the marsh (1 <= C,R <= 1000). The second line of a test
case contains four integers Cf , Rf , Ct, and Rt, where (Cf ,Rf ) specify Mr. Frogs home location and (Ct,Rt)
specify Ms. Toads home location (1 <= Cf ,Ct <= C and 1 <= Rf ,Rt <= R). The third line of a test case
contains an integer W (0 <= W <= 1000) indicating the number of watery places in the marsh. Each of the
next W lines contains four integers C1, R1, C2, and R2 (1 <= C1 <= C2 <= C and 1 <= R1 <= R2 <= R)
describing a rectangular watery place comprising cells whose coordinates (x, y) are so that C1 <= x <= C2
and R1 <= y <= R2. The end of input is indicated by C = R = 0.
The input must be read from standard input.
Output
For each test case in the input, your program must produce one line of output, containing the minimum
calories consumed by Mr. Frog to go from his home location to Ms. Toads home location. If there is no way
Mr. Frog can get to Ms. Toads home, your program should output impossible.
The output must be written to standard output.
Sample input
44
1142
2
2133
4344
44
1142
1
2134
76
4276
5
4171

Sample Output
14
impossible
12

5155
2434
7575
6666
00

35.Problem: Jukebox
The ICPC judges are preparing a party for the opening ceremony. For the party, they intend to add a playlist
with some songs to the jukebox software (a simple MP3 player). However, there are so many songs in the
computer that it is difficult to find the ones they want to add.
As a consequence, they need to use the search feature many times.
In this jukebox, when you search for a string s, the software returns every music whose title or artist name
contains s as a substring. String s is a substring of string t if t contains all characters of s as a contiguous
sequence (for example, bc is a substring of abcd, but ac is not). To save their precious time, while looking
for a song, they always use one of the songs golden string, i.e. one of the shortest strings for which the
search returns as a result only the song they want.

In the example above, a possible golden string for the song johnnatan is ta. Note that ta is not a substring
of the name of another song nor a substring of the artist of another song. Note also that there is no string of
size equal to 1 that could identify uniquely the song johnnatan.

They discovered that if they remove the artist fields from some of the songs they can get even smaller
golden strings. For the song john, there is no golden string. However, if one removes the artist field from all
other songs, the string c becomes the golden string for the song john.
Given the song list (each song with name and artist), your job is to determine the minimum sum of the golden
string sizes for all songs that can be obtained if one is allowed to remove some of the artist fields. In the
figure above you can see a possible best result with the golden strings in bold. The minimum sum of the
golden string sizes in this case is 10.

Input
The input contains several test cases. The first line of each test case contains one integer N (1 <= N <= 30),
which indicates the number of songs. Following there will be N pairs of lines (2 <= N lines), one pair for each
song. The first line of a pair will contain the song name, the second line will contain the artist name. Both
artist and song names are strings containing only lower case letters or underlines and having at least 1 and
at most 30 characters. There will be at most 6 different artists in the list. The end of the input is given by N =
0.
The input must be read from standard input.
Output
For each test case your program must output one single line with the minimum sum of the golden string
sizes. You may assume that there will always be a solution.
The output must be written to standard output.
Sample input
8
a_flor
los_hermanos
anna_julia
los_hermanos
quem_sabe
los_hermanos
pierrot
los_hermanos
azedume
los_hermanos
johnny
massacration
johnnatan
massacration
john
massacration
4
c
axc
b
axc
d
cc
xc
cc
0

Sample Output
10
5

36.Problem: Bubble Maps


Bubble Inc. is developing a new technology for browsing a map at different zoom levels. Their new
technology assumes that the region to be mapped is a rectangular plane surface and it divides this surface in
rectangular sub-regions, which represent deeper zoom levels. Bubble Inc. technology represents maps using
a structure known as quad-tree. In a quadtree, a rectangular region named x may be divided in half, both
horizontally and vertically, resulting in four equal-sized rectangular sub-regions. Those sub-regions are called
child regions of x, and are named xp for the top-left, xq for the top-right, xr for the bottom-right and xs for the
bottom-left regions, where xc represents the concatenation of string x and character c = p, q, r or s. For
example, if the base region to be mapped is called m, the child regions of m are, from top-left in clockwise
order: mp, mq, mr and ms, as illustrated below.

Any region can be further subdivided. For example, the region named ms can be further divided into subregions msp, msq, msr and mss, as illustrated below.

As another example, the figure below shows the result of subdividing the child sub-regions of the region
named msr.

Sub-regions with names of the same length have the same zoom level, since they represent regions of the
same size. Sub-regions in the same zoom level that share a common side are said to be neighbors.
Anything that lies outside the base region m is not mapped and, for every zoom level, all sub-regions of m
are mapped.
Bubbles map technology provides a way for the user to navigate from a given sub-region to neighboring
sub-regions in the directions up, down, left and right. You mission is to help Bubble Inc. in finding the
neighboring sub-regions of a given sub-region. That is, given the name of a rectangular sub-region, you must
determine the names of its four neighboring sub-regions.
Input
The input contains several test cases. The first line contains one integer N indicating the number of test
cases. Each of the following N lines represents a test case, containing the name of a region composed by C
characters (2 <= C <= 5000), the first always being the letter m and the following being either p, q, r or
s.
The input must be read from standard input.
Output
For each test case in the input your program must produce one line of output, containing the names of the
four neighboring regions of the given region in the order of direction up, down, left, right. For the neighbors
that are not mapped you should output <none> instead of its name. Leave one blank space between two
consecutive names.
The output must be written to standard output.
Sample input

Sample Output

2
mrspr
mps

mrspq mrssq mrsps mrsqs


mpp msp <none> mpr

37.Problem: Onion Layers


Dr. Kabal, a well recognized biologist, has recently discovered a liquid that is capable of curing the most
advanced diseases. The liquid is extracted from a very rare onion that can be found in a country called
Onionland. But not all onions of Onionland are worth to take to the lab for processing. Only those onions with
an odd number of layers contain the miraculous liquid. Quite an odd discovery!

Dr. Kabal has hired a lot of research assistants to collect and analyse onions for him. Since he does not want
to share his discovery with the world yet, he didnt tell the assistants to look for onions with an odd number of
layers. Instead, each assistant was given the task of collecting onions, and selecting points from each of the
layers outer borders, so that an approximation of the layer structure of the onion can be reconstructed later.
Dr. Kabal told the assistants that the next step will be a complicated analysis of these points. In fact, all he
will do is simply to use the points to count the number of layers in each of the onions, and select the ones
with an odd number of layers.

It is clear that the approximation obtained by Dr. Kabal, from the points collected, might have a different
shape than the original onion. For instance, only some of the points of the onion shown in Figure 1 would be
extracted in the process, giving rise to a set of points as shown in Figure 2. With these points Dr. Kabal will
try to approximate the original layers of the onion, obtaining something like what is shown in Figure 3. The
approximation procedure followed by Dr. Kabal (whose result is shown in Figure 3) is simply to recursively
find nested convex polygons such that at the end every point belongs to precisely one of the polygons. The
assistants have been told to select points in such a way that the number of layers in the approximation, if
done in this recursive manner, will be the same as in the original onion, so that is fine with Dr. Kabal. The
assistants are also aware that they need at least three points to approximate a layer, even the innermost
one.

Your task is to write a program that, given a set of points collected by an assistant (as shown in Figure 2),
determines if the respective onion should be taken to the laboratory.
Input
The input contains several test cases. Each test case consists of an integer 3 <= N <= 2000 in a single line,
indicating the number of points collected by the assistants. Following, there are N lines, each containing two
integers 2000 <= X, Y <= 2000 corresponding to the coordinates of each point. The input is finished by a
problem with N = 0 points, which should not be processed.
The input must be read from standard input.
Output
There should be one line of output for each test case in the input. For each test case print the
String Take this onion to the lab! if the onion should be taken to the laboratory or Do not take this onion to
the lab! if the onion should not be taken to the laboratory.
The output must be written to standard output.
Sample input
7
00
08
16
31
66
80
88
11
26
32
66
00
0 11
11
19
71
79
8 10
80
0

Sample Output
Do not take this onion to the lab!
Take this onion to the lab!

38.Problem: Odd or Even


There are several versions of Odd or Even, a game played by competitors to decide random issues (such as
who will code this problem?). In one of the versions, for two players, the game starts with each player
calling either odds or evens. Then they count to three (some people chant Once, twice, three, SHOOT!).
On three, both players hold out one of their hands, showing a number of fingers (from zero to five). If the
fingers add to an even number, then the person who called evens wins. If the fingers add to an odd number,
then the person who called odds wins.
John and Mary played several games of Odd or Even. In every game John chose odds (and, consequently,
Mary chose evens). During the games each player wrote down, in small cards, how many fingers he/she
showed, using one card for each game Mary used blue cards, John used red cards. Their objective was to
be able to re-check the results later, looking at the cards for each game. However, at the end of the day John
dropped the deck of cards, and although they could separate the cards by color, they are now out of order.
Given the set of numbers written on red cards and on blue cards, you must write a program to determine the
minimum number of games that Mary certainly won.
Input
The input contains several test cases. The first line of a test case contains an integer N representing the
number of games played (1 <= N <= 100). The second line of a test case contains N integers Xi, indicating
the number of fingers shown by Mary in each of the games (0 <= Xi <= 5, for 1 <= i <=N). The third line of a
test case contains N integers Yi, indicating the number of fingers shown by John in each of the games (0 <=
Yi <= 5, for 1 <= i <= N). The end of input is indicated by N = 0.
The input must be read from standard input.
Output
For each test case your program must write one line, containing one integer, indicating the minimum number
of games that Mary certainly won. The output must be written to standard output.
Sample input
3
104
312
9
022421204
123450123
0

Sample Output
0
3

39.Problem: Power Generation


Demand for electricity grew rapidly in the country over recent years, and is projected to grow even faster in
the next twenty years. To cope with this increase in demand, the government is planning to privatize the
countrys electricity power-generation sector, ending the monopoly of the state-owned company, ICPC
(Independent Circuit Power Corporation).
ICPC owns a set of power-generation plants (hydroelectric and nuclear). ICPCs plants are connected by
power lines that cross the country. Each power line connects two distinct power plants and is constructed in
a straight line. A power path is a sequence of power lines l1, l2, . . . , lm, with each power line li connecting
directly plants pi1 and pi, such that any two consecutive power lines li and li+1 are linked to a common
power plant pi.
Power plants were built over several years, one at a time, due to budget restrictions. Also due to budget
restrictions, every time a new power plant was built, only one new power line was constructed to integrate
the new plant to the existing ICPC system. The new power line always linked the newly built power plant to
the nearest power plant already in the system. If more than one such plant existed (that is, if more than one
plant was located at a minimum distance from the new plant), the oldest plant was chosen.
In the privatization project, the aim is to break up the ICPC power-generation system into smaller companies,
each company owning a set of power plants (each power plant will be owned by only one company). After
the privatization, ICPC will cease to exist; only the new companies will own the power plants. The division of
power plants among new companies must obey the following restrictions:
the total capacity of every new company must be at least C, where C is a value in MW (Mega Watts)
decided by the government. The total capacity of a set of power plants is the sum of capacities of those
plants;
power paths between any two plants owned by a new company must include only plants owned by that
company.
You have been hired by ICPC to determine which is the largest number of new companies that can be
created in the privatization process.
Input
The input contains several test cases. The first line of a test case contains two integers N and C indicating
respectively the total number of power plants owned by ICPC (1 <= N <= 10000) and the minimum total
capacity, in MW, that every new company must have (1 <= C <= 10000). Power plants are identified by
integers from 1 to N; plant 1 was the first to be built, plant 2 the second to be built, and so on. Each of the
next N lines describes a power plant; the first line describes power plant 1, the second line describes power
plant 2, and so on. Each description consists of three integers X, Y and P, where (X, Y ) is the plant location
(0 <= X <= 1000 and 0 <= Y <= 1000) and P is the plant capacity (1 <= P <= 1000). Plants were built at
different locations (that is, no two plants have the same location). The end of input is indicated by N = C = 0.
The input must be read from standard input.
Output
For each test case in the input your program must produce one line of output, containing only
one integer: the largest number of new companies that can be created in the privatization
process. The output must be written to standard output.
Sample input
2 22
0 0 20
10 20 30
4 430
10 20 100
20 10 400
50 10 50
25 25 500
3 100
10 10 33

Sample Output
1
2
0

0 10 33
10 0 33
00

40.Problem:

Report Recovery

At the end of the week, John asked Mary to send him an urgent sales report. Mary was in a hurry because
she was leaving for her holiday. She then copy-pasted the sales sheet on an email, sent it to John and went
out. She did not want to be annoyed with work issues, so she left without telling anyone where she would be.
She announced that she would be simply not available for the next two weeks, turned off her cell phone, and
left.
When John received the message he realized that the report had no spaces at all! He knew that the report
should have a header line with product codes of the form P1, P2, . . ., PN and the word Totals at the end.
Then there would be several lines reporting product sales for the different sellers of Marys office. Each seller
was identified with a name composed by one word (only alphabetical characters). The line corresponding to
a seller should begin with his/her name, followed by the number of sold products, according to the columns
report. The last line of the report should begin with the two letters TP followed by the totals of each column in
the report (of course, no sellers name began with the letters TP). John knew that there were no negative
numbers in the report, a zero quantity was reported with a single 0, and there were no leading zeros when
reporting a positive quantity.
At this point, John decided to reconstruct Marys report. He knew that there could be more than one possible
result, but he wanted to do it anyway with the first consistent solution that he could find (maybe he could fix
any mistakes when Mary comes back).
Could you help John with the recovering of Marys sales report?
Input
The input consists of several test cases. The first line in the input contains an integer C specifying the
number of test cases. The first line of a report is a header line, containing the product codes P1, P2, . . . PN
and the word Totals, as described above. The numbering of products in this header line is consecutive, from
1 to N, with 1 <= N <= 5. Then there are a number of lines, each representing a row of the report, as
described above. The last line of the report starts with the letters TP and have the format described above.
Consider that each seller sold less than 1000 units of each product. There are no more than 4 sellers on
each test case.
Each seller name will not exceed 10 characters (only uppercase and lowercase letters).
The input must be read from standard input.
Output
For each test case in the input your program must produce one possible Marys report. Each line of the
answer must be left aligned, with its items separated by a single space, and with no space at its end.
The output must be written to standard output.
Sample input
2
P1P2P3Totals
Amanda121100131
Charles5141772
Monique14121238
TP1862629241
P1P2Totals
Ingrid9519851936
Candid49212504
Peter10313
Camila000
TP145310002453

Sample Output
P1 P2 P3 Totals
Amanda 121 10 0 131
Charles 51 4 17 72
Monique 14 12 12 38
TP 186 26 29 241
P1 P2 Totals
Ingrid 951 985 1936
Candid 492 12 504
Peter 10 3 13
Camila 0 0 0
TP 1453 1000 2453

41.Problem: Turkish Roulette


Turkish Roulette is a betting game that uses a roulette with S slots, each one numbered with an integer
between -64 and 64. In each turn of the game players bet on B balls, each one also numbered from -64 to
64. For each of the B balls, exactly one player will bet on it.
After spinning the roulette, the dealer throws in the B balls sequentially. When the roulette stops, each ball is
lodged over two (adjacent) slots, as depicted in the figure below, which shows a roulette with thirty two slots
and four balls. Notice that, as the figure illustrates, a ball occupies the space of two adjacent slots, and
therefore there is room for at most S/2 balls in the roulette.

Balls end up lodged in the same relative positions that they were thrown in the roulette. That is, if balls a, b
and c are thrown in that sequence, they end up lodged such that, in clockwise direction, a is followed by b
which is followed by c which is followed by a. The value of a ball in a turn is calculated by multiplying the
balls number by the sum of the numbers of the two adjacent slots over which the ball is lodged. If a balls
value is positive, the player who bet on that ball receives that amount (the balls value) from the dealer; if a
balls value is negative, the player who bet on that ball must pay that amount to the dealer. The profit of the
dealer in a turn is the total amount received minus the total amount paid.
For example, in the figure above, the dealer pays $5.00 for ball numbered 1, pays $7.00 for ball numbered
7, receives $24.00 for ball numbered 12 and does not pay nor receive anything for ball numbered 3.
Therefore, in this turn the dealer makes a profit of $12.00 (24 5 7); note that the dealers profit in a turn
may be negative (loss).
You will be given the description of the roulette, the description of the balls and the sequence in which the
balls are thrown into the roulette. Write a program to determine the maximum profit that the dealer can make
in one turn.
Input
Input contains several test cases. The first line of a test case contains two integers S and B which indicate
respectively the number of slots in the roulette (3 <= S <= 250) and the number of balls used (1 <= B <=
S/2 ). The second line of a test case contains S integers Xi, indicating the numbers associated to the
roulettes slots, in clockwise direction (64 <= Xi <= 64, for 1 <= i <= S). The third line of a test case contains
B integers Yi, indicating the numbers associated to the balls (64 <= Yi <= 64, for 1 <= i <= B), in the
sequence the balls are thrown into the roulette (notice it is in this order that they end lodged in the roulette, in
clockwise direction). The end of input is indicated by S = B = 0.
The input must be read from standard input.
Output
For each test case in the input your program must write one line of output, containing an integer indicating
the maximum profit the dealer can make in one turn.
The output must be written to standard output.
Sample input
42
-1 0 2 -1

Sample Output
4
-11

-1 1
52
3 2 -1 7 1
23
73
-4 3 2 1 0 -4 -2
-10 0 1
42
0230
-2 -2
00

56
10

42. Problem: Team Arrangement


Barry Bennett, the coach of the Bings football team, wants to arrange his team for an important match
against the Bangs. He decides on the formation he wants to play, for example 4-4-2, meaning that there will
be four defenders, four midfielders, and two strikers (and of course, one goalkeeper). Your task is to
determine the players who will play. For each available player, we know his role (e.g. midfielder). For each
role, the players are selected in ascending order of their numbers. When the players are selected, you must
determine the captain too, who is the player with the longest record in the team play. In case two players
have the same record, the one with bigger number is chosen. Note that the captain is chosen among the
players that are selected in the arrange.
Input
The input consists of multiple test cases. The first 22 lines of each test case contain the data for the 22
available players in this format:
number name role year1year'1 year2year'2 ...
number is the player number (unique positive integer less than 100). name is a string of at most 20 letters.
role is a single character among G, D, M, S, for goalkeeper, defender, midfielder, and striker respectively.
Each yeari year'i pair (yeari year'i) shows the player has been a member of the team between the
specified years (inclusive). The years are in four-digit format. There is at least one and at most 20 such pairs,
and the same year is not repeated more than once in the list. There is a 23rd line describing the desired
formation, like 4-4-2 in that format. Note that there are only three numbers in the formation (so, 4-3-2-1 is not
valid), none of them is zero, and their sum is always 10. The input is terminated by a line containing a single
0.
Output
For each test case, output a list of 11 players chosen in the arrange. Each line must contain the player
number, his name and his role, separated by single blank characters. The players must be sorted according
to their role, in the order of goalkeeper, defenders, midfielders, and strikers. The players with the same role
are sorted according to ascending order of their numbers. There is an exception that the captain always
comes as the first player in the entire list. If it is not possible to arrange the team conforming to the desired
formation, write a single line containing IMPOSSIBLE TO ARRANGE in the output. There should be a blank
line after the output for each test case.
Sample Input and Output
A.in
9 PlayerA M 2000-2001 2003-2006
2 PlayerB M 2004-2006
10 PlayerC D 2001-2005
1 PlayerD D 2000-2001 2002-2004
11 PlayerE S 2003-2006
8 PlayerF M 2005-2006
22 PlayerG S 2005-2006
25 PlayerH G 2000-2001 2002-2003 2005-2006
6 PlayerI D 2003-2006
26 PlayerJ D 2003-2004 2000-2001
18 PlayerK M 2003-2004
19 PlayerL M 2000-2001 2003-2006
7 PlayerM S 2003-2006 1999-2001
21 PlayerN S 2003-2006
13 PlayerO S 2005-2006
15 PlayerP G 2001-2006
14 PlayerQ D 2003-2004
5 PlayerR S 2000-2005
20 PlayerS G 2000-2002 2003-2003
12 PlayerT M 2004-2005
3 PlayerU D 2000-2005
4 PlayerV M 2001-2004
4-4-2

Standard Output
7 PlayerM S
15 PlayerP G
1 PlayerD D
3 PlayerU D
6 PlayerI D
10 PlayerC D
2 PlayerB M
4 PlayerV M
8 PlayerF M
9 PlayerA M
5 PlayerR S

0
43. Problem: Barbara Bennett's Wild Numbers
A wild number is a string containing digits and question marks (like 36?1?8). A number X matches a wild
number W if they have the same length, and every non-question mark character in X is equal to the
character in the same position in W (it means that you can replace a question mark with any digit). For
example, 365198 matches the wild number 36?1?8, but 360199, 361028, or 36128 does not. Write a
program that reads a wild number W and a number X from input, both of length n, and determines the
number of n-digit numbers that match W and are greater than X.
Input
There are multiple test cases in the input. Each test case consists of two lines of the same length. The first
line contains a wild number W, and the second line contains an integer number X. The length of input lines is
between 1 and 10 characters. The last line of input contains a single character #.
Output
For each test case, write a single line containing the number of n-digit numbers matching W and greater than
X (n is the length of W and X).
Sample Input and Output
B.in
36?1?8
236428
8?3
910
?
5
#

Standard Output
100
0
4

44. Problem: Calculating Taxi Fare


The rules for calculating the taxi fares are quite complex. Many factors are to be considered in computing the
taxi fares, including the length of the trip, the time of the day, the speed, etc. Every morning Bianca Bennett
uses taxi to get to her office, she thinks if taximeters are programmed correctly. One day, she decided to
write a program to calculate the taxi fares to check this.
Imagine a taxi passes through a sequence of streets S1, S2, ..., Sn in order. The length of Si is Li and it is
assumed that the taxi travels in a constant speed and it takes Mi minutes to travel one kilometer in Si. To
make it simple, assume the passenger gets in at the start of a street Si and gets out at the end of the
destination street Sj (i.e., he does not get in or out in the middle of a street). The passenger is charged for
each kilometer of the trip. The first ten kilometers of the trip cost 1000 Rials each. The next 20 kilometers
(from 11 to 30) cost 250 Rials each. After that, each kilometer costs 100 Rials.
During the night, the fare is increased by 20%. The rule is that for each kilometer, if the taxi travels at least
one minute during the time interval [12 AM, 6 AM], that kilometer will cost 20% more. Since driving in a
heavy traffic costs more, if the average speed of the taxi is less than 30 km/h during the whole trip, the fare is
increased by 10%.
Input
The input consists of multiple test cases. The first part of each test case is the sequence of streets the taxi
travels. This comes in several lines, each describing one street in the form of street-name length min. streetname is a unique string of at most 20 letters and digits with no blank in it, and length and min are two positive
integer numbers which are Li (measured in kilometers, at most 200) and Mi (measured in minutes)
respectively. Each street is visited once by the taxi. The first part of the test case is terminated by a line
containing a single $ character. The second part of the test case contains a single line of the form sourcestreet dest-street time. The first two items are the names of the source and the destination streets
respectively. The third item is the time the passenger gets in which is in standard 24-hours format (HH:MM).
There is a line containing a single # character at the end of each test case. You may assume that the source
and the destination streets belong to the input sequence of streets and the destination street does not come
before the source street. The last line of the input contains two dash characters as shown in the sample
input.
Output
For each test case, output a line containing the fare of the passenger's trip.
Sample Input and Output
C.in
Khayyam 10 35
15thKhordad 50 15
Pamenar 15 40
$
Khayyam Pamenar 07:15
#
Jenah 10 40
Nouri 50 70
Hemmat 30 25
Chamran 80 80
ValieAsr 30 20
$
Nouri ValieAsr 23:30
#
--

Standard Output
21758
36432

45. Problem: Party at Hali-Bula


Dear Contestant,
I'm going to have a party at my villa at Hali-Bula to celebrate my retirement from
BCM. I wish I could invite all my co-workers, but imagine how an employee can
enjoy a party when he finds his boss among the guests! So, I decide not to invite
both an employee and his/her boss. The organizational hierarchy at BCM is such
that nobody has more than one boss, and there is one and only one employee with
no boss at all (the Big Boss)! Can I ask you to please write a program to determine
the maximum number of guests so that no employee is invited when his/her boss
is invited too? I've attached the list of employees and the organizational hierarchy
of BCM.
Best,
--Brian Bennett
P.S. I would be very grateful if your program can indicate whether the list of people
is uniquely determined if I choose to invite the maximum number of guests with
that condition.
Input
The input consists of multiple test cases. Each test case is started with a line containing an integer n (1 n
200), the number of BCM employees. The next line contains the name of the Big Boss only. Each of the
following n-1 lines contains the name of an employee together with the name of his/her boss. All names are
strings of at least one and at most 100 letters and are separated by blanks. The last line of each test case
contains a single 0.
Output (Standard Output)
For each test case, write a single line containing a number indicating the maximum number of guests that
can be invited according to the required condition, and a word Yes or No, depending on whether the list of
guests is unique in that case.
Sample Input and Output
D.in
6
Jason
Jack Jason
Joe Jack
Jill Jason
John Jack
Jim Jill
2
Ming
Cho Ming
0

Standard Output
4 Yes
1 No

46. Problem: Against Mammoths


Back to year 3024, humans finally developed a new technology that enables them to conquer the alien
races. The new technology made it possible to produce huge spaceships known as Saber Tooth spaceships
as powerful as the aliens' defending mammoths. At that time, humans ruled several planets while some
others were under control of the aliens. Using Saber Tooth ships, humans finally defeated aliens and this
became the first Planet War in history. Our goal is to run a simulation of the ancient war to verify some
historical hypotheses.
Producing each spaceship takes an amount of time which is constant for each planet but may vary among
different planets. We call the number of spaceships each planet can produce in a year, the production rate of
that planet. Note that each planet has a number of spaceships in it initially (before the simulation starts). The
planets start producing ships when the simulation starts, so if a planet has n ships initially, and has the
production rate p, it will have n + p ships at the beginning of year 1, and n + i p ships at the beginning of
year i (years are started from zero).
Bradley Bennett, the commander in chief of the human armies, decided a strategy for the war. For each alien
planet A, he chooses a corresponding human planet P, and produces spaceships in P until a certain moment
at which he sends all spaceships in P to invade the planet A. No alien planet is invaded by two human
planets and no human planet sends its spaceships to two different alien planets.
The defense power of the alien planets comes from their powerful mammoths. Each alien planet contains a
number of mammoths initially and produces a number of mammoths each year (called the production rate of
the planet). When a fight between spaceships and mammoths takes place, the side having the greater
number of troops is the winner. If the spaceships win, the alien planet is defeated. In case the number of
mammoths and spaceships are equal, the spaceships win.
The difficulty with planning this strategy is that it takes some time for the spaceships to reach the alien
planets, and during this time, the aliens produce mammoths. The time required for spaceships to travel from
each human planet to each alien planet is known. The ships can leave their planets only at the beginning of
years (right after the ships are produced) and reach the alien planets at the beginning of years too (right after
the mammoths are produced).
As an example, consider a human planet with two initial spaceships and production rate three invading an
alien planet with two initial mammoths and production rate two. The time required to travel between the two
planets is two years and the ships are ordered to leave at year one. In this case, five ships leave the human
planet. When they reach the alien planet, they confront eight mammoths and will be defeated during the
fight.
Bennett decided to prepare a plan that destroys every alien planet in the shortest possible time. Your task is
to write a program to generate such a plan. The output is the shortest possible time (in years) in which every
alien planet is defeated.
Input
There are multiple test cases in the input. The first line of each test case contains two numbers H and A
which are the number of planets under the control of humans and aliens respectively (both between 1 and
250). The second line of the test case contains H non-negative integers n1 m1 n2 m2 nH mH. The number ni
is the initial number of Saber Tooth spaceships in the ith human planet and mi is the production rate of that
planet. The third line contains A non-negative integers which specify the initial number of mammoths and the
production rate of the alien planets in the same format as the second line. After the third line, there are H
lines each containing A positive integers. The jth number on the ith line shows how many years it takes a
spaceship to travel from the ith human planet to the jth alien planet. The last line of the input contains two zero
numbers. Every number in the input except H and A is between 0 and 40000.
Output
The output for each test case contains a single integer which is the minimum time in which all alien planets
can be defeated. If it is impossible to destroy all alien planets, the output should be IMPOSSIBLE.

Sample Input and Output


E.in
21
2303
22
2
2
00

Standard Output
6

47. Problem: Chessboard Dance


Another boring Friday afternoon, Betty the Beetle thinks how to amuse herself. She goes out of her hiding
place to take a walk around the living room in Bennett's house. Mr. and Mrs. Bennett are out to the theatre
and there is a chessboard on the table! "The best time to practice my chessboard dance," Betty thinks! She
gets so excited that she does not note that there are some pieces left on the board and starts the practice
session! She has a script showing her how to move on the chessboard. The script is a sequence like the
following example:

move 2
turn right
move 3
turn left
turn left
move 1
At each instant of time Betty, stands on a square of the chessboard, facing one of the four directions (up,
down, left, right) when the board is viewed from the above. Performing a "move n" instruction, she moves n
squares forward in her current direction. If moving n squares goes outside the board, she stays at the last
square on the board and does not go out. There are three types of turns: turn right, turn left, and turn back,
which change the direction of Betty. Note that turning does not change the position of Betty.
If Betty faces a chess piece when moving, she pushes that piece, together with all other pieces behind (a
tough beetle she is!). This may cause some pieces fall of the edge of the chessboard, but she doesn't care!
For example, in the following figure, the left board shows the initial state and the right board shows the state
after performing the script in the above example. Upper-case and lower-case letters indicate the white and
black pieces respectively. The arrow shows the position of Betty along with her direction. Note that during the
first move, the black king (r) falls off the right edge of the board!
c
p

a
p

P
P

a
p

P
P

R
P
p

You are to write a program that reads the initial state of the board as well as the practice dance script, and
writes the final state of the board after the practice.
Input
There are multiple test cases in the input. Each test case has two parts: the initial state of the board and the
script. The board comes in eight lines of eight characters. The letters r, d, t, a, c, p indicate black pieces, R,
D, T, A, C, P indicate the white pieces and the period (dot) character indicates an empty square. The square
from which Betty starts dancing is specified by one of the four characters <, >, ^, and v which also indicates
her initial direction (left, right, up, and down respectively). Note that the input is not necessarily a valid chess
game status.
The script comes immediately after the board. It consists of several lines (between 0 and 1000). In each line,
there is one instruction in one of the following formats (n is a non-negative integer number):
move n
turn left
turn right

turn back
At the end of each test case, there is a line containing a single # character. The last line of the input contains
two dash characters.
Output
The output for each test case should show the state of the board in the same format as the input. Write an
empty line in the output after each board.
Sample Input and Output
F.in
.....c..
.p..A..t
D..>T.Pr
....aP.P
p.d.C...
.....p.R
........
........
move 2
turn right
move 3
turn left
turn left
move 1
#
--

Standard Output
.....c..
.p..A..t
D.....TP
....a..P
p.d.C^..
.......R
.....P..
.....p..

48. Problem: Bribing FIPA


There is going to be a voting at FIPA (Fdration Internationale de Programmation Association) to determine
the host of the next IPWC (International Programming World Cup). Benjamin Bennett, the delegation of
Diamondland to FIPA, is trying to seek other delegations support for a vote in favor of hosting IWPC in
Diamondland. Ben is trying to buy the votes by diamond gifts. He has figured out the voting price of each and
every country. However, he knows that there is no need to diamond-bribe every country, since there are
small poor countries that take vote orders from their respected superpowers. So, if you bribe a country, you
have gained the vote of any other country under its domination (both directly and via other countries
domination). For example, if C is under domination of B, and B is under domination of A, one may get the
vote of all three countries just by bribing A. Note that no country is under domination of more than one
country, and the domination relationship makes no cycle. You are to help him, against a big diamond, by
writing a program to find out the minimum number of diamonds needed such that at least m countries vote in
favor of Diamondland. Since Diamondland is a candidate, it stands out of the voting process.
Input
The input consists of multiple test cases. Each test case starts with a line containing two integers n (1 n
200) and m (0 m n) which are the number of countries participating in the voting process, and the number
of votes Diamondland needs. The next n lines, each describing one country, are of the following form:
CountryName DiamondCount DCName1 DCName2 ...
CountryName, the name of the country, is a string of at least one and at most 100 letters and DiamondCount
is a positive integer which is the number of diamonds needed to get the vote of that country and all of the
countries that their names come in the list DCName1 DCName2 ... which means they are under direct
domination of that country. Note that it is possible that some countries do not have any other country under
domination. The end of the input is marked by a single line containing a single # character.
Output
For each test case, write a single line containing a number showing the minimum number of diamonds
needed to gain the vote of at least m countries.
Sample Input and Output
G.in
32
Aland 10
Boland 20 Aland
Coland 15
#

Standard Output
20

49. Problem: Treasure of the Chimp Island


Bob Bennett, the young adventurer, has found the map to the treasure of the Chimp Island, where the ghost
zombie pirate LeChimp, the infamous evil pirate of the Caribbeans has hidden somewhere inside the Zimbu
Memorial Monument (ZM2). ZM2 is made up of a number of corridors forming a maze. To protect the
treasure, LeChimp has placed a number of stone blocks inside the corridors to block the way to the treasure.
The map shows the hardness of each stone block which determines how long it takes to destroy the block.
ZM2 has a number of gates on the boundary from which Bob can enter the corridors. Fortunately, there may
be a pack of dynamites at some gates, so that if Bob enters from such a gate, he may take the pack with
him. Each pack has a number of dynamites that can be used to destroy the stone blocks in a much shorter
time. Once entered, Bob cannot exit ZM2 and enter again, nor can he walk on the area of other gates (so, he
cannot pick more than one pack of dynamites).
The hardness of the stone blocks is an integer between 1 and 9, showing the number of days required to
destroy the block. We neglect the time required to travel inside the corridors. Using a dynamite, Bob can
destroy a block almost immediately, so we can ignore the time required for it too. The problem is to find the
minimum time at which Bob can reach the treasure. He may choose any gate he wants to enter ZM2.
Input
The input consists of multiple test cases. Each test case contains the map of ZM2 viewed from the above.
The map is a rectangular matrix of characters. Bob can move in four directions up, down, left, and right, but
cannot move diagonally. He cannot enter a location shown by asterisk characters (*), even using all his
dynamites! The character ($) shows the location of the treasure. A digit character (between 1 and 9) shows a
stone block of hardness equal to the value of the digit. A hash sign (#) which can appear only on the
boundary of the map indicates a gate without a dynamite pack. An uppercase letter on the boundary shows a
gate with a pack of dynamites. The letter A shows there is one dynamite in the pack, B shows there are two
dynamite in the pack and so on. All other characters on the boundary of the map are asterisks. Corridors are
indicated by dots (.). There is a blank line after each test case. The width and the height of the map are at
least 3 and at most 100 characters. The last line of the input contains two dash characters (--).
Output
For each test case, write a single line containing a number showing the minimum number of days it takes
Bob to reach the treasure, if possible. If the treasure is unreachable, write IMPOSSIBLE.
Sample Input and Output
H.in
*****#*********
*.1....4..$...*
*..***..2.....*
*..2..*****..2*
*..3..******37A
*****9..56....*
*.....******..*
***CA**********

Standard Output
1
IMPOSSIBLE

*****
*$3**
*.2**
***#*
--

50. Problem: Kadj Squares


In this problem, you are given a sequence S1, S2, ..., Sn of squares of different sizes. The sides of the
squares are integer numbers. We locate the squares on the positive x-y quarter of the plane, such that their
sides make 45 degrees with x and y axes, and one of their vertices are on y=0 line. Let bi be the x
coordinates of the bottom vertex of Si. First, put S1 such that its left vertex lies on x=0. Then, put Si, (i > 1) at
minimum bi such that
a) bi > bi-1 and
b) the interior of Si does not have intersection with the interior of S1...Si-1.

y
S1
b1

S2

b2 b3

b4

S3

The goal is to find which squares are visible, either entirely or partially, when viewed from above. In the
example above, the squares S1, S2, and S4 have this property. More formally, Si is visible from above if it
contains a point p, such that no square other than Si intersect the vertical half-line drawn from p upwards.
Input
The input consists of multiple test cases. The first line of each test case is n (1 n 50), the number of
squares. The second line contains n integers between 1 to 30, where the ith number is the length of the sides
of Si. The input is terminated by a line containing a zero number.
Output
For each test case, output a single line containing the index of the visible squares in the input sequence, in
ascending order, separated by blank characters.
Sample Input and Output
I.in
4
3514
3
212
0

Standard Output
124
13

ember 11, 2006

51. Problem: Prime Tracks


For her birthday, Colleen was given a section of track in order to start a toy train set. The section
was a railroad crossing of exactly 90 but with different lengths, as shown in the figure on the left
below.

Distance d1

Distance d2

The distances d1 and d2 are specified in integral numbers of millimeters.


Since this is the only piece of track she owned, she decided to purchase additional track in order to construct a
figure eight, as shown in the figure on the right.
The top and bottom regions are 270 portions of a circle, each with a constant radius, so that the
arcs exactly line up with each respective portion of the crossing.
Colleen goes to the toy store, Mathematical Marvels, to purchase track. The reason the store is
called Mathematical Marvels, explains the owner, is that we only sell flexible track, in sections
that happen to be lengths that are prime numbers. To make matters worse, there is a track
shortage! The store only carries one track piece with each prime number length between 3 and 997.
The store charges by the piece, not the length, of track, and Colleen only has enough money for a
maximum of five sections for the top oval, and five sections for the bottom oval.
You volunteer to help Colleen by writing a program to minimize the cost of purchasing the required
train track. To do this you will determine the smallest number of primes, and their values, that give
the lengths of track sections that must be purchased in order to complete the figure eight. There
may be more than one correct set of primes for each arc, but the minimal cardinality for each set
of sections is desired. Since the track sections are flexible, a tolerance of 1 mm on each arc
distance is allowed.
Input
The input will contain multiple cases. For each case, the input will consist of two positive integers
giving the lengths d1 and d2 as described above. It is not necessarily the case that d1 is less than
d2, so the length of the top oval may be less than, equal to, or greater than the length of the
bottom oval.
There will be at least one solution for each input case.
Input for the last case will be fol owed by a pair of zeroes.

Output
For each case, display the case number (they start with 1 and increase sequentially). Then, on each
of the next two lines, display the number of segments and the prime number lengths of track (in
ascending order) to be used in constructing the oval regions of the figure 8. Because of the track
shortage these primes must all be unique. As noted above, there may be more than one correct set
of prime-length track segments, but minimizing the number of segments is required.
Separate the output for consecutive cases with a blank line. Your output should appear similar to
that shown in the sample below.
Sample Input

Output for the Sample Input

301 501
210 435
00

Case 1
3 segments: 373, 991, 997
2 segments: 499, 919
Case 2
2 segments: 7, 983
3 segments: 61, 991, 997

November 11, 2006


52. Problem: Pies
Mrs. Smith bakes apple pies. Because she makes quite a few, she wishes to optimize the process by
knowing exactly how much dough is required for each pie. Her pies are baked in tins which have
negligible thickness but which are of this general shape (side view):

Angle of
pans side
with
horizontal
surface,

Pans base, of
diameter d

Pans rim, of
width r

Two pieces of dough are required for each pie. One piece of dough is placed in the bottom of the
pan, up the inside, and out to the outside edge of the rim. The second piece of dough goes over the
top of the pie, from the outside of the rim up to a point in the center of the pie forming a perfect
cone. For clarity, note that the dough is two layers thick at the very outside edge of the rim.

Height of the top crust, h


Height of the pan, p

Given values for , d, r, p, and h (as identified in the preceding figures), determine the volume of
dough required for each pie, in cubic inches, by first calculating the necessary surface areas and
then considering the dough to be 1/8 inches thick.
Input
The input wil contain multiple cases. For each case, the input will consist of a line containing real
numbers for , d, r, p, and h. Since these are real pies, will always be in the range 10 to 80
degrees, and the values for d, r, p, and h will be positive and less than or equal to 16 inches.
Input for the last case will be fol owed by a line containing a single 1.
Output
For each case, display the case number (they start with 1 and increase sequentially), and the total
volume of crust required, in cubic inches, with three fractional digits. Separate the output for
consecutive cases with a blank line. Your output should appear similar to that shown in the sample
below.
Sample Input

Output for the Sample Input

45.0 9.0 0.5 2.0 1.0


40.0 10.0 0.5 2.5 1.25
-1

Case 1: 42.258 cubic inches


Case 2: 61.413 cubic inches

53. Problem: Segment Life


Decimal numbers can be displayed using one or more seven-segment displays. The segments are
arranged so that illuminating selected segments yields a pattern corresponding to a decimal digit.
The patterns used in this problem are show below. There are three horizontal segments (each
illustrated by two hyphens), and four vertical segments (each illustrated by a vertical stroke).

Each of the segments in a single display has an expected lifetime specified by the manufacturer.
This lifetime is the minimum cumulative time each segment is expected to be capable of being
illuminated, independent of how frequently it is turned on or off.
In normal use, a display doesnt always illuminate the same segments. That is, different digits are
displayed with different frequencies. As a result, some segments might be illuminated longer than
others, and thus the actual length of time the display can be expected to display the proper results
is dependent on the values it displays.
Given the values to be displayed, their probability of appearance, and the lifetime specified by the
manufacturer, you are to determine the minimum time the display can be expected to display the
proper values.
Multiple single-digit displays may be required, the actual number of such depending on the largest
value to be displayed. Values are displayed with leading zeroes, if necessary, to use all single-digit
displays. The displays are entirely blank (no segments illuminated) if no value is displayed.
Examples
As a simple example, suppose the manufacturer specifies a particular display as having a 100 hour
lifetime. If only the digits 0 and 1 are displayed, each with a 25 percent probability, then the
display will require only a single digit, and it will be blank 50 percent of the time. During the
remaining time, the rightmost two vertical segments will be illuminated, since they are on during
the display of 0 or 1. Given these conditions, the display will correctly operate for at least 200
hours.
Suppose the values to be displayed are 0, 1, 10, and 11, each with a probability of 25 percent. If the
display has the same manufacturer-specified lifetime, then two single-digit display units will be
required, and the display will correctly operate for at least 100 hours.
Finally, assume arbitrary decimal digits are to be displayed (with equal probability) 50 percent of
the time. With a segment lifetime of 50 hours, the display can be expected to operate correctly
for at least 111.11 hours. This is because no segment is illuminated in more than 90 percent of the
digits displayed.
Input
For this problem there are multiple cases. The input for each case begins with two integers. The
first of these is the manufacturer-specified lifetime of a display, in hours; the second is the
number of ranges of values to be displayed. For each of these ranges there follows a group of three
integers that give the lowest and highest values in the range, and the probability that one of these
values will appear. The largest value will never require a display with more than six digits. Input for
the last case is followed by a single integer 1.
Output
For each case, display the case number (starting with 1) and the minimum time (with two fractional
digits) the display will operate correctly. Leave a single blank line between the output for
consecutive cases.

Sample Input

Output for the Sample Input

100 1
0 1 50

Case 1: 200.00 hours


Case 2: 100.00 hours

100 4
0 0 25
1 1 25
10 10 25
11 11 25
100 2
0 1 50
10 11 50
50 1
0 9 50
-1

Case 3: 100.00 hours


Case 4: 111.11 hours

54. Problem 4: Grade Dropping


Welcome to Discrete Math I. Forty percent of your final grade will be based on your homework
assignments. Since everyone can have a bad day from time to time, you will be allowed to not count
up to three of these assignments, but you have to choose which assignments to drop. If all
assignments counted equally (that is, the raw scores were simply averaged together) the choice
would be easy drop the assignments with the lowest scores. However, each assignment may have a
different maximum score. The final homework grade will be the percentage ratio of your total
score to the maximum possible score for the retained assignments.
Write a program that, given a list of assignment results, will calculate the best homework
percentage grade after dropping zero, one, two, and three of the assignments.
Example
As an example, consider that you have received the following scores on each of seven
assignments, with the maximum scores as show:
Assignment
Number
1
2
3
4
5
6
7

Score
41
22
2
11
24
26
4

Maximum
Possible
42
64
26
44
27
70
30

The homework grade without dropping any assignments is calculated as follows:


(41 + 22 + 2 + 11 + 24 + 26 + 4) / (42 + 64 + 26 + 44 + 27 + 70 + 30) = 42.9%
The best result possible for dropping only one assignment is to drop assignment 3:
(41 + 22 + 11 + 24 + 26 + 4) / (42 + 64 + 44 + 27 + 70 + 30) =46.2%
Similarly it is possible to choose the second and third assignments to drop to yield the best possible
final average.
Input
There may be multiple cases. The input for each case is a series of between 4 and 30 pairs of
integers terminated by a 1. The first integer in each pair is your score on an assignment; the
second integer is the maximum possible score on that assignment. Each assignment has a maximum
possible score between 1 and 100 points, and no assignment will ever receive a negative score.
Input for the last case is followed by a single integer 1.
Output
For each case, display the case number (starting with 1) and the maximum possible homework grade
(with two fractional digits) that could be obtained by dropping zero, one, two and three
assignments. Make your output appear similar to that shown in the samples below. Leave a single
blank line between the output for consecutive cases.

Sample Input
41 42 22
64 2 26 11 44
24 27
26 70 4
30 -1
-1
Output for the Sample Input
Case 1:
Dropping no grades: 42.90
Dropping 1 grade: 46.21
Dropping 2 grades: 50.22
Dropping 3 grades: 56.80

55. Problem 5: Nested Boxes


It is a common prank to give someone a gift in a large box, in which is nested a smaller box, with
another smaller box inside that one, and so forth, until the smallest box nested within all those
other boxes contains the gift. Given a set of boxes of various sizes, your problem is to find the
size (cardinality) of the largest subset of boxes that can be used to create such a nested
arrangement. If no boxes can be nested, then the size of the subset is just 1.
Naturally, each box in the set from which you can choose has three dimensions. Any box can be
rotated, if desired, if that would enable it to fit inside another box. For our purposes, a box A can
fit inside a box B if each dimension of box A is strictly less than the corresponding dimension of
box B.
Example
For example, suppose box A has dimensions 12 20 60 and box B has dimensions 42 18 10. If
we rotate box B appropriately so the dimensions are 10 18 42, then we will be able to nest it
inside box A. However, if box B had dimensions 13 12 58, then no rotations would allow it to fit
inside box A.
Input
There may be multiple cases. The input for each case begins with a line containing a single integer,
N, that specifies the number of boxes in the set from which you are allowed to choose. This line will
be followed by N more lines, each containing three positive non-zero integers giving the dimensions
of a box. N will be no larger than 500, and no box will have a dimension larger than 999.
Input for the last case is followed by a single integer 1.
Output
For each case, display the case number (starting with 1) and the maximum number of boxes selected
from the set that can be nested as described. Make your output appear similar to that shown in the
samples below. Leave a single blank line between the output for consecutive cases.

Sample Input

Output for the Sample Input

5
145 472 812
827 133 549
381 371 900
271 389 128
718 217 491
4
432 123 139
942 844 783
481 487 577
677 581 701
-1

Case 1: 2 boxes
Case 2: 4 boxes

November 11, 2006

56. Problem 6: Conveyor Belts


The package sorting area of a shipping company consists
of an incoming bin of packages, and three conveyor
belts, A, B, and C, of varying widths. Each conveyor
belt moves to the right. Packages fall off the end of the
conveyor and into some other sorting bin. Suppose that
the conveyors are of widths 10, 20, and 30 as in the
diagram shown to the right.
All the packages are simple six sided boxes with three
dimensions. The person doing the sorting places each box on the appropriate conveyor. The proper
conveyor to use is the narrowest one which is still wide enough to hold the package. We wish to use
as little conveyor length as possible. All packages will fit on at least one conveyor, and (for example)
a 20 conveyor would hold up to and including a 20 distance on one side of the package. Packages
are placed on the conveyor with no space between them. In order to select the conveyor, you need
to consider all dimensions of the package.
Examples
Suppose a certain box is 15 x 21 x 4. The sorting process first considers using the minimal
conveyor length, so we desire to put the box on a conveyor such that the 4 side is traveling in the
conveyor direction to the right. We can thus place the box on a 4 x 21 side so that it is 15 high,
or we can place it on a 4 x 15 side and the package will stand 21 high. Since we want to use the
narrowest possible conveyor, we select conveyor B since the 20 width of the conveyor will handle
the 15 dimension of the box (A is too narrow, C is excessively wide). At this point, conveyor B
moves to the right 4 to accommodate the box, and the box is placed on the far left end of the
belt.
Another box arrives which is 12 x 24 x 19. We use the 12 dimension for the linear distance, and
can either stand the box on a 12 x 19 surface so it is 24 high, or on a 12 x 24 surface so it is
19 high. We choose conveyor B since 19 <= 20. Conveyor B moves to the right by 12 to
accommodate the box, and we place it on the belt.
After the two boxes described above have been processed, conveyor
B will look like this, with the first box to the right of the second
box. Note that 24 of the conveyor belt is still unused.
As the belts move from left to right, packages will eventually fall off the end. The conveyor belts
are 40 long. A package must be more than 50% over the right edge in order to fall off. For
example, a box which occupies 5 of belt space will fall off when 3 has passed the end of the belt,
not 2. Since package dimensions are given as integral numbers of inches, there is no need to check
for 2.5. Similarly, a box taking up 4 of conveyor space falls off at 3 but stays on at 2.
Since there is 24 of conveyor remaining in this case, the first box
will fall off when the belt has moved more than 26 further (recall
that the first box is 4 on this dimension). The diagram shows the
first box about to fall off the conveyor.

Input
There may be multiple cases. The input for each case begins with a line containing three integers
that specify the widths of the conveyor belts, in increasing order. That is, conveyor A is the
narrowest, and conveyor C is the widest. No two conveyor belts will have the same width. This line
will be followed by additional lines, one for each box, in the order they are placed on the conveyor
belts. Each of these lines contains three positive non-zero integers giving the dimensions of a box.
The first of these lines gives data for box 1, the second line for box 2, and so forth. The last box in
each case will be followed by a line containing three integers, each 1.
Input for the last case is followed by a line containing three integer zeroes.
Output
For each case, display the case number (starting with 1) on a line by itself. Then display additional
lines, each of which gives the number of a box and the letter (A, B, or C) identifying the conveyor
belt from which it fell. These must be in the correct temporal order, over all conveyor belts. That
is, if box X falls off conveyor B before box Y falls off conveyor A, then output from box X must
precede the output for box Y, even if box Y was placed on conveyor A before box X was placed on
conveyor B. Make your output appear similar to that shown in the samples below. Leave a single
blank line between the output for consecutive cases. Note that there will be fewer lines of output
than there are boxes, since some boxes will remain on the conveyors at the end of the program.
Also, placing one large box on the conveyor may force more than one box (or no boxes) off the end.
Sample Input

Output for the Sample Input

10 15 20
6 8 10
4 11 8
19 8 8
5 9 12
10 10 10
888
9 9 14
-1 -1 1
000

Case 1:
Box 1 fell off conveyor A
Box 2 fell off conveyor A

57. Problem: Happy Birthday to You, and You, and You!


Many people recognize the birthday paradox. It states that given a group of 23 or more randomly
chosen persons, the probability that at least two of them will have the same birthday is more than
50%. Actually it isnt a paradox, but is so named because it contradicts what most people would
intuitively expect.
But what is the probability that at least three persons in a group of N randomly chosen persons
share the same birthday?
For simplicity we will assume that there are exactly 365 days in a year, and require that your
answer be correct only within one tenth of a percent. For example, with 88 people in a group, the
probability that at least three of these people will have the same birthday is 51.1 percent (with the
result rounded to one fractional digit). Your answer could be any of 51.0 percent, 51.1 percent, or
51.2 percent and still be considered correct.
Input
There may be multiple cases. The input for each case is a line containing the integer N, the size of
the group. N will be no larger than 1000.
Input for the last case is followed by a line containing -1.
Output
For each case, display the case number (starting with 1) and the probability that at least three
persons in a group of size N share the same birthday. Your result should be displayed as a
percentage rounded to one fractional digit. Separate the output for consecutive cases by a blank
line. Your output should look very similar to that shown in the samples below.
Sample Input

Output for the Sample Input

23
88
-1

Case 1. 1.3 percent


Case 2. 51.1 percent

Problem 8: E-mail Sniffing


Your company is constructing a device for the International Criminal Protection Council ICPC). This
device can be used to detect e-mail messages containing words that suggest the message relates to
an illegal activity, and thus require further attention. Since e-mail is abundant, and the networks
are fast, the device needs to detect these words very quickly. You have decided to construct a hash
code for each word in an e-mail and then determine if that word is in a hash table of suspect words.
To make the lookup fast, you have decided to use a perfect hash function where each suspect word
maps to a unique location in the table.
A perfect hash function maps its input directly to a fully-occupied table. You need to construct the
perfect hash function from the list of suspect words. The hash function is of the form C / w mod
n, where C is a positive integer (which you need to discover), w is an integer representation of a
word, and n is the length of the table (that is, the number of suspect words). C must be as small as
possible. Note that is the floor function and that R for some real number R is the largest
integer that is less than or equal to R.
Assume the set of n suspect words is represented by the positive integers w1, w2, , wn. The
problem is to find the smallest positive integer C such that C / wi mod n C / wj mod n for all
1 i < j n . You are to convert each input word to an integer by processing each letter in the
word, working left to right. Consider a to be 1, b to be 2, , and z to be 26. Use 5 bits for each
letter; before processing the next letter, shift the partially completed words integer value left by
5 bits or multiply it by 32. Thus a = 1, and bz = 2 32 + 26 = 90.
C must be a multiple of at least one words integer representation.
If C / wi mod n = C / wj mod n for some i j (that is, a hashing collision) then the next
largest C that could possibly resolve the conflict is at least the minimum of ( C / wi + 1) wi and
( C / wi + 1) wj, . Since all conflicts must be resolved, it is advantageous to choose the largest
candidate from among the conflicts as the next C to test. C will not always fit in a 32-bit integer.
Input
The input will contain multiple cases. For each case the input will consist of a single line containing
between two and thirteen unique words, each containing only between one and five lowercase
letters. The words are separated from each other by at least one blank.
Input for the last case will be fol owed by a line containing only an end of line character.
Output
For each case, display the case number (starting with 1) and the value of C that yields a perfect
hashing function. Separate the output for consecutive cases with a blank line. Your output should
appear similar to that shown in the sample below.
Sample Input

Output for the Sample Input

bomb timer fuse radio


ax knife pick lock gun
This line contains only an end of line.

Case 1: 19029075
Case 2: 817488

58. Problem: Digital Editing


A display device is being constructed that will display certain five-digit values. Only certain values
can be displayed, and the device can change only one digit at a time.
For example, suppose the allowed display values were 12345, 12346, 17345, 17346, 22346, and
26346. Is it possible to display each of these, given a choice as to which value is displayed first?
The answer is yes, as illustrated below.
Start with 26346.
Change the first 6 to 2 to yield 22346.
Now change the first 2 to 1 to yield 12346.
Now change the remaining 2 to 7 to yield 17346.
Then change the 6 to 5 to yield 17345.
And finally, change the 7 to 2 to yield 12345.
Although all six values can be displayed in this case, it is not always the case that all values can be
displayed. For example, consider this set of values: 59304, 58304, 8300, 48304, 19304, and 18304.
The longest sequence that can be displayed has four values, as in 18304 19304 5930458304.
The same value may not appear twice in the sequence of displayed values. In particular, the set of
values 11111, 12111, 11211, 11121, and 11112 only allow sequences with a maximum length of 3.
Your job, given the set of values that can be displayed, is to determine the maximum number of
values in a sequence that can be displayed, given that you can select the value with which the display
begins, and that you can only change one digit at a time.
It is obvious that there are multiple such sequences. For example, reversing the order in which the
values are displayed will yield another allowable sequence. It is not the particular sequence that is
of interest here, but only the length of the sequence.
Input
The input will contain multiple cases. Each case begins with a line containing an integer N that
specifies the number of distinct values in the set. N will be no larger than 10,000. This line is then
followed by one or more lines containing a total of N unique integers, each in the range 0 to 99999,
with one or more such integers per line. Multiple integers on a line will be separated by spaces.
Input for the last case will be fol owed by a line containing the integer 0.
Output
For each case, display the case number (starting with 1) and the number of unique values that can
be displayed subject to the single-digit modification constraint. Separate output for consecutive
cases with a blank line. Your output should appear similar to that shown in the sample below.
Sample Input

Output for the Sample Input

6
12345 12346 17345 17346 22346 26346
6
59304 58304 8300 48304 19304 58303
5
10057 57 10056 50056 58
0

Case 1. 6 values
Case 2. 4 values
Case 3. 5 values

59. Problem: Encrypting Passwords.


Chip and Dale have devised an encryption method to hide their passwords. They first agree secretly on a
number that will be used as the number of columns in a matrix. The sender prepares an intermediate format using
the following rules:
1. - The password is formed with lowercase letters only.
2. - Each letter will be represented in binary code according to
ASCII table.
The sender then enters the letters of the intermediate format along
the diagonals of the matrix and pads with extra characters 0
(zero) so as to make a rectangular array of letters. These
additional characters do not comprise the Password
For example, if the password is: iteso and there are five columns,
Dale would write down
For example, for the letter i:
Letter = i
ASCII Code = 105
Binary Code = 1 1 0 1 0 0 1
Note how Dale includes only the binary code of each letter and writes them all in lower case. Dale then sends the
password to Chip by writing the binary code in each row. So, the password in its intermediate format would be
encrypted as
111100011101001100101111001110011001100010000
Your job is to recover the password that was sent from Chip to Dale.
Input
There will be multiple input sets. Input for each set will consist of two lines. The first line will contain an integer
in the range 2 . . . 20 indicating the number of columns used. The next line is a string of up to 400 characters
(1s and 0s). The last input set is followed by a line containing a single zero (0). This line should not be
processed.
Output
Each input set should generate one line of output, giving the password.
Sample Input
5
111100011101001100101111001110011001100010000
3
110001010101011101101
0
Sample Output
iteso
acm

60. Problem: Football Foundation (FOFO).

The football foundation (FOFO) has been researching on soccer; they created a set of sensors to describe the
ball behavior based on a grid uniformly distributed on the field. They found that they could predict the ball
movements based on historical analysis. Each square sensor of the grid can detect the following patterns:
N north (up the field)
S south (south the field)
E east (to the right on the field)
W west (to the left on the field)
For example, in grid 1, suppose the ball was thrown into the field from north side into the field. The path the
sensors detected for this movement follows as shown. The ball went through 10 sensors before leaving the
field.
Comparing with what happened on grid 2, the ball went through 3 sensors only once, and started a loop
through 8 instructions and never exits the field.
You are selected to write a program in order to evaluate line judges job, with the following out put based on
each grid of sensors, the program needs to determine how long it takes to the ball to get out of the grid or how
the ball loops around.
Input
There will be one or more grids of sensors for the same game. The data for each is in the following form. On the
first line are three integers separated by blanks: The number of rows in the grid, the number of columns in the
grid, and the number of the column in which the ball enters from the north. The grid columns number starts with
one at the left. Then come the rows of direction instructions. The lines of instructions contain only the characters
N, S,E or W, with no blanks. The end of input is indicated by a grid containing 0 0 0 as limits.
Output
For each grid in the input there is one line of output. Either the ball follows a certain number of sensors and exits
the field on any one of the four sides or else the ball follows the behavior on some number of sensors repeatedly.
The sample input below corresponds to the two grids above and illustrates the two forms of output.
The word step is always immediately followed by (s) whether or not the number before is 1.
Sample Input
365
NEESWE
WWWESS
SNWWWW
451
SESWE
EESNW
NWEEN
EWSEN
000
Sample Output

10 step(s) to exit
3 step(s) before a loop of 8 step(s)

61. Problem: Similar Structures.


After September 11, 2001, improve the security has become a crucial challenge for intelligence departments
around the world. A crucial issue about this task is to identify terrorism patterns represented by attacks in
different locations (dots), relations between terrorism activities (connections) and, attributes (dots and
connections labels) that describes the acts committed by political groups or persons. A natural
representation for this information is a graph, and the ability to discover and test known patterns in such
information could lead to significant improvement in our ability to identify potential threats.
Based on the above problem description, our task consists on developing a tool that identifies a terrorism
patterns into a set of potential terrorism activities using a graph-based representation where all graphs are
undirected and labeled (thus, all vertices and edges has a label). The task of this problem consists on
finding if there exist a subgraph S of G where S have the same number of vertices and edges of G and
there exist one to one association between vertices and edges from S and G with the same label
(isomorphism).
Input
The input will be a file called simi.in, where different terrorism activities are represented by different graphs.
Consider that each graph have a name, where graph XS GX represents a recognized terrorism pattern
associated to a terrorism group and XP GX represents a set of attacked locations. By notation, X is an
integer number between 1 to 5, where each of one is a test. Consider that XS G1 is the graph to search for
in XP G1 and so on. Moreover, XS G1 appears in simi.in immediately before of XP G1.
For all cases, #vertices of XS GX is lower than #vertices of XP GX and 0 < #vertices <= 150 for each XP
GX and for all graphs, 0 <= #edges <= 5000. Also, vertex and edge labels contains 500 printable ASCII
characters (or less) without single spaces.
Both XS GX and XP GX are represented based on the following format. First, there is a line with the
graph name. As an example, the line for XS G1 is:
XS G1
Next, there are k lines (each line represents a vertex), 0 < k <= 150, each one using the following format:
v id label
Consider that id is a positive integer, 0 < id <= 150, and label is a string (vertex label). There are not two
lines with the same id value and all lines are sorted in an increased order based on id.
The next l lines represent all edges into the graph, each one using the following format:
e idx idy label
Consider that idx and idy are positive integers associated to a vertex into the graph. On the other hand, label
is a string (edge label).
Output
For each pair of graphs (XS GX, XP GX), X = 1, ..., 5, if it does not exist a subgraph S of XS Gi where
XP Gi is isomorphic to S, print the message:
XS_Gi_<-->_XP_Gi
There are not instances!
Otherwise, each instance is reported based on the following format. First, print the message:
XS_Gi_<-->_XP_Gi
Vertices_(G)_<-->_Vertices_(G)
The next lines are the vertices and edges from G associated to vertices and edges from G. The format is as
follows:
{vX,_vY}_<-->_{vA,_vB}
where X, Y, A and B are positive integers and each of one represents a vertex valid id, where X < Y. All
lines are sorted based on the ids of G in an increasing order:
Line n: {vX,_vY}_<-->_{vA,_vB}
Line n+1: {vX,_vY}_<-->_{vA,_vB}

Exactly when X < X or X = X and Y < Y


Restrictions: If there exist a isomorphic subgraph, it is unique. There are not empty lines for inputs and
output files. There are not two different edges between a pair of vertices.
Sample Input
XS G1
v1a
v2b
v3a
v4b
e12d
e13d
e14c
e23d
XP G1
v1b
v2a
v3b
v4a
e12d
e13d
e14d
e23c
e24d
e34e
XS G2
v 1 house
v 2 attacked
e 1 2 yesterday
XP G2
v 1 house
v 2 attacked
e 1 2 yesterday
XS G3
v 1 WTC
v 2 AlQaeda
e 1 2 atacked_by
XP G3
v 1 WTC
v 2 ETA
e 1 2 atacked_by
Sample Output
XS G1 <--> XP G1
Vertices_(G)_<-->_Vertices_(G)
{v1,v2} <--> {v2,v1}
{v1,v3} <--> {v2,v4}
{v1,v4} <--> {v2,v3}
{v2,v3} <--> {v1,v4}
XS G2 <--> XP G2
Vertices_(G)_<-->_Vertices_(G)
{v1,v2} <--> {v1,v2}
XS G3 <--> XP G3
There are not instances!

62. Problem: Medium Size Summations (R2D2).


R2-D2 (our well known friendly robot) needs to perform some operations quickly to save his space ship. These
operations require computing long summations and a division. Moreover, he needs to find the exact solution
and he is required to present a report with the results. For that, he needs to simplify his solution as much as
possible.
We assume that there is an array available (X1, X2 , .) of 99999999 elements.
The array has the peculiar property that the average of the first K numbers is equal to the average of the index
K and the number 1.
R2-D2 needs to do the following: Given a natural number N less than 99999999, his assignment is to compute
the function:

Since R2-D2 needs an exact solution, we ask him to report the following:
The solution needs to be given as a pair of relative prime numbers a,b such that
f(N)= a/b if the solution is not an exact integer. Otherwise just give the exact integer. The numbers processed
by R2-D2 were of eight digits (99999999). Remember that R2-D2 was built long long time ago. His circuits are
not that fast but he is clever. R2-D2 was able to perform one of these operations in less than one second. Can
you do this assignment as fast as R2-D2 did it???
Input
You will receive an input line with natural numbers separated by comma. Each number is less than 99999999.
You will receive no more than 20 numbers.
Output
You need to give a sequence of lines each one with the solution of the corresponding input case. The solution
is either a pair of natural numbers separated by the symbol / representing the pair a,b mentioned above (when
the division is not exact) or just one natural number (when the division is exact). Notice that these numbers
could require more than 8 digits.
Sample Input
1,2
Sample Output
1
6/5

63. Problem:The Inheritance


Mr. Smyth wants to leave his son, Peter, a part of his land as inheritance. This is a very big piece of land which
is in the shape of a simple polygon. The only condition is that his son has to start building walls within his
fathers land in such a way that he has an area of land that is also in the shape of a simple polygon.
Peter is a very lazy person and prefers to pay someone to build the walls. However, the people contracted by
Peter forgot the boundaries that limit Mr. Smyths land. But they did not worry about this and went ahead and
built the walls. On the contrary, if they told Peter that they had forgotten the boundaries of Mr. Smyths land
Peter could get angry and he may fired his employee.
Mr. Smyth knows his son very well and he will only leave land to his son if he builds walls that do not invade the
land of his neighbors, (that is, no wall must be outside Mr. Smyths land), and the walls built by his son must
form an enclosed area.
Finally, Mr. Smyth wants to know the area of the land left for himself.
Input
The input begins with a single positive integer on a line by itself indicating the number of the cases (a integer
between 1 and 20) following, each of them as described below. This line is followed by a blank line, and there is
also a blank line between two consecutive inputs.
The next line defines Mr. Smyths land which is a simple polygon (without crossing edges or touching
borders), defined by a list of vertexes (there are at most 100 vertices in a polygon); each vertex is defined
by its coordinates (x,y) in decimal format (positive real numbers less than 1000). The vertexes are
ordered according to their sequence in the polygon.
The next line contains the number NB which defines the number of walls (there are at most 100 walls).
Next, NB lines are defined, each line having 4 integer numbers (positive integers less than 1000) X0 Y0
X1 Y1 (separated by a single space), which represent the starting points and end points of each wall (the
walls don't have any order)
Output
For each test case, the output must follow the description below. The outputs of two consecutive cases will be
separated by a blank line.
If Peter doesnt invade the neighbors land and he obtained an enclosing area, then the output has a line
which states The area free for your father is totalarea where totalarea is the total area of Mr. Smyths
land minus the area of Peters land. totalarea must be printed exact to three digits to the right of the
decimal point (round up). Followed by the Peter's inheritance in next line, this part must be represented
by coordinates (x,y) ordered according to their sequence in the polygon, beginning with P0 and P1 of first
wall and so on.
If Peter invades the neighbors land , output should contain a line stating Trying to steal neighbors land.
If Peter does not invades the neighbors land and does not succeed in enclosing an area with the walls
built, then the output should contain a line skating Sorry, your assignment do not deserve an inheritance
Sample Input
3
2 2 16 2 14 12 4 12
7
5 7 8 10
13 6 11 3
5585
5575
8 10 12 9
12 9 13 6
11 3 8 5
2 2 16 2 14 12 4 12
7
5 7 8 10
13 6 11 3
5585

5575
8 10 16 11
16 11 13 6
11 3 8 5
10 10 20 10 20 20 10 20
5
15 15 15 19
25 19 25 17
17 17 17 15
15 19 25 19
17 17 25 17
Sample Output
The area free for your father is: 85.000 and your land is: 5 7 8 10 12 9 13 6 11 3
8555
Trying to steal neighbours land
Trying to steal neighbours land

64. Problem: The Explorer.


An explorer must decide where to construct a way to arrive from a point A to point B. In order to help him,
the explorer has made a map with the obstacles that exist. He drew into squares his map and he wants a
way that passed through the smaller number of squares. The way only can go from a square to another one
if they have a side in common, that is to say, cannot advance in diagonal, and it cannot happen through a
square that contains an obstacle. Each square of the map is identified by its coordinates, column and row.
The columns are numbered of left to right initiating with the 0. The rows are numbered from top to down
initiating with the 0.
Input
There will be multiple input sets. The first line contains the incoming number of input to evaluate. Each input
will be formed of the following way: first, a line containing two integer numbers, N and M, separated by
spaces, indicate the number of columns and lines, where 1 N, M 100. In each one of the following M
lines there is N numbers, separated by spaces, that can be 0 or 1, 0 if there is not obstacle in corresponding
square and 1 if there is it. In the penultimate line the column and row of point A. In the last line the column
and row of point B. All the cases of test will have at least a way to arrive from A at B.
Output
The number of squares through which it passes a minimum way between A and B.
Sample Input
2
33
100
100
001
20
02
54
01000
00110
01000
00000
13
20
Sample Output
5
9

65. Problem: Rounders


Introduction:
For a given number, if greater than ten, round it to the nearest ten, then (if that result is greater than 100)
take the result and round it to the nearest hundred, then (if that result is greater than 1000) take that number
and round it to the nearest thousand, and so on ...
Input:
Input to this problem will begin with a line containing a single integer n indicating the number of integers to
round. The next n lines each contain a single integer x (0 <= x <= 99999999).
Output:
For each integer in the input, display the rounded integer on its own line.
Note: Round up on fives.
Sample Input:
91
5
14
459
9
12345678
44444445
1445
446
Sample Output:
20
10
451
00
10000000
50000000
2000
500

66. Problem: Q
Introduction
You've got a queue. And you just got to mess with it.
Given a queue of items and a series of queue operations, return the resulting queue.
Queue operations are defined as follows:
starting-position to requested-position
meaning one wants the item at the starting position to be moved to the requested position. So if the queue of
items were:
Item1 Item2 Item3 Item4 Item5
(Item1 being in position 1, Item2 in position 2, etc.)
after applying the queue operation:
5 to 2
the resulting queue would be:
Item1 Item5 Item2 Item3 Item4
as Item5 (the item in position 5) was moved to position 2. Multiple queue operations are applied at the same
time, however; e.g., given the queue of items:
Item1 Item2 Item3 Item4 Item5 Item6 Item7 Item8
If the following queue operations were applied:
2 to 6; 6 to 3; 4 to 5; 5 to 2; 7 to 4; 8 to 1
then the resulting queue would be:
Item8 Item5 Item6 Item7 Item4 Item2 Item1 Item3
As you can see, the queue operations are strictly enforced, with other items (not involved in queue
operations) maintaining their order and moving to vacant positions in the queue. Note that no two queue
operations will have the same starting-position or same requested-position defined.
Input
Input to this problem will begin with a line containing a single integer x indicating the number of datasets.
Each data set consists of three components:
1. Start line A single line, "m n" (1 <= m, n <= 20) where m indicates the number of items in the
queue and n indicates the number of queue operations.
2. Queue items A line of short (between 1 and 8 characters) alphanumeric names for the items in the
queue. Names are unique for a given data set and contain no whitespace.
3. Queue operations n lines of queue operations in the format "starting-position requestedposition".
Output
For each dataset, output the queue after the queue operations have been applied. Print the elements of the
queue on a single line, starting from the first and ending with the last, with a single space separating each
item.
Sample Input
35
1
alpha beta gamma delta epsilon
52
86
abcdefgh
26
63
45
52
74
81
32
foo bar baz

31
13
Sample Output
alpha epsilon beta gamma delta
hefgdbac
baz bar foo

67. Problem: Enigmatologically Cruciverbalistic


Introduction:
The local ACM Newsletter has decided to start running a crossword puzzle in each issue. Instead of
purchasing premade puzzles, however, the editors would like to be able to make puzzles in various shapes
and with words of their own choosing. They've turned to you for the development of the puzzles ... and as a
programmer, you've decided to turn to your computer and solve the problem once and for all.
A crossword grid looks like this:
..#......
#.#......
#########
#.#.#...#
#.#.....#
######..#
#.#......
Each continuous row or column of two or more hash marks represents a single word, one letter per mark.
Where rows and columns cross, the letter in the shared mark must be the same.
Your goal is to write a program that fills a given grid with a given set of words such that:
every mark in the grid contains a letter;
no other cells in the grid contain a letter;
every word in the word list appears once and only once in the grid with no unused words left over;
and
no words (or other sequences of letters) not in the word list appear in the grid
Words inside of other words (BRIGHT inside of BRIGHTLY, for example) do not count as an appearance
of the sub-word. You may assume that every word in the word list is unique in that puzzle. You may also
assume that there is at most one possible layout for a given grid and word list.
Input:
The first line of data will be a number representing the number of datasets in the file. For each dataset, the
first line consists of two integers w h (2 <= w, h <= 15) where w is the width of the puzzle and h is the
height. The next h lines of the dataset are a representation of the crossword puzzle grid, as shown above. All
word spaces in the puzzle will be at least two characters in length. The next line consists of an integer c (1 <= c
<= 100) representing the number of words in the crossword. The next c lines contain the words in the
word list.
Output:
For each dataset in the input, output the heading "Puzzle #x", where x is 1 for the first dataset, 2 for the
second, and so on. Then print either "I cannot generate this puzzle." if the puzzle is impossible to
generate given that grid and word list, or print a solved representation of the puzzle as shown below.
Sample Input:
29
7
..#......
#.#......
#########
#.#.#...#
#.#.....#
######..#
#.#......
6C
OMPUTE

LAMPSHADE
EDIT
SO
PLAYER
ESTEEM
55
#####
#.#.#
#####
#.#.#
#####
6A
DAGE
ANGRY
YEARN
NEEDS
FLUTE
XYZZY
Sample Output:
Puzzle #1
..C......
P.O......
LAMPSHADE
A.P.O...D
Y.U.....I
ESTEEM..T
R.E......
Puzzle #2
I cannot generate this puzzle.

68. Blue Jeans


Introduction:
The Genographic Project is a research partnership between IBM and The National Geographic Society that
is analyzing DNA from hundreds of thousands of contributors to map how the Earth was populated.
As an IBM researcher, you have been tasked with writing a program that will find commonalities amongst
given snippets of DNA that can be correlated with individual survey information to identify new genetic
markers.
A DNA base sequence is noted by listing the nitrogen bases in the order in which they are found in the
molecule. There are four bases: adenine (A), thymine (T), guanine (G), and cytosine (C). A 6-base DNA
sequence could be represented as TAGACC.
Given a set of DNA base sequences, determine the longest series of bases that occurs in all of the sequences.
Input:
Input to this problem will begin with a line containing a single integer n indicating the number of datasets.
Each dataset consists of the following components:
1. A single positive integer m (2 <= m <= 10) indicating the number of base sequences in this dataset.
2. m lines each containing a single base sequence consisting of 60 bases.
Output:
For each dataset in the input, output the longest base subsequence common to all of the given base
sequences. If the longest common subsequence is less than three bases in length, display the string "no
significant commonalities" instead. If multiple subsequences of the same longest length exist, output
only the subsequence that comes first in alphabetical order.
Sample Input:
32G
ATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
3G
ATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA
GATACTAGATACTAGATACTAGATACTAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA
GATACCAGATACCAGATACCAGATACCAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA
3C
ATCATCATCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
ACATCATCATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AACATCATCATTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
Sample Output:
no significant commonalities
AGATAC
CATCATCAT
Problem: Core Wars
Introduction:
Core Wars is a game in which two opposing warrior programs attempt to destroy each other in the memory
of a virtual machine. They do this by overwriting each other's instructions, and the first program to execute
an illegal instruction is declared the loser. Each program is written in an assembly-like language called
Redcode, and the virtual machine which executes the two programs is known as the Memory Array

Redcode Simulator (MARS). Your goal is to write a MARS that will read in two Redcode programs,
simulate them, and print out which program was the winner.
MARS simulates a somewhat unusual environment compared to other virtual machines and processor
architectures. The following list describes these differences in detail:
1. MARS simulates a machine with 8000 memory locations and each location stores exactly one
Redcode instruction. In fact, a memory location can only store instructions and cannot directly store
any data. However, each instruction includes two numeric operands, and these in turn can be
manipulated by other instructions for data storage. This also makes self-modifying code possible.
2. The memory locations are arranged as a continuous array with the first location having address 0 and
the last having 7999. All address calculations are performed using modulo 8000 arithmetic. Put in
another way, memory addresses wrap around so that addresses 8000, 8001, and 8002 refer to same
memory locations respectively as addresses 0, 1, and 2. This also works for negative numbers. For
example, -7481, -15481, 519, and 8519 all refer to the same memory location.
3. All arithmetic and comparison operations are performed modulo 8000. Additions must normalize their
final result to be in the range of 0 to 7999 (inclusive) before writing that result into memory. This also
implies that -124 is considered to be greater than 511 since after normalization, -124 becomes 7876,
and 7876 is greater than 511.
4. The simulator maintains two separate instruction pointers (IPs) that store the address of the next
instruction to be executed by the warrior programs. After loading both programs into memory, these
IPs are initialized to the first instruction of each program. As the programs run, the IP is incremented
by one (modulo 8000) after each instruction is executed. If a jump/skip instruction is executed, then
the IP is instead loaded with the destination address of the jump/skip and execution continues from
this new address.
5. The simulator "time slices" between warriors by executing one instruction at a time, and alternating
between programs after each instruction. For example, if the two programs were loaded at addresses
2492 and 6140, the first six instructions would be executed in this order (assuming no jump/skip
instruction were executed): 2492, 6140, 2493, 6141, 2494, 6142.
Every instruction in MARS consists of an opcode, written as a three letter mnemonic, and two operands
called the A and B fields. Each operand is a number in the range 0-7999 (inclusive) and each can use one of
three addressing modes: immediate, direct, and indirect. These modes are explained in more detail below:
Immediate operands are written with a "#" sign in front, as in #1234. An immediate operand specifies a
literal value for the instruction to operate on. For example, the first operand (i.e. the A field) of an ADD
instruction (which performs integer addition) can be an immediate. In that case, the literal value specified
by the first operand provides one of the numbers being added.

Direct operands identify the memory locations which an instruction is to access. They are written with a
"$" sign in front, as in $1234. One example would be ADD #5 $3. A direct operand is actually an offset
relative to the current IP address. For example, if the ADD #5 $3 instruction were stored in memory
location 4357, it would actually be adding together a literal number five with a second value stored in the
B field of location 4360 (4357 + 3). However, if that same instruction were stored at location 132 it would
be adding five to a value in the B field of location 135 (132 + 3).

Indirect operands are analogous to how pointers in some programming languages work. Indirect
operands are written with a "@" sign in front of the number, as in ADD #5 @3. Like before, the indirect
operand is an offset relative to the current IP address, and therefore identifies a particular memory
location. However, the value stored in the B field of this memory location is then used as an offset relative
to that location to identify a second location. It is the B field of this second location which will actually be
operated on by the instruction itself. For example, if location 4357 contained ADD @1 @3, location 4358
contained 11 in its B field, and location 4360 contained 7996 in its B field, then this instruction would
actually be adding the values stored in locations 4369 (4358 + 11) and 4356 (4360 + 7996 modulo 8000).

The list below explains what each instruction does based on its opcode. Although not all instructions use
both of their operands, these must still be specified since other instructions might use these operands for
data storage. Some instructions update the B field of another instruction; this only affects the
numerical value of the field, but does not change its addressing mode.

DAT
This instruction has two purposes. First, it can be used as a generic placeholder for arbitrary data.
Second, attempting to execute this instruction terminates the simulation and the program which tried
to execute it loses the match. This is the only way that a program can terminate, therefore each
warrior attempts to overwrite the other one's program with DAT instructions. Both A and B operands
must be immediate.
MOV
If the A operand is immediate, the value of this operand is copied into the B field of the instruction
specified by MOV's B operand. If neither operand is immediate, the entire instruction (including all
field values and addressing modes) at location A is copied to location B. The B operand cannot be
immediate.
ADD
If the A operand is immediate, its value is added to the value of the B field of the instruction
specified by ADD's B operand, and the final result is stored into the B field of that same instruction. If
neither operand is immediate, then they both specify the locations of two instructions in memory. In
this case, the A and B fields of one instruction are respectively added to the A and B fields of the
second instruction, and both results are respectively written to the A and B fields of the instruction
specified by the ADD's B operand. The B operand cannot be immediate.
JMP
Jump to the address specified by the A operand. In other words, the instruction pointer is loaded
with a new address (instead of being incremented), and the next instruction executed after the JMP
will be from the memory location specified by A. The A operand cannot be immediate. The B
operand must be immediate, but is not used by this instruction.
JMZ
If the B field of the instruction specified by JMZ's B operand is zero, then jump to the address
specified by the A operand. Neither the A nor B operand can be immediate.
SLT
If A is an immediate operand, its value is compared with the value in the B field of the instruction
specified by SLT's B operand. If A is not immediate, the B fields of the two instructions specified by
the operands are compared instead. If the first value (i.e the one specified by A) is less than the
second value, then the next instruction is skipped. The B operand cannot be immediate.
CMP
The entire contents of memory locations specified by A and B are checked for equality. If the two
locations are equal, then the next instruction is skipped. Memory locations are considered equal to
another if they both have the same opcodes and they have the same values and addressing modes in
their respective operand fields. The A or B operands cannot be immediate.
Input:
The input begins with a line containing a single integer n indicating the number of independant simulations
to run. For each simulation the input will contain a pair of programs, designated as warrior number one and
warrior number two. Each warrior program is specified using the following format:
One line with integer m (1 <= m <= 8000) indicating the number of instructions to load for this warrior. A
second line containing an integer a (0 <= a <= 7999) gives the address at which to start loading the warrior's
code. These two lines are then followed by m additional lines containing the warrior's instructions, with one
instruction per line. If the warrior is loaded at the end of memory, the address will wrap around and the
instructions continue loading from the beginning of memory.
The address ranges occupied by the two programs will not overlap. All other memory locations which
were not loaded with warrior code must be initialized to DAT #0 #0. Execution always begins with
warrior number one (i.e. the warrior read in first from the input file).
Output:

Each simulation continues running until either warrior executes a DAT instruction or until a total of 32000
instructions (counting both warriors) are executed. If one warrior program executes a DAT, the other is
declared the winner; display "Program #x is the winner.", where x is either 1 or 2 and represents the
number of the winning warrior. If neither program executes a DAT after the maximum instruction count is
reached, then the programs are tied; display "Programs are tied."
Sample Input:
231
85
ADD #4 $2
JMP $-1 #0
DAT #0 #-3
51
00
JMP $2 #0
DAT #0 #-1
ADD #5 $-1
MOV $-2 @-2
JMP $-2 #0
15
524
MOV $0 $1
55
39
JMP $2 #0
DAT #0 #-1
ADD #5 $-1
MOV $-2 @-2
JMP $-2 #0
Sample Output:
Program #2 is the winner.
Programs are tied.

69. Problem: 'Roid Rage


Introduction:
When writing game programs, it is often useful to determine when two polygons intersect one another. This
is especially useful in arcade games like Asteroids where one polygon could represent a spaceship while
another represents a huge, unyielding chunk of space rock.
Write a program that can determine which polygons of a given set intersect one another.
Input:
Input to this problem will begin with a line containing a single integer n indicating the number of datasets.
Each data set consists of the following components:
1. A line containing a single positive integer m (1 <= m <= 10) indicating the number of polygons to
analyze.
2. m lines, each representing a single polygon, with the first line describing polygon 1, the second line
describing polygon 2, and so on. Each line begins with a single positive integer v (3 <= v <= 20)
indicating the number of vertices describing this polygon. This is followed by v (x,y) coordinate pairs
(0 <= x, y <= 100), each of which is a vertex of this polygon. The vertices are connected by edges in
the order listed with the last vertex connected back to the first by a final edge. All polygons are
"simple"; they do not self-intersect.
Output:
For each dataset in the input, output the heading "Data Set #z", where z is 1 for the first dataset, 2 for the
second, etc. If this data set contained no intersecting polygons, output the message "no collisions" on its
own line. Otherwise, output the list of all pairs of intersecting polygons, one pair per line, each pair
formatted with the lowest-numbered polygon first. Output the polygon pairs in ascending order, sorting first
by the lowest-numbered polygon in the set and then the second.
Note: The definition of "intersecting" for the purpose of this problem means that two polygons either share an
interior region (i.e., they overlap), or they share boundary points (i.e., they touch at a point or along an
edge).
Sample Input:
22
4 0,0 1,0 1,1 0,1
4 2,2 3,2 3,3 2,3
43
2,1 1,2 2,3
3 2,1 3,2 2,3
5 2,0 4,2 2,4 5,4 5,0
4 3,3 1,3 1,5 3,5
Sample Output:
Data Set #1
no collisions
Data Set #2
12
14
24
34

70. Problem: Children of the Candy Corn


Introduction:
The cornfield maze is a popular Halloween treat. Visitors are shown the entrance and must wander through
the maze facing zombies, chainsaw-wielding psychopaths, hippies, and other terrors on their quest to find
the exit.
One popular maze-walking strategy guarantees that the visitor will eventually find the exit. Simply choose
either the right or left wall, and follow it. Of course, there's no guarantee which strategy (left or right) will
be better, and the path taken is seldom the most efficient. (It also doesn't work on mazes with exits that are
not on the edge; those types of mazes are not represented in this problem.)
As the proprieter of a cornfield that is about to be converted into a maze, you'd like to have a computer
program that can determine the left and right-hand paths along with the shortest path so that you can figure
out which layout has the best chance of confounding visitors.
Input:
Input to this problem will begin with a line containing a single integer n indicating the number of mazes.
Each maze will consist of one line with a width, w, and height, h (3 <= w, h <= 40), followed by h lines of w
characters each that represent the maze layout. Walls are represented by hash marks ('#'), empty space by
periods ('.'), the start by an 'S' and the exit by an 'E'.
Exactly one 'S' and one 'E' will be present in the maze, and they will always be located along one of the
maze edges and never in a corner. The maze will be fully enclosed by walls ('#'), with the only openings
being the 'S' and 'E'. The 'S' and 'E' will also be separated by at least one wall ('#').
You may assume that the maze exit is always reachable from the start point.
Output:
For each maze in the input, output on a single line the number of (not necessarily unique) squares that a
person would visit (including the 'S' and 'E') for (in order) the left, right, and shortest paths, separated by a
single space each. Movement from one square to another is only allowed in the horizontal or vertical
direction; movement along the diagonals is not allowed.
Sample Input:
28
8
########
#......#
#.####.#
#.####.#
#.####.#
#.####.#
#...#..#
#S#E####
95
#########
#.#.#.#.#
S.......E
#.#.#.#.#
#########
Sample Output:
37 5 5
17 17 9

71. Problem: Panic Room


Introduction
You are the lead programmer for the Securitron 9042, the latest and greatest in home security software from
Jellern Inc. (Motto: We secure your stuff so YOU can't even get to it). The software is designed to "secure"
a room; it does this by determining the minimum number of locks it has to perform to prevent access to a
given room from one or more other rooms. Each door connects two rooms and has a single control panel

that will unlock it. This control panel is accessible from only one side of the door. So, for example, if the
layout of a house looked like this:
with rooms numbered 0-6 and control panels marked with the letters "CP" (each next to the door it can
unlock and in the room that it is accessible from), then one could say that the minimum number of locks to
perform to secure room 2 from room 1 is two; one has to lock the door between room 2 and room 1 and the
door between room 3 and room 1. Note that it is impossible to secure room 2 from room 3, since one would
always be able to use the control panel in room 3 that unlocks the door between room 3 and room 2.
Input
Input to this problem will begin with a line containing a single integer x indicating the number of datasets.
Each data set consists of two components:
1. Start line a single line "m n" (1 <=m<= 20; 0 <=n<= 19) where m indicates the number of rooms in
the house and n indicates the room to secure (the panic room).
2. Room list a series of m lines. Each line lists, for a single room, whether there is an intruder in that
room ("I" for intruder, "NI" for no intruder), a count of doors c (0 <= c <= 20) that lead to other
rooms and have a control panel in this room, and a list of rooms that those doors lead to. For
example, if room 3 had no intruder, and doors to rooms 1 and 2, and each of those doors' control
panels were accessible from room 3 (as is the case in the above layout), the line for room 3 would
read "NI 2 1 2". The first line in the list represents room 0. The second line represents room 1, and
so on until the last line, which represents room m - 1. On each line, the rooms are always listed in
ascending order. It is possible for rooms to be connected by multiple doors and for there to be more
than one intruder!
Output
For each dataset, output the fewest number of locks to perform to secure the panic room from all the
intruders. If it is impossible to secure the panic room from all the intruders, output "PANIC ROOM BREACH".
Assume that all doors start out unlocked and there will not be an intruder in the panic room.
Sample Input

37
2
NI 0
I3045
NI 2 1 6
NI 2 1 2
NI 0
NI 0
NI 0
72
I0
NI 3 0 4 5
NI 2 1 6
I212
NI 0
NI 0
NI 0
43
I0
NI 1 2
NI 1 0
NI 4 1 1 2 2
Sample Output
2P
ANIC ROOM BREACH
1

72. Problem: Savings Account


Suppose you open a savings account with a certain initial balance. You will not make any withdrawals or
further deposits for a number of years. The bank will compound your balance (add the annual interest) once a
year, on the anniversary of the opening of the account. Your goal is to achieve a certain target amount in your
savings account. In how may years will the target amount be achieved?
Input
The input file will contain data for one or more test cases, one test case per line. Each line will contain three
numbers: the initial balance, the annual interest rate (as a percentage of the balance), and the target amount,
separated by blank spaces. These will be positive numbers; they may or may not contain a decimal point. The
target amount will be greater than the initial balance. The input is terminated by endoffile
Output
For each line of input, your program will produce exactly one line of output: This line will contain one
positive integer value: the number of years required to achieve the target amount.
Sample input
200.00 6.5 300
500 4 1000.00
Output for sample input
7
18
Problem: Bridge Bidding
Bridge is a very complicated card game, and the bidding part is particularly difficult to master. The bidding is
made even more difficult because players use different bidding conventions (meanings assigned to bids). In
this problem, you are asked to write a program that suggests the first bid that should be made. The bidding
conventions described below are simplified from those used by a certain person who shall remain nameless.
A bridge hand consists of 13 cards. Each card has a suit (spades, hearts, diamonds, or clubs) and a rank (A, K,
Q, J, T, 9, 8, 7, 6, 5, 4, 3, 2). Here, the letter T denotes the card whose rank is 10. Before making a bid, an
experienced bridge player studies the number of high card points (hcp) in the hand, as well as the distribution
(the number of cards in each suit). The hcp contributed by each card is completely determined by its rank as
follows:
Rank hcp
A4
K3
Q2
J1
others 0
For example, if the hand is:
Spades: A, 2
Hearts: K, J, T, 9, 2
Diamonds: 3
Clubs: K, Q, 7, 4, 3
Then this hand has 13 hcp and a distribution of 5521 (the distribution is usually listed in nonincreasing
order). A balanced distribution is any one of 4333, 4432, and 5332.
In bridge, an opening bid is either "pass" or consists of a level (17) and a trump suit. The trump suits are no
trump, spades, hearts, diamonds, clubs ranked in decreasing order. Once a hand has been evaluated, the player
applies the following list of (simplified) rules to determine the appropriate opening bid. In cases where
multiple rules apply, the first one that applies should be used. An "x" in a distribution can be substituted with
any nonnegative number. Multiple "x"s in a distribution are not necessarily the same.

1. With at least 10 hcp and a yxxx distribution (y >= 8), bid the suit with y cards at the 4 level. This is
known as a preemptive bid.
2. With 1013 hcp and a 7xxx distribution, bid the suit with 7 cards at the 3level. This is known as a
preemptive bid.
3. With 89 hcp and a yxxx distribution (y >= 7), bid the suit with y cards at the 2level if the ycard suit
is Spades or Hearts. This is known as a "weaktwo" bid.
4. With 811 hcp and a 6xxx distribution, in which Spades or Hearts is one of the 6card suits, bid the
higher rank suit at the 2 level. This is known as a "weaktwo" bid.
5. With 1115 hcp, a distribution of 4441 or 5440, and at least 4 spades, bid Diamonds at the 2
level. This is called the "Mini Roman Convention".
6. With 1517 hcp and a balanced distribution, bid No Trump at the 1 level provided that at least 3 suits are
"stopped." A suit is considered stopped if the suit contains at least one of the following:
an A;
a K and one other;
a Q and two others; or
a J and three others;
7. With 2022 hcp and a balanced distribution, bid No Trump at the 2 level.
8. With at least 22 hcp, bid Clubs at the 2 level.
9. With 1316 hcp:If there is a 5card or longer suit in Spades or Hearts, bid it at the 1 level. If both bids are
possible, bid the longer suit.
a. If both suits have the same length, bid the higher ranking suit.
b. Without a 5card suit in Spades or Hearts, bid the longer of Diamonds or Clubs at the 1
level (whichever one has the most number of cards) . If there is a tie, bid the higher
ranking suit.
10. With at least 17 hcp, bid the longest suit at the 1 level. If there is a tie, bid the lowest ranking suit. This is
known as a "reverse".
11. If none of the rules above is applicable, bid Pass.
In the example above, rule 9a applies and a bid of 1 Hearts should be made.
Input
The input consists of a number of cases. The bridge hand for each case is specified on one line, with a single
space separating each of the 13 cards in the hand. Each card is given as a twocharacter string. The first letter
is the suit (S, H, D, C) and the second character is the rank (A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, 2). The end of
input is terminated by endoffile.
Output
For each case, print the hand number (starting from 1), followed by a colon and a space, and then the
suggested bid on a single line (see below for the exact format). Each bid is either "Pass" or a level and a suit
("No Trump", "Spades", "Hearts", "Diamonds", "Clubs") separated by a single space.
Sample input
SA S2 HK HJ HT H9 H2 D3 CK CQ C7 C4 C3
SK SQ HT H8 H4 CA CQ CT C5 DK DQ DJ D8
SA SK SQ S3 S2 HT D7 D9 CA CK CQ C7 C5
Output for sample input
Hand #1: 1 Hearts
Hand #2: 1 No Trump
Hand #3: 1 Clubs

73. Problem: Baskets of Gold Coins


You are given N baskets of gold coins. The baskets are numbered from 1 to N. In all except one of the
baskets, each gold coin weighs w grams. In the one exceptional basket, each gold coin weighs wd grams. A
wizard appears on the scene and takes 1 coin from Basket 1, 2 coins from Basket 2, and so on, up to and
including N1 coins from Basket N1. He does not take any coins from Basket N. He weighs the selected
coins and concludes which of the N baskets contains the lighter coins. Your mission is to emulate the wizard's
computation.
Input
The input file will consist of one or more lines; each line will contain data for one instance of the problem.
More specifically, each line will contain four positive integers, separated by one blank space. The first three
integers are, respectively, the numbers N, w, and d, as described above. The fourth integer is the result of
weighing the selected coins.
N will be at least 2 and not more than 8000. The value of w will be at most 30. The value of d will be less
than w.
Output
For each instance of the problem, your program will produce one line of output, consisting of one positive
integer: the number of the basket that contains lighter coins than the other baskets.
Sample input
10 25 8 1109
10 25 8 1045
8000 30 12 959879400
Output for sample input
2
10
50
Problem: Count
This problem is strictly to acclimate teams to the contest environment. We strongly suggest you first finish
this problem, and then attempt the more complex practice problem.
Input
The input file will contain an unknown number of lines with at most 100 characters on each line. All the
characters will be printable ASCII characters. Note that the input file will always exist, but may be empty.
Output
The number of lines in the input file.
Sample input
one
and two
three
Output for sample input
3

74. Problem: Doors and Penguins


The organizers of the Annual Computing Meeting have invited a number of vendors to set up booths in a large
exhibition hall during the meeting to showcase their latest products. As the vendors set up their booths at their
assigned locations, they discovered that the organizers did not take into account an important facteach
vendor supports either the Doors operating system or the Penguin operating system, but not both. A vendor
supporting one operating system does not want a booth next to one supporting another operating system.
Unfortunately the booths have already been assigned and even set up. There is no time to reassign the booths
or have them moved. To make matter worse, these vendors in fact do not even want to be in the same room
with vendors supporting a different operating system.
Luckily, the organizers found some portable partition screens to build a wall that can separate the two groups
of vendors. They have enough material to build a wall of any length. The screens can only be used to build a
straight wall. The organizers need your help to determine if it is possible to separate the two groups of vendors
by a single straight wall built from the portable screens. The wall built must not touch any vendor booth (but it
may be arbitrarily close to touching a booth). This will hopefully prevent one of the vendors from knocking
the wall over accidentally.
Input
The input consists of a number of cases. Each case starts with 2 integers on a line separated by a single space:
D and P, the number of vendors supporting the Doors and Penguins operating system, respectively (1 <= D, P
<= 500). The next D lines specify the locations of the vendors supporting Doors. This is followed by P lines
specifying the locations of the vendors supporting Penguins. The location of each vendor is specified by four
positive integers: x1, y1, x2, y2. (x1, y1) specifies the coordinates of the southwest corner of the booth while
(x2, y2) specifies the coordinates of the northeast corner. The coordinates satisfy x1 < x2 and y1 < y2. All
booths are rectangular and have sides parallel to one of the compass directions. The coordinates of the
southwest corner of the exhibition hall is (0,0) and the coordinates of the northeast corner is (15000, 15000).
You may assume that all vendor booths are completely inside the exhibition hall and do not touch the walls of
the hall. The booths do not overlap or touch each other.
The end of input is indicated by D = P = 0.
Output
For each case, print the case number (starting from 1), followed by a colon and a space. Next, print the
sentence:
It is possible to separate the two groups of vendors.
if it is possible to do so. Otherwise, print the sentence:
It is not possible to separate the two groups of vendors.
Print a blank line between consecutive cases.
Sample input
33
10 40 20 50
50 80 60 90
30 60 40 70
30 30 40 40
50 50 60 60
10 10 20 20
21
10 10 20 20
40 10 50 20
25 12 35 40
00
Output for sample input
Case 1: It is possible to separate the two groups of vendors.
Case 2: It is not possible to separate the two groups of vendors.

Problem: GPA
Each course grade is one of the following five letters: A, B, C, D, and F. (Note that there is no grade E.) The
grade A indicates superior achievement, whereas F stands for failure. In order to calculate the GPA, the letter
grades A, B, C, D, and F are assigned the following grade points, respectively: 4, 3, 2, 1, and 0.
Input
The input file will contain data for one or more test cases, one test case per line. On each line there will be one
or more upper case letters, separated by blank spaces.
Output
Each line of input will result in exactly one line of output. If all upper case letters on a particular line of input
came from the set {A, B, C, D, F} then the output will consist of the GPA, displayed with a precision of two
decimal places. Otherwise, the message "Unknown letter grade in input" will be printed.
Sample input
ABCDF
BFFCCA
DCEF
Output for sample input
2.00
1.83
Unknown letter grade in input

75. Problem: Human Knot


A classic icebreaking exercise is for a group of n people to form a circle and then arbitrarily join hands with
one another. This forms a "human knot" since the players' arms are most likely intertwined. The goal is then
to unwind the knot to form a circle of players with no arms crossed.
We now adapt this game to a more general and more abstract setting where the physical constraints of the
problem are gone. Suppose we represent the initial knot with a 2regular graph inscribed in a circle (i.e., we
have a graph with n vertices with exactly two edges incident on each vertex). Initially, some edges may cross
other edges and this is undesirable. This is the "knot" we wish to unwind.
A "move" involves moving any vertex to a new position on the circle, keeping its edges intact. Our goal is to
make the fewest possible moves such that we obtain one nsided polygon with no edgecrossings remaining.
For example, here is a knot on 4 vertices inscribed in a circle, but two edges cross each other. By moving
vertex 4 down to the position between 2 and 3, a graph without edgecrossings emerges. This was achieved in
a single move, which is clearly optimal in this case.

When n is larger, things may not be quite as clear. Below we see a knot on 6 vertices. We might consider
moving vertex 4 between 5 and 6, then vertex 5 between 1 and 2, and finally vertex 6 between 3 and 4; this
unwinds the knot in 3 moves.
But clearly we can unwind the same knot in only two moves:

Input
The input consists of a number of cases. Each case starts with a line containing the integer n (3 <= n <= 500),

giving the number of vertices of the graph. The vertices are labelled clockwise from 1 to n. Each of the next n
lines gives a pair of neighbors, where line i (1 <= i <= n) specifies the two vertices adjacent to vertex i. The
input is terminated by n = 0.
Output
For each case, if there is no solution, print "Not solvable." on a line by itself. If there is a solution, print "Knot
solvable." on a line by itself, followed by the minimum number of moves required to solve the problem, on a
line by itself.
Sample input
6
45
35
26
16
12
34
6
26
14
56
25
34
13
0
Output for sample input
Knot solvable.
2
Knot solvable.
1

76.Problem: Knots
An even number N of strands are stuck through a wall. On one side of the wall, a girl ties N/2 knots between
disjoint pairs of strands. On the other side of the wall, the girl's groomtobe also ties N/2 knots between
disjoint pairs of strands. You are to find the probability that the knotted strands form one big loop (in which
case the couple will be allowed to marry).
For example, suppose that N = 4 and you number the strands 1, 2, 3, 4. Also suppose that the girl has created
the following pairs of strands by tying knots: {(1, 4), (2,3)}. Then the groomtobe has two choices for tying
the knots on his side: {(1,2), {3,4)} or {(1,3), (2,4)}.
Input
The input file consists of one or more lines. Each line of the input file contains a positive even integer, less
than or equal to 100. This integer represents the number of strands in the wall.
Output
For each line of input, the program will produce exactly one line of output: the probability that the knotted
strands form one big loop, given the number of strands on the corresponding line of input. Print the
probability to 5 decimal places.
Sample input
4
20
Output for sample input
0.66667
0.28377
Problem: Marbles in Three Baskets
Each of three baskets contains a certain number of marbles. You may move from one basket into another
basket as many marbles as are already there, thus doubling the quantity in the basket that received the
marbles. You must find a sequence of moves that will yield the same number of marbles in the three baskets.
Moreover, you must achieve the goal in the smallest possible number of moves. Your program must also
recognize the case in which there is no such sequence of moves.
Input
Each line of the input file will contain data for one instance of the problem: three positive integers, with one
blank space separating adjacent integers. The three integers represent the initial numbers of marbles in the
three baskets. The sum of the three integers will be at most 60.
Output
The output will begin with the initial configuration from the input. Thereafter, on successive lines, the number
of marbles in the respective baskets will be printed after each move, concluding with the line in which the
three numbers are identical. As stated above, the goal must be achieved in the smallest possible number of
moves. (The correct output is not unique, however. There may be different sequences of moves which achieve
the goal correctly in the smallest possible number of steps.) If there is no sequence of moves to achieve the
goal, only the initial configuration will be printed. Each integer in the output will be rightjustified in a field
of width 4. Each instance of the problem will be concluded by a line of 12 equal signs.
Sample input
6 7 11
15 18 3
567

Output for sample input


6 7 11
6 14 4
12 8 4
888
============
15 18 3
12 18 6
12 12 12
============
567
============

77. Problem: Permutation Recovery


Professor Permula gave a number of permutations of the n integers 1, 2, ..., n to her students. For each integer
i (1 <= i <= n), she asks the students to write down the number of integers greater than i that appears before i
in the given permutation. This number is denoted ai. For example, if n = 8 and the permutation is
2,7,3,5,4,1,8,6, then a1 = 5 because there are 5 numbers (2, 7, 3, 5, 4) greater than 1 appearing before it.
Similarly, a4 = 2 because there are 2 numbers (7, 5) greater than 4 appearing before it.
John, one of the students in the class, is studying for the final exams now. He found out that he has lost the
assignment questions. He only has the answers (the ai's) but not the original permutation. Can you help him
determine the original permutation, so he can review how to obtain the answers?
Input
The input consists of a number of test cases. Each test case starts with a line containing the integer n (n <=
500). The next n lines give the values of a1, ..., an. The input ends with n = 0.
Output
For each test case, print a line specifying the original permutation. Adjacent elements of a permutation should
be separated by a comma. Note that some cases may require you to print lines containing more than 80
characters.
Sample input
8
5
0
1
2
1
2
0
0
10
9
8
7
6
5
4
3
2
1
0
0
Output for sample input
2,7,3,5,4,1,8,6
10,9,8,7,6,5,4,3,2,1

78. Problem: String Equations


We all understand equations such as:
3+8=4+7
But what happens if we look at equations with strings instead of numbers? What would addition and equality
mean?
Given two strings x and y, we define x + y to be the concatenation of the two strings. We also define x = y to
mean that x is an anagram of y. That is, the characters in x can be permuted to form y.
You are given n distinct nonempty strings, each containing at most 10 lowercase characters. You may also
assume that at most 10 distinct characters appear in all the strings. You need to determine if you can choose
strings to put on both sides of an equation such that the "sums" on each side are "equal" (by our definitions
above). You may use each string on either side 0 or more times, but no string may be used on both sides.
Input
The input consists of a number of cases. Each case starts with a line containing the integer n (2 <= n <= 100).
The next n lines contain the n strings. The input is terminated with n = 0.
Output
For each case, print either "yes" or "no" on one line indicating whether it is possible to form an equation as
described above. If it is possible, print on each of the next n lines how many times each string is used, with the
strings listed in the same order as the input. On each line, print the string, followed by a space, followed by
the letter "L", "R", or "N" indicating whether the string appears on the left side, the right side, or neither side
in the equation. Finally, this is followed by a space and an integer indicating how many times the string
appears in the equation. Each numeric output should fit in a 64bit integer.
If there are multiple solutions, any solution is acceptable.
Sample input
2
hello
world
7
i
am
lord
voldemort
tom
marvolo
riddle
0
Output for sample input
no
yes
iL1
am L 1
lord L 1
voldemort L 1
tom R 1
marvolo R 1
riddle R 1

79. Problem: Toothpick Arithmetic


A toothpick expression uses toothpicks to represent a positive integer. The expression consists of operands
and operators.
Each operand consists of one or more vertical toothpicks ("|"); the value of the operand is the number of
toothpicks.
The operators that can appear in an expression are addition and multiplication. The addition operator is the
plus sign ("+"), which consists of one vertical and one horizontal toothpick. The multiplication operator is the
letter "x", which also consists of two toothpicks. Multiplication has precedence over addition.
The expression must begin with an operand. Thereafter, operators and operands alternate. Finally, the
expression must end with an operand. Given a positive integer, your program must represent it as a toothpick
expression, using the smallest number of toothpicks.
Input
The input file will consist of one or more lines; each line will contain data for one instance of the problem.
More specifically, each line will contain one positive integer, not exceeding 5000.
Output
Each line of input will give rise to one line of output, consisting of: the number of toothpicks used in the
expression, the expression, and the given integer from the input, formatted as shown in the sample output. The
word "toothpicks" (even if the answer is 1) will be preceded by one blank space and followed by a colon and
one blank space. An equal sign (but no blank spaces) will separate the expression from the given number. The
expression should not contain any spaces.
If there are multiple expressions which use the smallest number of toothpicks, any such expression is
acceptable.
Sample input
35
37
53
Output for sample input
14 toothpicks: |||||||x|||||=35
17 toothpicks: ||||||x||||||+|=37
21 toothpicks: |||||x|||||x||+|||=53

80. PROBLEM: WACMIAN NUMBERS


In the supposedly uninhabited Wacmahara Desert, a tribe of unusual people has
been discovered. The Wacmians have only 2 fingers and a thumb on each hand,
and have invented their own numbering system. The digits they use and the
symbols they use for digits are quite unusual, but anthropologists have been able
to represent them as follows:
% represents 0
) represents 1
~ represents 2
@ represents 3
? represents 4
\ represents 5
$ represents -1 (yes, they even have a negative digit)
As you may expect, their system is base 6 where each place value is 6 times the
value to its right, as in the following examples:
)@% is 1*62+3*6+0 = 36+18+0 = 54
?$~~ is 4*63+(1)*62+2*6+2 = 86436+12+2 = 842
$~~ is (1)*62+2*6+2 = 36+12+2 = -22
Your task is to take Wacmian numbers and represent them as standard base 10
numbers.
INPUT FORMAT
Input consists of Wacmian numbers, one per line. Each number consists of a
sequence of 1 to 10 Wacmian digits. A single # on a line by itself indicates the
end of input.
OUTPUT FORMAT
Output will be the corresponding decimal numbers, one per line.
SAMPLE INPUT:
)@%
?$~~
$~~
%
#
SAMPLE OUTPUT:
54
842
-22
0

81. PROBLEM: CD TITLES


A keen photographer, I found my hard disk quickly filling up with snapshots and
videos. I decided to offload a lot of the files to CD. Each CD is in its own plastic
case, and the contents are clearly described on the front of the case. As the
number of CDs increased, I built myself a shelf on which the CDs stand vertically.
I need your help! I have written a title for each CD into a text file, but I need the
titles to appear vertically so that I can put them in the spine of the CD cases and
be able to read them easily from the shelf. I want you to write a program that will
output my titles vertically. I need lines between each title so that, when I print
them, I can easily cut along the lines.
I have worked out that I can fit 36 characters into the available space, so all
output titles must be 36 characters long, padded with spaces at the end where
necessary. If I accidentally make a title too long, only output the first 36
characters.
INPUT FORMAT
Input will be at most 50 titles, one to a line. Each title consists of 1 to 100 arbitrary
characters. A single # on a line by itself indicates the end of input.
OUTPUT FORMAT
Output will be the same titles presented vertically, where the left to right order will
be the same as the order of the input. There will be a column of bar (|)
characters at each end, and separating each title, and a row of minus (-)
characters (1 per column) at the beginning and end.
SAMPLE INPUT:
012345678901234567890123456789012345
David and Janes wedding, March 2002, Alexandria
Bahamas Holiday August 2001
#
SAMPLE OUTPUT:
------|0|D|B|
|1|a|a|
|2|v|h|
|3|i|a|
|4|d|m|
|5| |a|
|6|a|s|
|7|n| |
|8|d|H|
|9| |o|
|0|J|l|
|1|a|i|
|2|n|d|
|3|e|a|
|4||y|
|5|s| |
|6| |A|
|7|w|u|
|8|e|g|
|9|d|u|
|0|d|s|
|1|i|t|
|2|n| |
|3|g|2|

|4|,|0|
|5| |0|
|6|M|1|
|7|a| |
|8|r| |
|9|c| |
|0|h| |
|1| | |
|2|2| |
|3|0| |
|4|0| |
|5|2| |
-------

82. PROBLEM 3 - CAESAR CIPHER


Julia has decided to encrypt her notes so that nobody else could understand
them. The code is based on the so-called Caesar Cipher where each letter is
shifted a certain number of places left or right through the alphabet. In this
context, the alphabet is treated as being circular so that the first letter follows
after the last letter, and the last letter precedes the first letter.
Julia applies these ideas separately to uppercase letters, lower case letters, and
digits. For example, with a shift of 1, A becomes B, Z becomes A, a becomes
b, z becomes a, 0 becomes 1, 9 becomes 0. Spaces, punctuation, and
any other symbols are not affected in this scheme.
Your task is to help Julia encrypt her notes.
INPUT FORMAT
Each line of input begins with a number representing the shift. The number will be
in the range -1,000,000,000 to 1,000,000,000. The number is followed by a colon
(:). The rest of the line consists of a string of 1 to 200 arbitrary characters and
represents a fragment of the text to be encrypted. A single # on a line by itself
indicates the end of input.
OUTPUT FORMAT
Output will be the corresponding encrypted text fragments, one per line.
SAMPLE INPUT:
0:Clear text!
1:David and Janes wedding, March 2002, Alexandria
-1:Bahamas Holiday August 2001
53:ACMZ, acmz, 0379!
26000000:ACMZ, acmz, 0379!
26000001:ACMZ, acmz, 0379!
#
SAMPLE OUTPUT:
Clear text!
Ebwje boe Kboft xfeejoh, Nbsdi 3113, Bmfyboesjb
Azgzlzr Gnkhczx Ztftrs 1990
BDNA, bdna, 3602!
ACMZ, acmz, 0379!
BDNA, bdna, 1480!

83. PROBLEM: WATER TANKS


There are n identical large cylindrical tanks for storing water. The tanks are arranged
in a circle on level ground. Each tank is connected with its two neighbours by means
of pipes situated at its base. There is a valve between each adjacent pair of tanks
(tank n is next to tank 1). All valves are initially closed. All the outlets and the pipes
are at the same level and are always full of water, even if all the tanks are deemed to
be empty.
The volume in any tank is measured by the height of the surface of the water above
the level of the top of the outlets. If all valves (or all valves but one) are opened so
that water can flow between the tanks, then the levels will eventually equalise.
Conversely, if all tanks are initially at the same level, no valves need be opened to
equalise the levels. Thus it may be necessary to only open some of the valves to
achieve this result.
For example, consider n=4 tanks each 5 metres high. Assume that the water level in
these tanks is at 4, 4, 3, and 3 meters respectively. Their water level will equalise if
we open the valves between tanks #2 and #3 and between #4 and #1, as suggested
by the following diagram. Thus for this set we need to open only two valves:
Given a set of initial heights, determine the minimum number of valves to open so
that the final water levels in all tanks is equal.

INPUT FORMAT
The input will consist of one or more scenarios, each scenario consisting of two lines.
The first line contains a descriptive title, which is a string of letters or spaces no more
than 200 characters long, containing at least 1 letter.
The second line starts with the number of basins n (3 n 200), a space, and then n
integers in the range 0 to 99, separated by single spaces, representing the water
levels in the tanks.
The scenarios sequence is terminated by a single # character on a line by itself.
OUTPUT FORMAT
Output one line for each input scenario. The line consists of the first letter of each
word in the descriptive title in upper case, followed by a colon (:), a space, and then
the minimum number of valves that need to be open to achieve equal heights in all
tanks.
SAMPLE OUTPUT:
HFDB: 2
TAE: 5
SAMPLE INPUT:
High four dude basins
44433

The Australasian eight


821122116
#
SAMPLE INPUT:
High four dude basins
44433
The Australasian eight
821122116
#

84. PROBLEM : SPOTS


Painting tiles is hard work. John has convinced his two sons Raul and George to do a
painting job, by agreeing to pay one dollar per tile painted by each of them. Raul will
paint red tiles and George green tiles at the places indicated by their father.
However, they are still not convinced: How are they going to divide up the area to be
painted, what happens if both want to paint the same tile at the same time, what are
the rules, and, last, but not least, how much will they receive in the end?
To avoid arguments and to have some fun, John would like to show them a
simulation of the problem before the hard work begins. The simulation will start with
each son at opposite ends of a rectangular grid of width N and height M (N,M 2),
Raul at (0,0) and George at (N-1, M-1). The two sons will begin by painting a spot in
their respective colours on their starting tiles. Next, Raul and George are each given
a series of individual instructions for moving to the next tile to paint. Each move can
be repeated one or more times and is defined by a pair of increments along the
horizontal x-axis and vertical y-axis, in this order; these increments can be positive,
negative, or zero.
For example, assume that Raul is on his initial tile (0,0) on a grid with N=10, M=5,
and receives the instructions to hop 2 times in the direction of (1,0) and then 3 times
in the direction of (2,1). He will begin by painting a red spot on the tile (0,0). Then,
according to these instructions, he will successively land on and paint red spots on
the following tiles: (1,0), (2,0), (4,1), (6,2), (8,3). The following diagram uses the letter
R to mark the tiles spotted in red by Raul according to his instructions:

At each simulation step the two sons move in lock-step, each hopping according to
his own instructions. To avoid conflicts, each time Raul and George are about to hop
to the next tile the simulation must check whether they would land on the same tile.
If so, the simulation ends without them moving, and the landing tile remains painted
in its previous colour, if any. Otherwise, the simulation will end as soon as one of the
sons ends his instructions.
Each tile can contain only one colour spot, either red or green. Since it is possible
that Raul and George land on the same tile at different times, the simulation should
only count the tile towards the son landing there last.
To avoid Raul and George falling off the edge of the tile grid, they are allowed to
wrap around, in all directions. For example, for a grid of the same size as above, one
hypothetical move from (8,3) in the direction (2,3) results in the tile (0,1).
y
x
Your task is to write a program that computes the results of such a simulation given
the grid size and the instructions for each son.
INPUT FORMAT
The input consists of one or more scenarios. Each scenario consists of 3 lines. The
first line contains two numbers separated by a space, N and M, 2 N, M 1000,
respectively representing the width and the height of the grid. The second line

contains the instructions for Raul and the third line the instructions for George. Each
instruction line starts with a number C, in the range 1 to 100, followed by C groups of
3 numbers. In each group the first number is a repetition count in the range 1 to
1,000,000,000, the second number is an increment along the x-axis, and the third
number an increment along the y-axis - both increments are in the range -1,000 to
1,000. All numbers are separated by single spaces. The end of the input is indicated
by a grid of size 0, i.e., a 0 on a line by itself.
OUTPUT FORMAT
Output one line for each input scenario. Each output line should show two numbers
separated by a single space, representing the earnings of Raul and George, in this
order.
SAMPLE INPUT:
10 5
2210321
3 4 -2 0 1 0 -9 2 1 0
10 10
2 1 15 5 1 0 0
2 1 0 0 2 -4 -4
10 7
2 1000 2 -1 1000 0 -1
2 1000 -1 0 1000 -1 0
10 10
5 1000 2 -1 1000 1 0 2 5 5 3 1 1 10 1 1
5 1000 -1 0 1000 0 1 3 -4 -4 2 -1 -1 10 -1 -1
0
SAMPLE OUTPUT:
56
21
30 10
18 18

85. PROBLEM: MOBILE PHONES


ACMIA mobile phones have a shortcut mode for typing text messages using the
numerical phone keypad. In this mode, the system uses a dictionary of known words.
After a sequence of digits is entered the system checks for and displays all possible
matches in the dictionary. The ACMIA phone keypad for the English alphabet is as
follows:

Your task is to write a program that displays all possible matches for given digit
sequences, using a given dictionary.
A digit sequence corresponds to a sequence of words, with zero digits (0) indicating
spaces. Leading and trailing zeros are ignored, and multiple consecutive embedded
zeros are treated as a single zero. For each sequence of non-zero digits, display the
matching word from the dictionary. When more than one match is available, display
all matches in dictionary order between round parentheses and separated by bars
(|). If there is no matching word, display a sequence of asterisks (*) of the same
length. For example, with a dictionary consisting solely of the words i, loud,
love, programming, the digit sequence
0040568300077647266464077770
will be displayed as the text
i (loud|love) programming ****
INPUT FORMAT
The input will consist of one or more scenarios, each scenario consisting of a
dictionary of permitted words and a series of digit sequences to be interpreted as text
messages.
The dictionary consists of 1 to 1,000 words, one word per line, in increasing
dictionary order, with no duplicates. Each word consists of 1 to 30 lowercase letters.
For any given non-zero digit sequence there will be no more than 10 matching words
in the dictionary. The end of the dictionary is indicated by a line consisting of a single
#.
The digit sequences to interpret as text messages follow the dictionary, one per line.
Each message line consists of 1 to 100 digits, with at least 1 non-zero digit. The end
of messages is indicated by a line consisting of a single #.
The end of input is indicated by an empty dictionary (a dictionary with zero words).
OUTPUT FORMAT
For each scenario output a line consisting of the word SET (all uppercase) followed
by a space and then the scenario number, starting with 1. Following this output the
list of interpreted text messages, one message per line.
SAMPLE INPUT:
i
loud
love
programming
#
0040568300077647266464077770

#
a
game
go
golf
good
hand
hold
hole
home
in
me
of
to
#
2046630426306304653
46086020466304663
#
#
SAMPLE OUTPUT:
SET 1
i (loud|love) programming ****
SET 2
a (good|home) (game|hand) (me|of) (golf|hold|hole)
(in|go) to a (good|home) (good|home)

86. PROBLEM: COLOUR GRIDS


You are given a number of plastic tiles, all of the same size, and a target pattern.
Your task is to assemble the tiles into a pile so that, looking from the top, it matches
the target pattern. Each tile is composed of 16 squares of transparent or coloured
plastic (opaque and identically coloured on both faces), arranged in a 4x4 grid. The
target pattern is also a grid of colours, similar to a tile, but without transparencies.
The tiles can be rotated clockwise through multiples of 90 and/or flipped about a
horizontal axis. This leads to 8 possible transformations - rotated 0, 1, 2 or 3 times,
or a flip followed by the same sequence of rotations. These transformations, in the
above order, are numbered 0 to 7. The following diagrams provide an example, with
colours denoted by upper case letters, and dots (.) representing transparency:

Write a program that will read in a sequence of tiles and a target pattern and
determine whether the target pattern can be made by some arrangement of all or
some of the input tiles.
If there are several ways of achieving the target, then choose the pile with fewest tiles.
If there are still several ways of achieving the target, then at every point in the pile, in a topdown order,
choose first the lowest numbered appropriate tile and, if still needed, the lowest numbered appropriate
transformation.
INPUT FORMAT
The input will consist of one or more of problems. The first line of each problem
contains the title of the problem as a string of 1 to 30 characters other than space,
followed by a space, and the number of tiles n (1 n 10). This is followed in turn by
n+1 lines, the first n lines specifying the tiles (implicitly numbered 0 to n-1); and the
last line specifying the target pattern. Each of these n+1 lines contains 4 blocks of 4
characters, either an upper case letter representing a colour, or a full stop (.)
representing transparency. Blocks are separated by single spaces and represent grid
rows, in successive row order. Characters composing blocks represent grid cells, in
successive column order. The end of input is signified by a line consisting of a single
#.

OUTPUT FORMAT
Output consists of one line for each problem, consisting of the title of the problem,
followed by a space, and either the word noway (all lowercase) if the target cannot
be achieved, or a description of the pile if the target can be achieved. The tiles in the
pile should be listed in order from the top of the pile downwards, in the form: tile
number (0 through n-1), slash (/), transformation number (0 through 7). Separate
descriptions of successive tiles by single spaces.
SAMPLE INPUT:
OBVIOUS 1
RRGG RRGG YYBB YYBB
BBGG BBGG YYRR YYRR
EASY 2
BBBB BBBB ..BB ..BB
RRRR RRRR .... ....
RRRR RRRR BBBB BBBB
Is-this-possible? 2
BBBB BBBB ..BB ..BB
RRRR RRRR .... ....
RRBB RRBB BBRR BBRR
#
SAMPLE OUTPUT:
OBVIOUS 0/7
EASY 1/0 0/1
Is-this-possible? noway

87. PROBLEM: POSTAL VANS


A new suburb has been established with 4 avenues running WestEast and N streets
running NorthSouth, where 1 N 1000. On the map, the suburb is a rectangular
grid and the post office is at its North-West corner.
For example, the following diagram shows such a suburb with N=5 streets, with the
avenues depicted as horizontal lines, and the post office as a dark blob at the topleft
corner:

Each day the postal van leaves the post office, drives around the suburb and returns
to the post office, passing exactly once through every intersection (including those on
borders or corners). The executives from the post company want to know how many
distinct routes can be established for the postal van (of course, the route direction is
significant in this count).
For example, the following diagrams show 2 such routes for the above suburb:

As another example, the following diagrams show all the 4 possible routes for a
suburb with N=3 streets.

Write a program that will determine the number of such distinct routes given the
number of streets.
INPUT FORMAT
The input text consists of one or more lines, each containing a single number from 1
to 1000 inclusive the number of parallel streets. A single # on a line by itself
indicates the end of input.

OUTPUT FORMAT
There is a single line of output for each input value. Each output line consists of the
number of streets followed by a colon (:) and a space, followed by the number of
possible distinct routes corresponding to that many streets. Each number is
displayed as a decimal number, with commas (,) used as separators between
groups of 3 digits, counting from the right.
SAMPLE INPUT:
1
2
3
4
10
30
#
SAMPLE OUTPUT:
1: 0
2: 2
3: 4
4: 12
10: 3,034
30: 374,605,036,706

88. PROBLEM: TRICKY TREES


The stream of tourists passing through the enchanted forest of Acmagorn is drying
up because most people have seen it already and dont see the point of seeing it
again. This is worrying the custodians of the forest because they rely on the money
that tourists spend to manage the forest (and to pay their salaries). In an attempt to
bring the tourists back again, they have devised a plan to make the forest look a bit
different every day someone sees it. According to this plan, every night the trees
randomly rearrange the order of their branches. Although the rearrangement doesnt
change the structure of the trees, it can make their appearance quite different.
For example, images (a) and (b) below could show two possible rearrangements of
the same tree. Of course, trees that are structurally different trees will always look
different, no matter what rearrangement occurs. The trees in images (c) and (d) will
never look the same as each other, because they are structurally different - nor will
either (c) or (d) look the same as either (a) or (b).

As another example, the images (e) and (f) below could also show two possible
rearrangements of the same tree.

This plan is a great success and the tourists are flocking back to see the constantly
changing forest. Our friends Mary and Paul have been there several times and each
time theyve brought home many good pictures. They have now decided to put a bit
of order in their collection of pictures, by identifying all matching tree images, i.e., all
images that could represent the same tree. To achieve this result, they intend to
associate a tag number with each image, such that images of trees are given the
same tag if, and only if, they match. For examples, the images (a), (b), (c), (d) above
could receive the tags 0, 0, 1, 2, in this order.
They have started by coding their collection of tree images. For each tree they
labelled each node, in no particular order, with a distinct number in the range 0 to k1, where k is the number of the nodes in that tree.
Your task is to write a program that will allow them to identify matching tree images.
INPUT FORMAT
Input consists of one or more scenarios, with each scenario consisting of a number of
tree images. Each scenario starts with a line containing a single number, n (1 n
100) specifying the number of images in the scenario, followed by n lines containing
image descriptions. Each image description line has at most 5,000 characters and
consists of a number k (1 k 1000) specifying the number of nodes in the tree,
followed by k numbers in the range -1 to k-1, specifying the parent of each node in

turn, using -1 for the root node (which has no parent). The sequence of scenarios is
terminated by an empty scenario, i.e., a line consisting of single zero (0).
OUTPUT FORMAT
Output consists of one line for each scenario, beginning with a scenario sequence
number (starting with 1), a colon (:), a space, and followed by a succession of tag
numbers, one for each image, in input order, and separated by single spaces. Tag
numbers are allocated successively in input image order, starting with 0, and
increased by 1 at the first occurrence of an image not matching any of the previous
images.
SAMPLE INPUT:
4
7 -1 0 0 6 6 6 0
7 -1 3 3 0 3 0 0
7 -1 0 1 1 6 6 1
7 -1 3 3 0 5 0 0
2
13 -1 0 0 0 1 1 2 2 3 4 4 5 6
13 -1 0 0 0 1 1 2 3 3 5 7 8 8
5
2 -1 0
3 -1 0 0
2 1 -1
3 -1 0 1
3 2 2 -1
0
SAMPLE OUTPUT:
1: 0 0 1 2
2: 0 0
3: 0 1 0 2 1

89. Problem: Euchre Results


Anna, Betty, Cindy and Zelda like playing the card game Euchre. Euchre is a game for two teams of
two, and each time they meet the girls split off into different teams. They also keep overall records of
the number of games each player has won and lost. Anna has misplaced her won-loss results, but she
does have the results of the other three players. Given this, she figures she can determine her won-loss
record
Input
Input will consist of multiple problem instances. Each instance will consist of a single line containing
six integers. The first two are the number of wins and losses (respectively) for Betty, the next two are
the number of wins and losses for Cindy and the last two are the number of wins and losses for Zelda.
A final line of six zeroes will terminate input and should not be processed.
Output
For each problem instance, output a single line indicating Anna's won-loss record, in the format shown
in the example below.
Sample Input
10 3 6 7 8 5
1874 2945 2030 2789 1025 3794
000000
Sample Output
Anna's won-loss record is 2-11.
Anna's won-loss record is 4709-110.

90. Problem: Least Common Multiple


The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is
divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105.
Input
Input will consist of multiple problem instances. The first line of the input file will contain a single
integer indicating the number of problem instances. Each instance will consist of a single line of the
form m n1 n2 n3 nm where m is the number of integers in the set and n1 nm are the integers. All
integers will be positive and lie within the range of a 32-bit integer.
Output
For each problem instance, output a single line containing the corresponding LCM. All results will lie
in the range of a 32-bit integer.
Sample Input
2
3 5 7 15
6 4 10296 936 1287 792 1
Sample Output
105
10296

91. Problem: Granny's Bike


Most days Granny rides her bike around town to do errands, visit, have a cup of coffee, and so on. She
enjoys riding her bike and wants to avoid passing the same place twice to add to the interest of the
ride. So, each day she draws a map of the places to be visited, with lines connecting those near each
other, and sees if she can visit them all and return home without passing a place more than once. Some
days she finds she can do this and other days she finds she can't. For example, for the map on the left,
Granny can visit every place and return home without passing any place twice, but she can't do it for
the map on the right.

She turns to you to write a program to help her.


Input
There will be multiple test cases for this problem. Each test case will have input on multiple lines. The
first line will contain the integer n (< 10) noting the number of places Granny wants to visit that day.
These will be numbered 1 through n and Granny's house will be numbered 0. The next n lines will be
a list of those places near each spot. The first line will be a list of places with a direct route from place
1. The second line will be a list of places with a direct route from place 2, and so on. You may assume
that if place i has a direct route to place j, then there is a direct route the other direction also. A line
containing 0 will follow the last test case.
Output
For each test case, print one line of the form:
Case m: Granny can make the circuit.
Or
Case m: Granny can not make the circuit.
as appropriate. Here, m is the number of the test case, starting at 1.
Sample Input
5
025
013
24
035
14
4
0234
13
12
01
0
Sample Output
Case 1: Granny can make the circuit.
Case 2: Granny can not make the circuit.

92. Problem: Crypto Columns


The columnar encryption scheme scrambles the letters in a message (or plaintext) using a keyword
as illustrated in the following example: Suppose BATBOY is the keyword and our message is MEET ME
BY THE OLD OAK TREE. Since the keyword has 6 letters, we write the message (ignoring spacing and
punctuation) in a grid with 6 columns, padding with random extra letters as needed:
MEETME
BYTHEO
LDOAKT
REENTH
Here, we've padded the message with NTH. Now the message is printed out by columns, but the columns
are printed in the order determined by the letters in the keyword. Since A is the letter of the keyword
that comes first in the alphabet, column 2 is printed first. The next letter, B, occurs twice. In the
case of a tie like this we print the columns leftmost first, so we print column 1, then column 4. This
continues, printing the remaining columns in order 5, 3 and finally 6. So, the order the columns of the
grid are printed would be 2, 1, 4, 5, 3, 6, in this case. This output is called the ciphertext, which in this
example would be EYDEMBLRTHANMEKTETOEEOTH. Your job will be to recover the plaintext when given
the keyword and the ciphertext.
Input
There will be multiple input sets. Each set will be 2 input lines. The first input line will hold the
keyword, which will be no longer than 10 characters and will consist of all uppercase letters. The
second line will be the ciphertext, which will be no longer than 100 characters and will consist of all
uppercase letters. The keyword THEEND indicates end of input, in which case there will be no ciphertext
to follow.
Output
For each input set, output one line that contains the plaintext (with any characters that were added for
padding). This line should contain no spacing and should be all uppercase letters.
Sample Input
BATBOY
EYDEMBLRTHANMEKTETOEEOTH
HUMDING
EIAAHEBXOIFWEHRXONNAALRSUMNREDEXCTLFTVEXPEDARTAXNAARYIEX
THEEND
Sample Output
MEETMEBYTHEOLDOAKTREENTH
ONCEUPONATIMEINALANDFARFARAWAYTHERELIVEDTHREEBEARSXXXXXX

93. Problem: Decorations


The Sultan of Sylvania loves throwing parties, because that gives him a reason to decorate the palace.
He particularly likes decorations called streamers made up of different beads strung together on a string
and hung from the ceiling. Now, like most Sultans, he is very particular about everything, including
these strung decorations. Specifically, he only likes certain combinations of beads to be used on the
streamers. For example, if there are four different types of beads { A, B, C and D { the Sultan might
say It pleases his highness that only the combinations ABB, BCA, BCD, CAB, CDD and DDA appear in
the streamers at tonight's party". This, needless to say, puts a severe limit on the number of different
streamers possible. For example, if the length of the streamers was 5, then the only possible streams
of beads would be BCABB and BCDDA (strings such as ABBCA could not be used because BBC is not an
approved combination). Since the Sultan likes variety, it is important to know the total number of
streamers possible, given a length and the current bead combinations which tickle the Sultan's fancy.
Input
Input will consist of multiple test cases. Each case will consist of two lines. The first line will contain
three positive integers n, l and m, where n indicates the number of bead types, l is the length of the
streamers and m indicates the number of bead combinations which the Sultan likes. The maximum
values for n, l and m will be 26, 100 and 600, respectively. The next line will contain the m combinations.
Each combination will be of the same length (between 1 and 10) and will be separated using a single
space. All combinations will make use of only the uppercase letters of the alphabet. An input line of 0
0 0 will terminate input and should not be processed.
Output
For each test case, output a single line indicating the number of possible streamers. All answers will be
within the range of a 32-bit integer.
Sample Input
456
ABB BCA BCD CAB CDD DDA
545
EDCBA
483
AA BB CC
000
Sample Output
2
625
3

94. Problem: EKG Sequence


The EKG sequence is a sequence of positive integers generated as follows: The first two numbers of
the sequence are 1 and 2. Each successive entry is the smallest positive integer not already used that
shares a factor with the preceding term. So, the third entry in the sequence is 4 (being the smallest
even number not yet used). The next number is 6 and the next is 3. The first few numbers of this
sequence are given below.
1, 2, 4, 6, 3, 9, 12, 8, 10, 5, 15, 18, 14, 7, 21, 24, 16, 20, 22, 11, 33, 27
The sequence gets its name from its rather erratic fluctuations. The sequence has a couple of interesting,
but non-trivial, properties. One is that all positive integers will eventually appear in the sequence.
Another is that all primes appear in increasing order. Your job here is to find the position in the
sequence of a given integer.
Input
Input consists of a number of test cases. Each case will be a line containing a single integer n, 1 <= n <= 300000.
An input of 0 follows the last test case. Note that the portion of the EKG sequence that
contains all integers <= 300,000 will not contain an integer >1,000,000.
Output
Each test case should produce one line of output of the form:
The number n appears in location p.
where n is the number given and p is the position of n in the EKG sequence. You are guaranteed that
p will be no larger than 1,000,000.
Sample Input
12
21
2
33
100000
299977
0
Sample Output
The number 12 appears in location 7.
The number 21 appears in location 15.
The number 2 appears in location 2.
The number 33 appears in location 21.
The number 100000 appears in location 97110.
The number 299977 appears in location 584871.

95. Problem: Phone Home


When relay towers for mobile telephones communicate with the mobile phones in their area, there is
always the possibility of interference. So, when assigning the transmission frequency, the FCC makes
sure that nearby towers have frequencies that aren't too close. On the other hand, the FCC does not
want to assign too many different frequencies; they want to save as many as possible for other uses.
Your job is to find an optimal assignment of frequencies.
In this problem, the frequencies will be integers. Nearby towers must be assigned frequencies that differ
by at least 2. You'll find an assignment using as few frequencies as possible. For example, consider the
following two arrangements of towers. Two towers near each other are indicated by the connecting line.

Note that the following are legal frequency assignments to these two tower configurations. However,
the second arrangement does not use the fewest number of frequencies possible, since the tower with
frequency 5 could have frequency 1.

Input
There will be multiple test cases. Input for each test case will consist of two lines: the first line will
contain the integer n, indicating the number of towers. The next line will be of the form x1 y1 x2 y2
... xn yn where xi yi are the coordinates of tower i. A pair of towers are considered near" each other
if the distance between them is no more than 20. There will be no more than 12 towers and no tower
will have more than 4 towers near it. A value of n = 0 indicates end of input.
Output
For each test case, you should print one line in the format:
The towers in case n can be covered in f frequencies.
where you determine the value for f. The case numbers, n, will start at 1.
Sample Input
5
0 0 5 7.5 1 -3 10.75 -20.1 12.01 -22
6

0 1 19 0 38 1 38 21 19 22 0 21
0
Sample Output
The towers in case 1 can be covered in 3 frequencies.
The towers in case 2 can be covered in 2 frequencies.

96. Problem: Polly Nomials

97. Problem: Pushing Boxes


Scrap cars in a junk yard are crushed in a device that pushes the car in from the sides, from the front
and back, and from the top and bottom. The result is a compact little chunk of metal. In this problem
you're going to model a device that works in a similar manner, but doesn't crush anything, only pushes
boxes around in two dimensions. The boxes are all square with unit length on a side and are situated
on the floor of a room. Each wall of the room can be programmed to move inward a certain amount,
pushing any boxes it may bump into. Unlike the car-crusher, this device is sensitive and if it senses that
boxes are stacked up against a wall and that it might crush them if pressed any farther, it will stop.
For example, suppose we have boxes arranged in a 12-by-16 room as shown below. The upper left-hand
corners of the boxes (which is how we will locate them in this problem) are at coordinates (1,13) (box
A below), (3,2), (6,2), (6,4), (6,6), (7,6) and (8,9) (box G), where the first coordinate indicates distance
from the top wall and the second coordinate indicates distance from the left wall.

Suppose the top wall is programmed to move down 3 units (then retreats, as the walls always will) and
then the right wall is programmed to move left 14 units. The first operation can be performed with no
problem, but the second one can not be carried out without crushing some boxes. Therefore, the right
wall will move only 13 units, the maximum distance it can move until boxes are packed tightly between
it and the left wall. The boxes will then be in the configuration shown in the following figure. The
locations of the boxes are (3,1), (3,2), (6,0), (6,1), (6,2), (7,2), (8,2).

Input
There will be multiple data sets for this problem. The first line of each data set will be two integers
giving the height and width of the room. (We'll visualize the room as if on a piece of paper, as drawn
above.) Each dimension will be no more than 20. The next line will contain an integer n (0 < n <= 10)
followed by n pairs of integers, each pair giving the location of a box as the distances from the top and
the left walls of the room. The following lines will be of the form direction m, where direction is
either down, left, up, right, or done and m is a positive integer. For example, left 2 would mean

to try to move the right wall 2 spaces to the left. The \direction" done indicates that you are finished
pushing this set of boxes around. There will be no integer m following the direction done, of course.
The data sets are followed by a line containing 0 0.
Output
For each data set you are to produce one line of output of the form:
Data set d ends with boxes at locations (r1; c1) (r2; c2) (rn; cn).
where the (ri; ci) are the locations of the boxes given from top-to-bottom, left-to-right, (separated by
one space) and d is the data set number (starting at 1).
Sample Input
12 16
7 1 13 3 2 6 2 6 4 6 6 7 6 8 9
down 3
left 14
done
44
3102123
right 3
up 2
left 1
done
00
Sample Output
Data set 1 ends with boxes at locations (3,1) (3,2) (6,0) (6,1) (6,2) (7,2) (8,2).
Data set 2 ends with boxes at locations (0,2) (1,1) (1,2).

98. Problem: Squadtrees


Quadtrees are data structures used to store digital images. For our purposes, the images will be simple
bitmaps, where every pixel is either a 1 (black) or a 0 (white). A quadtree representation of a bitmap is
obtained as follows: first, associate the root node with the entire image. If the entire image is either all
1's or all 0's, then store that value in the node and you're done. Otherwise divide the region into four
equal size quadrants, add four children to the root, and assign each child one of the four regions in the
following order: the first child gets the upper left quadrant, the second the upper right, the third the
lower left and the fourth the lower right. Then recursively apply the above rules to each of the children.
For example, the 4x4 image on the left would be represented by the quadtree on the right:

Note that this procedure only works as stated if the image is a square and has a side length equal to
a power of 2. For those images which do not meet those requirements, we pad the rows and columns
with 0's (on the right and on the bottom, respectively) until we have a bitmap of the appropriate size.
For example, a 5x13 image would be converted to a 16x16 bitmap (with the original image residing in
the upper left portion, and the remainder of the image filled with 0's).
While quadtrees can result in a significant savings in space over the original image, even more savings
can be achieved if we identify repeated subtrees. For example, in the tree above, the first and third
subtrees of the root are identical, so we could replace the root of the third subtree with a reference to
the first subtree, obtaining something that symbolically looks like the following:

We will call these compressed quadtrees super quadtrees, or squadtrees. For our purposes the use of a
reference saves space only when the tree it replaces has height of at least 1. Thus, while we could replace
5 of the nodes which contain a B with references to the first node with a B, this would not in practice
save any space in the compression. Using this rule, our squadtree contains only 12 nodes, as opposed
to 17 in the original quadtree. Your job for this problem is to take a set of images and determine the
number of nodes in both the resulting quadtrees and squadtrees.
Input
Input will consist of multiple problem instances. Each instance will start with a single line containing
two integers n and m, indicating the number of rows and columns in the image. The maximum values
for these integers is 128. The next n lines will each contain m characters representing the image to
process. A black pixel will be represented by a `1', and a white pixel will be represented by a `0'. The
input line 0 0 will terminate input and should not be processed.
Output
For each problem instance, output two integers separated by a single space. The first value is the
number of nodes in the quadtree for the problem instance, and the second is the number of nodes in
the squadtree.
Sample Input

44
1011
0111
1010
0111
67
1110111
1010101
0000000
0100010
1011101
1010101
00
Sample Output
17 12
61 24

99. Problem: This Takes the Cake


In the kingdom of Polygonia the royal family consists of the king, the queen, and the 10-year-old twins,
Prince Obtuse and Prince Trisect. The twins are fiercely competitive, and on their birthday they
always vie with each other for the biggest portion of the cake. The wise king and queen have devised
the following way to prevent squabbles over the cake. One prince is allowed to cut the cake into two
pieces, then the other prince gets to choose which of the two pieces he wants.
Cakes in Polygonia are always in the shape of a convex quadrilateral (a four-sided polygon with each
internal angle less than 180 degrees). Furthermore, local custom dictates that all cake cutting must be
done using a straight cut that joins two vertices, or two midpoints of the sides of the cake, or a vertex
and a midpoint. For instance, the following figure shows all the possible legal cuts in a typical cake.

Your problem is to determine, for a number of dierent cakes, the best cut, i.e., the one that divides the
cake into two pieces whose areas (we are disregarding the thickness of the cake) are as nearly equal as
possible. For instance, given a cake whose vertices (when the cake is viewed from above) are located, in
counterclockwise order, at the points (0; 1), (6; 0), (5; 2) and (2; 3), the best possible cut would divide
the cake into two pieces, one with area 4.375, the other with area 5.125; the cut joins the points (1; 2)
and (5:5; 1) (the midpoints of two of the sides).
Input
Input consists of a sequence of test cases, each consisting of four (x; y) values giving the counterclockwise
traversal of the cake's vertices as viewed from directly above the cake; the final test case is followed by
a line containing eight zeros. No three points will be collinear, all quadrilaterals are convex, and all
coordinates will have absolute values of 10000 or less.
Output
For each cake, the cake number followed by the two areas, smaller first, to three decimal places of
precision.
Sample Input
01605223
0 0 100 0 100 100 0 100
00000000
Sample Output
Cake 1: 4.375 5.125

100.Problem: Quick Change


J.P. Flatheads Grocery Store hires cheap labor to man the checkout stations. The people he hires (usually high
school kids) often make mistakes making change for the customers. Flathead, whos a bit of a tightwad, figures he
loses more money from these mistakes than he makes; that is, the employees tend to give more change to the
customers than they should get.
Flathead wants you to write a program that calculates the number of quarters ($0.25), dimes ($0.10), nickels
($0.05) and pennies ($0.01) that the customer should get back. Flathead always wants to give the customers
change in coins if the amount due back is $5.00 or under. He also wants to give the customers back the smallest
total number of coins. For example, if the change due back is $1.24, the customer should receive 4 quarters, 2
dimes, 0 nickels, and 4 pennies.
Input
The first line of input contains an integer N which is the number of datasets that follow. Each dataset consists of a
single line containing a single integer which is the change due in cents, C, (1 C 500).
Output
For each dataset, print out the dataset number, a space, and the string:
Q QUARTER(S), D DIME(S), n NICKEL(S), P PENNY(S)
Where Q is he number of quarters, D is the number of dimes, n is the number of nickels and P is the number of
pennies.
Sample Input

Sample Output

3
124
25
194

1 4 QUARTER(S), 2 DIME(S), 0 NICKEL(S), 4 PENNY(S)


2 1 QUARTER(S), 0 DIME(S), 0 NICKEL(S), 0 PENNY(S)
3 7 QUARTER(S), 1 DIME(S), 1 NICKEL(S), 4 PENNY(S)

101.Problem: Shufflem Up
A common pastime for poker players at a poker table is to shuffle stacks of chips. Shuffling chips is performed by
starting with two stacks of poker chips, S1 and S2, each stack containing C chips. Each stack may contain chips of
several different colors.
The actual shuffle operation is performed by interleaving a chip from S1 with a chip from S2 as shown below for
C=5:

The single resultant stack, S12, contains 2*C chips. The bottommost chip of S12 is the bottommost chip from S2. On
top of that chip, is the bottommost chip from S1. The interleaving process continues taking the 2nd chip from the
bottom of S2 and placing that on S12, followed by the 2nd chip from the bottom of S1 and so on until the topmost chip
from S1 is placed on top of S12.
After the shuffle operation, S12 is split into 2 new stacks by taking the bottommost C chips from S12 to form a new
S1 and the topmost C chips from S12 to form a new S2. The shuffle operation may then be repeated to form a new
S12.
For this problem, you will write a program to determine if a particular resultant stack S12 can be formed by shuffling
two stacks some number of times.
Input
The first line of input contains a single integer N, (1 N 1000) which is the number of datasets that follow.
Each dataset consists of four lines of input. The first line of a dataset specifies an integer C, (1 C 100) which is
the number of chips in each initial stack (S1 and S2). The second line of each
dataset specifies the colors of each of the C chips in stack S1, starting with the bottommost chip. The third line of
each dataset specifies the colors of each of the C chips in stack S2 starting with the bottommost chip. Colors are
expressed as a single uppercase letter (A through H). There are no blanks or separators between the chip colors.
The fourth line of each dataset contains 2*C uppercase letters, (A through H), representing the colors of the
desired result of the shuffling of S1 and S2 zero or more times. The bottommost chips color is specified first.
Output
Output for each dataset consists of a single line that displays the dataset number (1 though N), a space, and an
integer value which is the minimum number of shuffle operations required to get the desired resultant stack. If the
desired result can not be reached using the input for the dataset, display the value negative 1 (-1) for the number
of shuffle operations.
Sample Input

Sample Output

2
4
AHAH
HAHA
HHAAAAHH
3
CDE
CDE
EEDDCC

12
2 -1

102.Problem: Push Button Lock


The Frobozz Magic Lock Company is in the business of manufacturing push button style combination door locks.
A push button door lock consists of a number of push buttons B, (1 B 11), labeled 1 through B. The lock is
opened by pressing the correct sequence of button combinations and then turning the doorknob. If the sequence
of presses is correct, the door magically opens.
A combination consists of 1 or more buttons being pressed simultaneously. A sequence consists of a series of
combinations. A sequence must have at least one combination. Once a button has been used in a combination, it
may not be used again in the same sequence. In addition, it is not necessary to use all the buttons in a sequence.
For example, for B=8:
(1-2-3)(4)(7-8)
is a valid sequence with 3 combinations (1-2-3), (4), and (7-8). Note that buttons 5 and 6 are not used in this
sequence.
(1-2-3)(2-4)(5-6)
is not a valid sequence, since button 2 appears in 2 combinations (1-2-3) and (2-4).
The CEO of Frobozz, J. Pierpont Flathead, wants you to write a program that determines the number of valid
sequences possible for given values of B. The program must be able to process a list of lock orders (datasets)
from customers and generate a report showing the order number, the value of B, and the number of valid
sequences possible. This list will always contain at least one dataset, but no more than 100 datasets.
Input
The first line of input contains a single integer N, (1 N 100), representing the number of datasets that follow.
Each dataset consists of a single line of data containing a single integer B, which is the number of buttons for the
lock.
Output
For each dataset, display the dataset number, a blank, the value B, a blank, and the number of valid sequences.
Sample Input

Sample Output

3
3
4
3

1 3 25
2 4 149
3 3 25

103.Problem: Sign Message Formatting


The National Transportation Communications for ITS Protocol (NTCIP) for communicating with highway signs with
dynamic messages describes the messages using Markup Language for Transportation Information (MULTI). A
MULTI string consists of text to be displayed together with embedded tags which describe formatting of the text
and included dynamic elements. Tags begin with the open bracket ([) character and end with the close bracket
(]) character. If an open bracket character is to appear in the text, it is represented as two open bracket
characters. Similarly, if a close bracket character is to appear in the text, it is represented as two close bracket
characters. This problem is concerned with formatting for character cell displays, which are rectangular arrays of
character cells each of which can display a single character.
The tags to be supported for this problem are:
Tag

Description

[nl]

Start a new row of the array

[sc<digit>]

Insert <digit> blank character cells between each pair of text characters in the following string until
changed.

[/sc]

Set inter-character spacing to zero (equivalent to [sc0]).

[jl2]

Set left justified text (the first character of the text is the leftmost character of the line).

[jl3]

Set center justified text (the number of character positions before and after the text on the line is the
same or the number after is one more than the number before).

[jl4]

Set right justified text (the final character of the string is the rightmost character on the line).

[jl5]

Set fully justified text (an equal number of blank character spaces, as large as possible for the line
length, is placed between each pair of characters in the text; the resulting string is centered in the
line as for centered text).

For example, on a 24 character line ( indicates a blank character cell):


Format String

Generated Output

[jl2]MESSAGE

MESSAGE

[jl3]MESSAGE

MESSAGE

[jl4]MESSAGE

MESSAGE

[jl2][sc2]MESSAGE

MESSAGE

[jl5]MESSAGE

MESSAGE

[jl2]THIS[jl3]IS A[jl4]MESSAGE

THISIS AMESSAGE

Letters within tags are case-insensitive. That is [nl] = [NL] = [Nl] = [nL].
The default justification at the beginning of a message is left justification and the default character spacing is 0.
Justification and character spacing are maintained across [nl] tags.
The [jl2] and [jl5] tags may only be used before any text has been output on a line. Otherwise it is an error (TAG
CONFLICT).
Once [jl5] text has been output on a line, no other justification tag may be set on that line. Otherwise it is an error
(TAG CONFLICT).

The [jl3] tag may not be used after right justified text ([jl4]) has been output on a line. Otherwise it is an error
(TAG CONFLICT).
A justification tag [jl?] with the same value as the current value does not cause a TAG CONFLICT error.
Extra character spacing specified by the [sc?] tag is ignored on lines with fully justified text. The full justification
rules determine the extra spaces.
If too many characters are required on a line or too many lines are required in a message, it is an error (TOO
BIG). A [nl] tag does not begin a new line unless followed by text output.
If left justified text and center justified text appear on the same line, there must be at least one blank character cell
between the last character of left justified text and the first character of center justified text. Otherwise it is an error
(TOO BIG).
If center justified text and right justified text appear on the same line, there must be at least one blank character
cell between the last character of center justified text and the first character of right justified text. Otherwise it is an
error (TOO BIG).
If left justified text and right justified text appear on the same line, there must be at least one blank character cell
between the last character of left justified text and the first character of right justified text. Otherwise it is an error
(TOO BIG).
The only tags allowed in a message are the seven tags listed above otherwise it is an error (BAD TAG). A
malformed tag or an unmatched single open or closed bracket is a BAD TAG error.
For this problem you will write a program which takes as input the dimensions of the character cell array and a
MULTI string and either outputs an error string or a correctly formatted message.
Input
The first line of input contains a single integer N, (1 N 100), which is the number of datasets that follow. Each
dataset consists of a single line containing an integer R, (1 R 25), a blank, an integer C, (1 C 80), a blank,
and the remainder of the line is a MULTI-Text string. R is the number of rows in the character cell array, C is the
number of columns in the character cell array, and the MULTI-Text is the text to be formatted.
Output
For each dataset, output the dataset number on a line by itself, followed by one of the error strings (TAG
CONFLICT, TOO BIG, BAD TAG) on a line by itself in the case of an error, or, R lines each of which has exactly
C characters (other than terminating newlines) representing the formatted message using space characters for
empty character cells. The last line of output for a dataset result should be a single blank line.
Note: For ease in grading, a dataset that contains an error will only contain one type of error.
Sample Input
7
4 24 [jl2]MESSAGE[nl][jl3]MESSAGE[nl][jl4]MESSAGE
2 24 This[jl3]is a[jl4]message
2 24 This is a very long message which will not fit
4 24 This[nl]message[nl]has[nl]too[nl]many[nl]lines
2 32 [jl3]This message has a [[ and a ]]
2 32 This is a bad tag[xy34]
2 32 [jl3]This message [jl5] has a tag conflict.

Sample Output
(^ added after the last character of the lines for illustrative purposes. It should NOT appear in program output.)

1
MESSAGE ^
MESSAGE ^
MESSAGE^
^
2
This is a message^
^
3
TOO BIG
4
TOO BIG
5
This message has a [ and a ] ^
^
6
BAD TAG
7
TAG CONFLICT

104.Problem: Visible Lattice Points


A lattice point (x, y) in the first quadrant (x and y are integers greater than or equal to 0), other than the origin, is
visible from the origin if the line from (0, 0) to (x, y) does not pass through any other lattice point. For example, the
point (4, 2) is not visible since the line from the origin passes through (2, 1). The figure below shows the points (x,
y) with 0 x, y 5 with lines from the origin to the visible points.

Write a program which, given a value for the size, N, computes the number of visible points (x,y) with 0 x, y N.
Input
The first line of input contains a single integer C, (1 C 1000) which is the number of datasets that follow.
Each dataset consists of a single line of input containing a single integer N, (1 N 1000), which is the size.
Output
For each dataset, there is to be one line of output consisting of: the dataset number starting at 1, a single space,
the size, a single space and the number of visible points for that size.
Sample Input

Sample Output

4
2
4
5
231

125
2 4 13
3 5 21
4 231 32549

105.Problem: Triangular N-Queens Problem


A queen piece on a triangular array of cells, N cells on a side, can attack any cell on a file parallel to one of the
sides containing the queens cell. For example, in the array in Figure 1, a queen on the black cell, attacks all of
the shaded cells. The Triangular N-Queens Problem of size N, is to find a maximal set of queen positions in a
triangular array with N cells on a side so that no queen is attacking any other queen. For example, the black cells
in Figure 2 give a maximal set of queen positions in a size 6 array. It turns out that a size N array always has
floor((2*N + 1)/3) as the maximal number of non-attacking queen positions.

Write a program, which, given the size, N, of the triangular array, finds a maximal set of non-attacking queen
positions on the array (floor((2*N + 1)/3) of them).
Input
The input begins with a line containing an integer value specifying the number of datasets that follow, C, (1 C
1000). Each dataset consists of a single line containing a single integer N, (1 N 1000), which is the size of the
triangular array.
Output
The first output line for each problem gives the problem number starting at 1, a single space, the input size, a
single space and the number of queen positions. Following the first line will be the queen positions, 8 positions
per line except perhaps for the last line of positions. Each position has the format open bracket ([), row number
starting with 1, a comma, the position from the left within the row starting at 1 and a close bracket (]). Positions
within a line are separated by a single space. For example, the queen positions in Figure 2 are [1,1] [4,2] [5,4]
[6,3]. The lines of position values are followed by a single blank line.
Sample Input

Sample Output

6
3
6
9
10
14
18

132
[1,1] [3,2]
264
[3,1] [4,3] [5,5] [6,2]
396
[4,1] [5,3] [6,5] [7,7] [8,2] [9,4]
4 10 7
[4,1] [5,3] [6,5] [7,7] [8,2] [9,4] [10,6]
5 14 9
[6,1] [7,3] [8,5] [9,7] [10,9] [11,11] [12,2] [13,4]
[14,6]
6 18 12
[7,1] [8,3] [9,5] [10,7] [11,9] [12,11] [13,13] [14,2]
[15,4] [16,6] [17,8] [18,10]

Notes
11. There may be many different correct answers to a particular problem, so your answers need not be the
same as those in the Sample Output above.
22. Some solution methods for this problem may cause the time limit to be exceeded. Be sure to try the larger
values before submitting your solution.

106.Problem: Non-divisible 2-3 Power Sums


Every positive integer N can be written in at least one way as a sum of terms of the form (2a)(3b) where no term in
the sum exactly divides any other term in the sum. For example:
1 = (20)(30)
7 = (22)(30) + (20)(31)
31 = (24)(30) + (20)(32) + (21)(31) = (22) + (33)
Note from the example of 31 that the representation is not unique.
Write a program which takes as input a positive integer N and outputs a representation of N as a sum of terms of
the form (2a)(3b).
Input
The first line of input contains a single integer C, (1 C 1000) which is the number of datasets that follow.
Each dataset consists of a single line of input containing a single integer N, (1 N < 231), which is the number to
be represented as a sum of terms of the form (2a)(3b).
Output
For each dataset, the output will be a single line consisting of: The dataset number, a single space, the number of
terms in your sum as a decimal integer followed by a single space followed by representations of the terms in the
form [<2 exponent>,<3 exponent>] with terms separated by a single space. <2 exponent> is the power of 2 in the
term and <3 exponent> is the power of 3 in the term.
Sample Input

Sample Output

6
1
7
31
7776
531441
123456789

1 1 [0,0]
2 2 [2,0] [0,1]
3 3 [4,0] [0,2] [1,1]
4 1 [5,5]
5 1 [0,12]
6 8 [3,13] [4,12] [2,15] [7,8] [9,6] [0,16] [10,5] [15,2]

107.Problem: Margaritas on the River Walk


One of the more popular activities in San Antonio is to enjoy margaritas in the park along the river know as the
River Walk. Margaritas may be purchased at many establishments along the River Walk from fancy hotels to
Joes Taco and Margarita stand. (The problem is not to find out how Joe got a liquor license. That involves Texas
politics and thus is much too difficult for an ACM contest problem.) The prices of the margaritas vary depending
on the amount and quality of the ingredients and the ambience of the establishment. You have allocated a certain
amount of money to sampling different margaritas.
Given the price of a single margarita (including applicable taxes and gratuities) at each of the various
establishments and the amount allocated to sampling the margaritas, find out how many different maximal
combinations, choosing at most one margarita from each establishment, you can purchase. A valid combination
must have a total price no more than the allocated amount and the unused amount (allocated amount total
price) must be less than the price of any establishment that was not selected. (Otherwise you could add that
establishment to the combination.)
For example, suppose you have $25 to spend and the prices (whole dollar amounts) are:
Vendor A B C H J
D
Price 8 9 8

16 5
7

Then possible combinations (with their prices) are:


ABC(25), ABD(24), ABJ(22), ACD(23), ACJ(21), ADJ( 20), AH(24), BCD(24), BCJ(22), BDJ(21), BH(25),
CDJ(20), CH(24), DH(23) and HJ(21).
Thus the total number of combinations is 15.
Input
The input begins with a line containing an integer value specifying the number of datasets that follow, N, (1 N
1000). Each dataset starts with a line containing two integer values V and D representing the number of vendors
(1 V 30) and the dollar amount to spend (1 D 1000) respectively. The two values will be separated by one
or more spaces. The remainder of each dataset consists of one or more lines, each containing one or more
integer values representing the cost of a margarita for each vendor. There will be a total of V cost values
specified. The cost of a margarita is always at least one (1). Input values will be chosen so the result will fit in a 32
bit unsigned integer.
Output
For each problem instance, the output will be a single line containing the dataset number, followed by a single
space and then the number of combinations for that problem instance.
Note: Some solution methods for this problem may be exponential in the number of vendors. For these methods,
the time limit may be exceeded on problem instances with a large number of vendors such as the second
example below.
Sample Input

Sample Output

2
6 25
8 9 8 7 16 5
30 250
1 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

1 15
2 16509438

108.Problem: Triangular Sums


The nth Triangular number, T(n) = 1 + ... + n, is the sum of the first n integers. It is the number of points in a
triangular array with n points on side. For example T(4):
X
XX
XXX
XXXX
Write a program to compute the weighted sum of triangular numbers:
W(n) = SUM[k = 1..n; k*T(k+1)]
Input
The first line of input contains a single integer N, (1 N 1000) which is the number of datasets that follow.
Each dataset consists of a single line of input containing a single integer n, (1 n 300), which is the number of
points on a side of the triangle.
Output
For each dataset, output on a single line the dataset number, (1 through N), a blank, the value of n for the
dataset, a blank, and the weighted sum , W(n), of triangular numbers for n.
Sample Input

Sample Output

4
3
4
5
10

1 3 45
2 4 105
3 5 210
4 10 2145

109.Problem: Sudoku

Oh no! Bill just realized that the sudoku puzzle he


had spent the last ten minutes trying to solve
essentially
was last weeks puzzle, only rotated
counterclockwise.
How cheap! Couldnt the magazine
afford to make a new one every week? Of course,
he had no way of knowing about this before he
started to solve it, as the holes to fill with digits
were other than last week. Nevertheless, realizing
that this weeks puzzle was a simple derivative of
last weeks certainly took the fun out of solving the
rest of it.
The sudoku board consists of 99 cells. These can be grouped into 33 regions of 33
cells each. Some of the cells are filled with a digit 1 through 9 while the rest of them are left
empty. The aim of the game is to fill each empty cell with a digit 1 . . . 9 so that every row,
every column and every region contains each of the numbers 1 . . . 9 exactly once. A proper
sudoku puzzle always has exactly one solution.
Help Bill avoid unpleasant surprises by creating a program that checks whether an unsolved
sudoku puzzle is in fact derived from an earlier puzzle by simple operations.
The allowed operations are:
1. Rotating the entire puzzle clockwise or counterclockwise.
2. Swapping two columns within a 3 9 column segment.
3. Swapping two rows within a 9 3 row segment.
4. Swapping entire row or column segments.
5. Applying a permutation f of the digits 1 . . . 9 to every cell (i.e. replace x by f (x) in
every cell).
An operation is considered being performed on the sudoku solution (rather than on the
unsolved puzzle) and always guarantees that if the board before the transformation was a
solution to a sudoku puzzle, it still is afterwards.
Input

The input starts with the number of test cases 0 N 50 on a single line.
Then for every test case follow nine lines describing last weeks puzzle solution, fromtop
to bottom. Each line corresponds to a row in the puzzle and consists of nine digits (1 . . . 9),
describing the contents of the cell from left to right.
Last weeks solution is followed by nine lines describing this weeks unsolved puzzle.
Here, also, every line corresponds to a puzzle row and every digit (0 . . . 9) describes the
contents of a cell. 0 indicates that the cell is empty. The rows are presented ordered from top
to bottom, and within each row, the cells are ordered from left to right.
After every test case except the last one follows a blank line. Every unsolved puzzle
is guaranteed to be uniquely solvable and last weeks solution is always a proper sudoku
solution.
Output

For every test case, output Yes if the sudoku puzzle can be derived from the given solved
puzzle using the allowed operations, or No if this is not possible.
Sample input

2
963174258
178325649
254689731
821437596
496852317
735961824
589713462
317246985
642598173
060104050
200000001
008305600
800407006
006000300
700901004
500000002
040508070
007206900
534678912
672195348
198342567
859761423
426853791
713924856
961537284
287419635
345286179
010900605
025060070
870000902
702050043
000204000
490010508
107000056
040080210
208001090
Sample output

Yes
No

110.Problem: The SetStack Computer

Background from Wikipedia: Set theory is a branch of mathematics created principally


by the German mathematician Georg Cantor at the end of the 19th century. Initially
controversial, set theory has come to play the role of a foundational theory in modern
mathematics, in the sense of a theory invoked to justify assumptions made inmathematics
concerning the existence of mathematical objects (such as numbers or functions)
and their properties. Formal versions of set theory also have a foundational role
to play as specifying a theoretical ideal of mathematical rigor in proofs.
Given this importance of sets, being the basis of mathematics, a set of eccentric theorist
set off to construct a supercomputer operating on sets instead of numbers. The initial SetStack Alpha is under construction, and they need you to simulate it in order to verify the
operation of the prototype.
The computer operates on a single stack of sets, which is initially empty. After each
operation, the cardinality of the topmost set on the stack is output. The cardinality of a set S
is denoted |S| and is the number of elements in S. The instruction set of the SetStack Alpha
is PUSH, DUP, UNION, INTERSECT, and ADD.
PUSH will push the empty set {} on the stack.
DUP will duplicate the topmost set (pop the stack, and then push that set on the stack
twice).
UNION will pop the stack twice and then push the union of the two sets on the stack.
INTERSECT will pop the stack twice and then push the intersection of the two sets on
the stack.
ADD will pop the stack twice, add the first set to the second one, and then push the
resulting set on the stack.
For illustration purposes, assume that the topmost element of the stack is
A = {{}, {{}}}
and that the next one is
B = {{}, {{{}}}}.
For these sets, we have |A| = 2 and |B| = 2. Then:
UNION would result in the set { {}, {{}}, {{{}}} }. The output is 3.
INTERSECT would result in the set { {} }. The output is 1.
ADD would result in the set { {}, {{{}}}, {{},{{}}} }. The output is 3.
Input

An integer 0 T 5 on the first line gives the cardinality of the set of test cases. The first
line of each test case contains the number of operations 0 N 2 000. Then follow N lines
each containing one of the five commands. It is guaranteed that the SetStack computer can
execute all the commands in the sequence without ever popping an empty stack.
Output

For each operation specified in the input, there will be one line of output consisting of a
single integer. This integer is the cardinality of the topmost element of the stack after the
corresponding command has executed. After each test case there will be a line with ***
(three asterisks).
Sample input

2
9
PUSH
DUP

ADD
PUSH
ADD
DUP
ADD
DUP
UNION
5
PUSH
PUSH
ADD
PUSH
INTERSECT
Sample output

0
0
1
0
1
1
2
2
2
***
0
0
1
0
0
***

111.Problem: Pie

My birthday is coming up and traditionally Im serving pie. Not just one pie, no, I have
a number N of them, of various tastes and of various sizes. F of my friends are coming to
my party and each of them gets a piece of pie. This should be one piece of one pie, not several
small pieces since that looks messy. This piece can be one whole pie though.
My friends are very annoying and if one of them gets a bigger piece than the others,
they start complaining. Therefore all of them should get equally sized (but not necessarily equally
shaped) pieces, even if this leads to some pie getting spoiled (which is better than spoiling the party).
Of course, I want a piece of pie for myself too, and that piece should also be of the same size. What is
the largest possible piece size all of us can get? All the pies are cylindrical in
shape and they all have the same height 1, but the radii of the pies can be different.
Input

One line with a positive integer: the number of test cases. Then for each test case:
One line with two integers N and F with 1 N, F 10 000: the number of pies and
the number of friends.
One line with N integers ri with 1 ri 10 000: the radii of the pies.
Output

For each test case, output one line with the largest possible volume V such that me and my
friends can all get a pie piece of size V. The answer should be given as a floating point
number with an absolute error of at most 103.
Sample input

3
33
433
1 24
5
10 5
1423456542
Sample output

25.1327
3.1416
50.2655

112.Problem D: Ticket to Ride


Ticket to Ride is a board game for up to 5 players.
The goal of the game is to set up train lines (and to
thwart the opponents attempts at setting up their
train lines). At the beginning of play, each player
is assigned four train lines. A player may choose
to discard as many of these four assignments as she
likes. Each assignment has a score, corresponding to
its difficulty (so, typically, a train line between e.g.
Stockholm and Tokyo would be worth more than a
train line between e.g. Stockholm and Utrecht). At
the end of the game, each player gets points for the
assignments that they have successfully completed,
and penalty points for the assignments that they
have failed to complete.
An assignment consists of a pair of cities that are to be
connected by a series of shorter
railway routes. A route can be claimed (for a certain cost associated with the route), but
things are complicated by the fact that there is only a limited number of routes, and once a
player claims a route, none of the other players can claim it. A player has successfully set up a train line between
two cities if there is a path between the two cities using only routes that have been claimed by this player. For
simplicity, we will ignore all additional aspects of the game (including the actual process of claiming routes and
additional ways to score points).
For instance, if your assignment is to connect Stockholm and Amsterdam in the Figure
above, you would probably want to claim the routes between Stockholm and Copenhagen,
and between Copenhagen and Amsterdam. But if another player manages to claim the route
between Copenhagen and Stockholm before you, your train line would have to use some
other routes, e.g. by going to Copenhagen via Oslo.
In this problem, we will consider the rather bold strategy of trying to complete all four
assignments (typically, this will be quite hard). As a preliminary assessment of the difficulty
of achieving this, we would like to calculate the minimum cost of setting up all four lines
assuming that none of the other players interfere with our plans. Your job is to write a
program to determine this minimum cost.
Input
The input consists of several (at most 20) games to be analyzed. Each game starts with two
integers 1 n 30, 0 m 1 000, giving the number of cities and railway routes in the
map, respectively. Then follow n lines, giving the names of the n cities. City names are at
most 20 characters long and consist solely of lower case letters (a-z).
After this follow m lines, each containing the names of two different cities and an integer
1 c 10 000, indicating that there is a railway route with cost c between the two cities.
Note that there may be several railway routes between the same pair of cities. You may
assume that it is always possible to set up a train line from any city to any other city.
Finally, there will be four lines, each containing the names of two cities, giving the four
train line assignments.
The input is terminated by a case where n = m = 0. This case should not be processed.
Output

For each game, output a single line containing a single integer, the minimum possible cost
to set up all four train lines.
Sample input

10 15
stockholm
amsterdam

london
berlin
copenhagen
oslo
helsinki
dublin
reykjavik
brussels
oslo stockholm 415
stockholm helsinki 396
oslo london 1153
oslo copenhagen 485
stockholm copenhagen 522
copenhagen berlin 354
copenhagen amsterdam 622
helsinki berlin 1107
london amsterdam 356
berlin amsterdam 575
london dublin 463
reykjavik dublin 1498
reykjavik oslo 1748
london brussels 318
brussels amsterdam 173
stockholm amsterdam
oslo london
reykjavik dublin
brussels helsinki
21
first
second
first second 10
first first
first first
second first
first first
00
Sample output

3907
10

113.Problem E: The Bookcase

No wonder the old bookcase caved under the massive piles of books Tom had stacked
on it. He had better build a new one, this time large enough to hold all of his books.
Tomfinds it practical to have the books close at hand when he works at his desk. Therefore,
he is imagining a compact solution with the bookcase standing on the back of
the desk. Obviously, this would put some restrictions on the size of the bookcase, it
should preferably be as small as possible. In addition, Tom would like the bookcase
to have exactly three shelves for aesthetical reasons.
Wondering how small his bookcase could be, he models the problem as follows. He measures
the height hi and thickness ti of each book i and he seeks a partition of the books in
three non-empty sets S1, S2, S3 such that

is minimized,
i.e. the area of the bookcase as seen when standing in front of it (the depth needed is obviously
the largest width of all his books, regardless of the partition). Note that this formula
does not give the exact area of the bookcase, since the actual shelves cause a small additional
height, and the sides cause a small additional width. For simplicity, we will ignore this small
discrepancy.
Thinking a moment on the problem, Tom realizes he will need a computer program to
do the job.
Input

The input begins with a positive number on a line of its own telling the number of test
cases (at most 20). For each test case there is one line containing a single positive integer N,
3 N 70 giving the number of books. Then N lines follow each containing two positive
integers hi, ti, satisfying 150 hi 300 and 5 ti 30, the height and thickness of book i
respectively, in millimeters.
Output

For each test case, output one line containing the minimum area (height times width) of a
three-shelf bookcase capable of holding all the books, expressed in square millimeters.
Sample input

2
4
220 29
195 20
200 9
180 30
6
256 20
255 30
254 15
253 20
252 15
Sample output

251 9
18000
29796

114. Problem : Printer Queue


The only printer in the computer science students union is experiencing an extremely heavy workload.
Sometimes there are a hundred jobs in the printer queue and you may have to wait for hours to get a single page
of output.
Because some jobs are more important than others, the Hacker General has invented and implemented a simple
priority system for the print job queue. Now, each job is assigned a priority between 1 and 9 (with 9 being the
highest priority, and 1 being the lowest), and the printer operates as follows.
The first job J in queue is taken from the queue.
If there is some job in the queue with a higher priority than job J, then move J to the
end of the queue without printing it.
Otherwise, print job J (and do not put it back in the queue).
In this way, all those important muffin recipes that the Hacker General is printing get printed very quickly. Of
course, those annoying term papers that others are printing may have to wait for quite some time to get printed,
but thats life.
Your problem with the new policy is that it has become quite tricky to determine when
your print job will actually be completed. You decide to write a program to figure this out.
The program will be given the current queue (as a list of priorities) as well as the position of
your job in the queue, and must then calculate how long it will take until your job is printed,
assuming that no additional jobs will be added to the queue. To simplify matters, we assume
that printing a job always takes exactly one minute, and that adding and removing jobs from
the queue is instantaneous.
Input
One line with a positive integer: the number of test cases (at most 100). Then for each test
case:
One line with two integers n and m, where n is the number of jobs in the queue (1 n 100) and m is the
position of your job (0 m n 1). The first position in the
queue is number 0, the second is number 1, and so on.
One line with n integers in the range 1 to 9, giving the priorities of the jobs in the queue.
The first integer gives the priority of the first job, the second integer the priority of the
second job, and so on.
Output

For each test case, print one line with a single integer; the number of minutes until your job
is completely printed, assuming that no additional print jobs will arrive.
Sample input

3
10
5
42
1234
60
119111
Sample output

1
2
5

115.Problem G: Prime Path

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that
they would all have to change the four-digit room numbers on their offices.
It is a matter of security to change such things every now and then, to keep the enemy in the dark.
But look, I have chosen my number 1033 for good reasons. I am the Prime minister, you know!
I know, so therefore your new number 8179 is also a prime. You will just have to paste four new
digits over the four old ones on your office door.
No, its not that simple. Suppose that I change the first digit to an 8, then the number will read 8033
which is not a prime!
I see, being the prime minister you cannot stand having a non-prime number on your door even for a
few seconds.
Correct! So I must invent a scheme for going from 1033 to 8179 by a path of prime numbers where
only one digit is changed from one prime to the next prime.
Now, the minister of finance, who had been eavesdropping, intervened.
No unnecessary expenditure, please! I happen to know that the price of a digit is one pound.
Hmm, in that case I need a computer program to minimize the cost. You dont know some very
cheap software gurus, do you?
In fact, I do. You see, there is this programming contest going on. . .
Help the prime minister to find the cheapest prime path between any two given four-digit
primes! The first digit must be nonzero, of course. Here is a solution in the case above.
1033
1733
3733
3739
3779
8779
8179
The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2
can not be reused in the last step a new 1 must be purchased.
Input

One line with a positive number: the number of test cases (at most 100). Then for each test
case, one line with two numbers separated by a blank. Both numbers are four-digit primes
(without leading zeros).
Output

One line for each case, either with a number stating the minimal cost or containing the word
Impossible.
Sample input

3
1033 8179
1373 8017
1033 1033
Sample output

6
7
0

116.Problem: Linelands Airport

Lineland is a strange country. As the name suggests, its shape (as seen from above) is just a
straight line, rather than some two-dimensional shape. The landscape along this line is very
mountainous, something which occasionally leads to some problems. One such problem
now occurs: in this modern era the king wants to build an airport to stimulate the countrys
economy. Unfortunately, its impossible for airplanes to land on steep airstrips, so a horizontal
piece of land is needed. To accommodate for the larger airplanes, this strip needs to have
length at least L.
Over the years, the inhabitants of Lineland have become very proficient in flattening
pieces of land. Given a piece a land, they can remove rock quickly. They dont want to
add rock for that may lead to an unstable landing strip. To minimize the amount of effort,
however, they want to remove the least amount of rock necessary to reach their goal: a flat
piece of land of length L. What is this minimum amount? Because of the low-dimensional
nature of Lineland, the amount of rock that needs to be removed is measured as the total
area of land above the place where the landing strip is placed, rather than the volume (so in
the Figure below, the amount of land removed is given by the lightly shaded area).

Input

One line with a positive number: the number of test cases (at most 25). Then for each test
case:
One line with an integer N, 2 N 500, the number of points, and an integer L,
1 L 10 000, the necessary length to flatten.
N lines with two integers xi and yi with 0 xi, yi 10 000 describing the landscape
of Lineland. The xi are in (strictly) ascending order. At position xi the height of the
landscape is yi. Between two xi the landscape has constant slope. (So the landscape is
piecewise linear). The difference between xN and x1 is greater than or equal to L.
Output

For each test case, output one line with the minimum amount of rock which must be removed
in order to build the airport. The answer should be given as a floating point number
with an absolute error of at most 103.
Sample input

4
35

02
42
14 0
43
02
20
40
53
3 10
10 2
30 2
35 7
2 777
222 333
4444 5555
Sample output

0.9000
0.3750
0.0000
373362.4867

117.Problem: Leonardos Notebook

I just bought Leonardos secret notebook! Rare object collector Stan Ucker was really agitated
but his friend, special investigator Sarah Kepticwas unimpressed.
How do you know it is genuine?
Oh, it must be, at that price. And it is written in the da Vinci code.
Sarah browsed a few of the pages. It was obvious to her that the code was a substitution cipher, where
each letter of the alphabet had been substituted by another letter.
Leonardo would have written the plain-text and left it to his assistant to encrypt, she said. And he
must have supplied the substitution alphabet to be used. If we are lucky, we can find it on the back
cover!
She turned up the last page and, lo and behold, there was a single line of all 26 letters of the
alphabet:
QWERTYUIOPASDFGHJKLZXCVBNM
This may be Leonardos instructions meaning that each A in the plain-text was to be
replaced by Q, each B withW, etcetera. Let us see...
To their disappointment, they soon saw that this could not be the substitution that was used
in the book. Suddenly, Stan brightened.
Maybe Leonardo really wrote the substitution alphabet on the last page, and by mistake
his assistant coded that line as he had coded the rest of the book. So the line we have here is
the result of applying some permutation TWICE to the ordinary alphabet!
Sarah took out her laptop computer and coded fiercely for a few minutes. Then she turned
to Stan with a sympathetic expression.
No, that couldnt be it. I am afraid that you have been duped again, my friend. In all
probability, the book is a fake.
Write a program that takes a permutation of the English alphabet as input and decides if it
may be the result of performing some permutation twice.
Input

The input begins with a positive number on a line of its own telling the number of test cases
(at most 500). Then for each test case there is one line containing a permutation of the 26
capital letters of the English alphabet.
Output

For each test case, output one line containing Yes if the given permutation can result from
applying some permutation twice on the original alphabet string ABC...XYZ, otherwise output
No.
Sample input

2
QWERTYUIOPASDFGHJKLZXCVBNM
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Sample output

No
Yes

118.Problem: Shoot-out
This is back in the Wild West where everybody is fighting everybody. In particular, there are n cowboys, each with
a revolver. These are rather civilized cowboys, so they have decided to take turns firing their guns until only one is
left standing. Each of them has a given probability of hitting his target, and they all know each others probability.
Furthermore, they are geniuses and always know which person to aim at in order to maximize their winning
chance, so they are indeed peculiar cowboys. If there are several equally good targets, one of those will be
chosen at random. Note that a cowboys code of ethics forces him to do his best at killing one of his opponents,
even if intentionally missing would have increased his odds (yes, this can happen!)

Input specifications
On the first line of the input is a single positive integer t, telling the number of test cases
to follow. Each case consists of one line with an integer 2 <= n <= 13 giving the number
of cowboys, followed by n positive integers giving hit percentages for the cowboys in
the order of their turns.

Output specifications
For each test case, output one line with the percent probabilities for each of them
surviving, in the same order as the input. The numbers should be separated by a
space and be correctly rounded to two decimal places.

Sample input
5
2 1 100
3 100 99 98
3 50 99 100
3 50 99 99
3 50 99 98

Output for sample input


1.00 99.00
2.00 0.00 98.00
25.38 74.37 0.25
25.38 49.50 25.12
25.63 24.63 49.74

119.Problem: Tour Guide


You are working as a guide on a tour bus for retired people, and today you have taken your regular Nordic seniors
to The Gate of Heavenly Peace. You let them have a lunch break where they could do whatever they like. Now
you have to get them back to the bus, but they are all walking in random directions. You try to intersect them, and
send them straight back to the bus. Minimize the time before the last person is in the bus. You will always be able
to run faster than any of the tour guests, and they walk with constant speed, no matter what you tell them.
The seniors walk in straight lines, and the only way of changing their direction is to give them promises of
camphor candy. A senior will neither stop at nor enter the bus before given such a promise.

Input specifications
A number of test cases consisting of: A line with an integer 1 <= n <= 8, the number of
people on the tour. A line with an floating point number 1 < v <= 100, your maximum
speed (you start in the bus at the origin). Then follow n lines, each containing four
floating point numbers xi yi vi ai, the starting coordinates (106 <= xi, yi <= 106), speed
(1 <= vi < 100) and direction (0 <=ai < 2) of each of the tour guests.
The input is terminated by a case with n = 0, which should not be processed. All
floating point numbers in the input will be written in standard decimal notation, and
have no more than 10 digits.

Output specifications
For each test case, print a line with the time it takes before everybody is back in the bus
(the origin). Round the answer to the nearest integer. The answer will never be larger
than 106.

Sample input
1
50.0
125.0 175.0 25.0 1.96
3
100.0
40.0 25.0 20.0 5.95
-185.0 195.0 6.0 2.35
30.0 -80.0 23.0 2.76
0

Output for sample input


20
51

120.Problem: Nasty Hacks

You are the CEO of Nasty Hacks Inc., a company that creates small pieces of malicious software which teenagers
may use to fool their friends. The company has just finished their first product and it is time to sell it. You want to
make as much money as possible and consider advertising in order to increase sales. You get an analyst to
predict the expected revenue, both with and without advertising. You now want to make a decision as to whether
you should advertise or not, given the expected revenues.

Input specifications
The input consists of n cases, and the first line consists of one positive integer giving n.
The next n lines each contain 3 integers, r, e and c. The first, r, is the expected revenue
if you do not advertise, the second, e, is the expected revenue if you do advertise, and
the third, c, is the cost of advertising. You can assume that the input will follow these
restrictions: 106 <= r, e <= 106 and 0 <= c <= 106.

Output specifications
Output one line for each test case: advertise, do not advertise or does not matter,
presenting whether it is most profitable to advertise or not, or whether it does not make
any difference.

Sample input
3
0 100 70
100 130 30
-100 -70 40

Output for sample input


advertise
does not matter
do not advertise

121.Problem: Jezzball

JezzBall is a computer game in which red-and-white atoms bounce about a rectangular field of play. The player
advances to later levels (with correspondingly higher numbers of atoms and lives)
by containing the atoms in progressively smaller spaces, until at least 75% of the
area is blocked off. (wikipedia.org) The picture to the right is a screenshot
from the original game, where the player has already covered some space
(the black part). In this problem we will consider a slightly different, non-discrete,
version of the game. That is, while the length unit is still pixels, you should treat them as non-discrete in the sense
that all objects can be at non-integer coordinates and all movements are continuous.
The size of the playing field will be 1024 768 pixels. The atoms that bounce
around will be infinitely thin (and not round balls like in the screenshot). The atoms
will move at a constant speed and only change direction when hitting the edge of the
playing field (x-coordinate 0 and 1024 or y-coordinate 0 and 768), where they bounce
without loss of energy. The atoms do not hit each other.
The player can divide the playing field in two by shooting a horizontal or vertical
ray from (in this problem) a fixed point on the playing field. The ray will then extend
in both directions simultaneously (up and down for vertical rays, or left and right for
horizontal rays) at a uniform speed (in this problem always 200 pixels per second). The
rays will also be infinitely thin. If no atom touches any part of the ray while its still
being extended, the field has sucessfully been divided. Otherwise the player loses a
life.
If an atom touches the endpoint of an extending edge, this will not be counted as a
hit. Also, if an atom hits the ray at the same instant it has finished extending, this will
also not count as a hit. Write a program that determines the minimum time the player
must wait before he can start extending a ray so that an atom will not hit it before the
ray has been completed.

Input specifications
Each test case starts with a line containing a single integer n, the number of atoms
(1 <= n <= 10). Then follows a line containing two integers, x and y, the position where
the two ray ends will start extending from (0 < x < 1024, 0 < y < 768). Then n lines
follow, each containing four integers, x, y, vx and vy describing the initial position and
speed of an atom (0 < x < 1024, 0 < y < 768, 1 <= |vx| <= 200, 1 <= |vy| <= 200). The
speed of the atom in the x direction is given by vx, and the speed in the y direction is
given by vy. All positions in each input will be distinct. The input is terminated by a
case where n = 0, which should not be processed. There will be at most 25 test cases.

Output specifications
For each test case, output the minimum time (with exactly 5 decimal digits) until the
player can extend either a horizontal or vertical ray without an atom colliding with it
while it is being drawn. The input will be constructed so that the first time this occurs
will be during an open interval at least 105 seconds long. If no such interval is found
during the first 10000 seconds, output Never (without quotes).

Sample input
3
700 420
360 290 170 44
900 150 -53 20
890 100 130 -100
4
10 10

1 1 192 144
513 385 192 144
1023 767 -192 -144
511 383 -192 -144
0

Output for sample input


2.80094
Never

122.Problem: Card Trick

The magician shuffles a small pack of cards, holds it face down and performs the following procedure:
1. The top card is moved to the bottom of the pack. The new top card is dealt face up onto the table. It is the Ace
of Spades.
2. Two cards are moved one at a time from the top to the bottom. The next card is dealt face up onto the table. It
is the Two of Spades.
3. Three cards are moved one at a time . . .
4. This goes on until the nth and last card turns out to be the n of Spades.
This impressive trick works if the magician knows how to arrange the cards
beforehand (and knows how to give a false shuffle). Your program has to determine
the initial order of the cards for a given number of cards, 1 <= n <= 13.
Input specifications
On the first line of the input is a single positive integer, telling the number of test cases
to follow. Each case consists of one line containing the integer n.
Output specifications
For each test case, output a line with the correct permutation of the values 1 to n, space
separated. The first number showing the top card of the pack, etc . . .
Sample input
2
4
5
Output for sample input
2143
31452

123.Problem: Traveling Salesman

Long before the days of international trade treaties, a salesman would need to pay taxes at every
border crossed. So your task is to find the minimum number of borders that need to be crossed
when traveling between two countries. We model the surface of Earth as a set of polygons in three dimensions
forming a closed convex 3D shape, where each polygon corresponds to one country. You are
not allowed to cross at points where more than two countries meet.
Input specifications
Each test case consists of a line containing c, the number of countries (4 <= c <= 6000),
followed by c lines containing the integers n x1 y1 z1 . . . xn yn zn, describing (in order)
the n corners of a closed polygon (3 <= n <= 20). Then follows a line with one integer
m (0 < m <= 50), and then m lines with queries ca cb, where ca and cb are country
numbers (starting with 1). No point will be on the line between two connected points,
and 106 <=x, y, z <= 106 for all points. No two non-adjacent edges of a country share
a common point. The input is terminated by a case where c = 0, which should not be
processed.
Output specifications
For each query, output the number of borders you must cross to go from ca to cb.
Sample input
6
4000001011010
4100101111110
4000100101001
4010110111011
4000010110100
4001011111101
2
12
13
0
Output for sample input
2
1

124.Problem: Whac-a-Mole

While visiting a traveling fun fair you suddenly have an urge to break the high
score in the Whac-a-Mole game. The goal of the Whac-a-Mole game is to... well...
whack moles. With a hammer. To make the job easier you have first consulted
the fortune teller and now you know the exact appearance patterns of the moles.
The moles appear out of holes occupying the n2 integer points (x, y) satisfying
0 <= x, y < n in a two-dimensional coordinate system. At each time step, some
moles will appear and then disappear
again before the next time step. After the moles appear but before they disappear, you
are able to move your hammer in a straight line to any position (x2, y2) that is at distance
at most d from your current position (x1, y1). For simplicity, we assume that you
can only move your hammer to a point having integer coordinates. A mole is whacked
if the center of the hole it appears out of is located on the line between (x1, y1) and
(x2, y2) (including the two endpoints). Every mole whacked earns you a point. When
the game starts, before the first time step, you are able to place your hammer anywhere
you see fit.
Input specifications
The input consists of several test cases. Each test case starts with a line containing three
integers n, d and m, where n and d are as described above, and m is the total number
of moles that will appear (1 <= n <= 20, 1 <= d <= 5, and 1 <= m <= 1000). Then follow
m lines, each containing three integers x, y and t giving the position and time of the
appearance of a mole (0 <= x, y < n and 1 <= t <= 10). No two moles will appear at the
same place at the same time.
The input is ended with a test case where n = d = m = 0. This case should not be
processed.
Output specifications
For each test case output a single line containing a single integer, the maximum
possible score achievable.
Sample input
426
001
313
012
022
102
202
543
001
121
241
000
Output for sample input
4
2

125.Problem H: RandomWalking

The Army of Coin-tossing Monkeys (ACM) is in the business of producing randomness. Good random
numbers are important for many applications, such as cryptography, online gambling, randomized algorithms
and panic attempts at solutions in the last few seconds of programming competitions.
Recently, one of the best monkeys has had to retire. However, before he left, he invented a new,
cheaper way to generate randomness compared to
directly using the randomness generated by coin-tossing monkeys. The method starts
by taking an undirected graph with 2n nodes labelled 0, 1, . . . , 2n 1. To generate k
random n-bit numbers, they will let the monkeys toss n coins to decide where on the
graph to start. This node number is the first number output. The monkeys will then
pick a random edge from this node, and jump to the node that this edge connects to.
This new node will be the second random number output. They will then select a
random edge from this node (possibly back to the node they arrived from in the last
step), follow it and output the number of the node they landed on. This walk will
continue until k numbers have been output.
During experiments, the ACM has noticed that different graphs give different
output distributions, some of them not very random. So, they have asked for your
help testing the graphs to see if the randomness is of good enough quality to sell.
They consider a graph good if, for each of the n bits in each of the k numbers
generated, the probability that this bit is output as 1 is greater than 25% and smaller
than 75%.
Input specifications
The input will consist of several data sets. Each set will start with a line consisting
of three numbers k, n, e separated by single spaces, where k is the number of n-bit
numbers to be generated and e is the number of edges in the graph (1 <= k <= 100,
1 <= n <= 10 and 1 <= e <= 2000). The next e lines will consist of two space-separated
integers v1, v2 where 0 <= v1, v2 < 2n and v1 v2. Edges are undirected and each
node is guaranteed to have at least one edge. There may be multiple edges between
the same pair of nodes.
The last test case will be followed by a line with k = n = e = 0, which should not
be processed.
Output specifications
For each input case, output a single line consisting of the word Yes if the graph is good,
and No otherwise.
Sample input
10 2 3
03
13
23
524
01
03
12
23
000
Output for sample input
No
Yes

126.Problem: HoneycombWalk

A bee larva living in a hexagonal cell of a large honeycomb decides to creep for a walk. In each step the larva
may move into any of the six adjacent cells and after n steps, it is to end up in its original cell.
Your program has to compute, for a given n, the number of different such larva walks.
Input specifications
The first line contains an integer giving the number of test cases to follow. Each case
consists of one line containing an integer n, where 1 <= n <= 14.
Output specifications
For each test case, output one line containing the number of walks. Under the
assumption 1 <= n <= 14, the answer will be less than 231.
Sample input
2
2
4
Output for sample input
6
90

127.Problem: String Cutting


Lets consider a string s of length n (0< n <10 000) containing only characters from a to z. We define a cut ci (0 < i
< n) is an action splitting the string s into 2 substrings s1 and s2 so that s1 consists of first i characters of s and s2
consists of remaining characters from s. Each cut is associated with a cost which equals to the total number of
characters consisted in either s1 or s2 but not in both. For example, let s = abcbacbd, the cut c 5 will break s into
s1= abcba and s2 = cbd with the cost of 2.
The original string can be cut into k+1 substrings after applying k cuts sequentially to the string and its subsequent
substrings. In order to simply describe these k cuts, we specify the position of the cuts with regard to the original
string.
Lets consider an example where we sequentially apply 3 cuts at positions 5, 3 and 6 to the string s = ababccd.
After the first cut at position 5, we have two substrings s 1 = ababc and s2 = cd with the cost of 3. The second cut
at position 3 breaks s1 into two substrings s11 = aba and s12 = bc with the cost of 2. The last cut at position 6
breaks s2 into two substrings s21 = c and s22 = d with the cost of 2. The total cost for the 3 cuts is 3+2+2=7.
Given a string and their cuts, your task is to write a program to compute the total cost for the cut.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the first line contains the integer number k (1 k 1000). The second line contains k positive
integer numbers describing the position of k cuts. The third line contains the string which will be cut.
Output
For each test case, write in one line the total cost of the cuts.
Sample Input

Sample Output

2
3
536
ababccd
2
42
ababcd

7
4

128.Problem: Patrol Robot


A robot has to patrol around a rectangular area which is in a form of m n grid (m rows and n columns). The rows
are labeled from 1 to m. The columns are labeled from 1 to n. A cell (i,j) denotes the cell in row i and column j in
the grid. At each step, the robot can only move from one cell to an adjacent cell, i.e. from (x,y) to (x+1,y), (x,y+1),
(x1,y) or (x,y1). Some of the cells in the grid contain obstacles. In order to move to a cell containing obstacle,
the robot has to switch to turbo mode. Therefore, the robot cannot move continuously to more than k cells
containing obstacles.
Your task is to write a program to find the shortest path (with the minimum number of cells) from cell (1, 1) to cell
(m, n). It is assumed that both these cells do not contain obstacles.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the first line contains two positive integer numbers m and n separated by space (1 m, n 20).
The second line contains an integer number k (0 k 20). The i th line of the next m lines contains n integer aij
separated by space (i = 1, 2, ..., m; j = 1, 2, ..., n). The value of a ij is 1 if there is an obstacle on the cell (i, j), and is
0 otherwise
Output
For each data set, if there exists a way for the robot to reach the cell (m ,n), write in one line the integer number s,
which is the number of moves the robot has to make; 1 otherwise.
Sample Input

Sample Output

3
25
0
01000
00010
46
1
011000
001011
011110
011100
22
0
01
10

7
10
-1

129.Problem: Construction Schedule


There are many tasks which need to be done in order to construct a building. In order to perform these tasks,
there should be a reasonable schedule. There might be relations between tasks. The difficulty we meet in creating
a schedule is that the schedule has to satisfy all given relations among the given tasks.
Given a set of tasks and their relations, your task is to write a program to check whether it is possible to create a
schedule to perform the tasks.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the first line contains two integer numbers n (1 n 500), and k (0 k 20000) separated by
spaces, where n denotes the total number of tasks, and k denotes the total number of relations. The next k
following lines describe k relations among the tasks. Let tj be a starting time of the task j, j = 1, 2, ..., n. Each
relation is in one of the two forms:
4 x y v means task x must not start after task y starts v days, i.e. tx ty + v,
5 x y -v means task x must not start before task y starts v days, i.e. tx ty + v,
where v is a positive integer not greater than 10 000.

Output
For each test case, write in one line YES if it is possible to construct a schedule to satisfy all the given relations
among the given tasks, NO otherwise.
Sample Input

Sample Output

2
22
1 2 -2
121
21
1 2 -1

NO
YES

130.Problem: Inferring Ancestors


Reconstructing the evolutionary relationships among
species is one of major subjects in biology. Typically,
each species is presented by a sequence over four
nucleotide types: A, C, G, and T. A nucleotide mutation
is said to be happened at position i between two
sequences X = (x1, ..., xl) and Y=(y1, ..., yl) if xi yi. The
distance between two sequences X and Y is calculated
as the total nucleotide mutations between them.
There are n contemporary species, which are labeled
from 0 to n1. The evolutionary relationships among
species are depicted by a binary rooted tree where n
leaves represent n contemporary species, internal nodes
represent ancestor species, and branch lengths
represent distances between species (see figure below).
This tree can be represented in text form using brackets
as ((0,1),((3,4),2)).
Since nucleotide sequences are not available for ancestor species, our task is to determine one nucleotide
sequence for each ancestor species such that the tree length (total branch lengths) is minimized.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the first line containing two integer numbers separated by space (n 10, l 100) indicating the
number of contemporary species and the length of nucleotide sequences, respectively. The ith line of the following
n lines contains the nucleotide sequence of the contemporary species labeled i1. The last line contains the text
representation of the tree topology.
Output
For each data set, write in one line an integer number indicating the minimum length of the tree.
Sample Input

Sample Output

2
23
AGG
CGT
(0,1)
55
ACGTG
ACATG
CTATG
ATATG
GTATT
((0,1),(2,(3,4))
)

2
5

131.Problem: Black-White Grid


Let M be a grid of n rows and n columns. The rows are numbered from 1 to n and the columns are numbered from
1 to n. A cell (i, j) denotes the cell in row i and column j in the grid. Each cell is colored in black or white. Let C ij
denote the color of the cell (i, j). All cells of the form (i, i) for 1 i n are called diagonal cells.
Swapping rows i and j of the grid M denotes the following action: we swap the values of C ik and Cjk for k = 1, 2, ...,
n. Swapping two columns is defined analogously.
We say that M is white-colorable if it is possible to swap some of the pairs of rows and some of the pairs of
columns (in any sequence) so that, after all the swappings, all the diagonal cells of M are white. For example, Fig
1 shows a white-colorable grid.

Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the first line contains a single positive integer n (n 1000) the size of the grid. The i th line of
the following n lines contains n character Cij (i = 1, 2, ..., n; j = 1, 2, ..., n) specifying color pattern of the grid.
Character Cij is B or W indicating that the color of cell (i, j) is black or white respectively.
Output
For each data set, write in one line YES if given grid is white-colorable or NO otherwise.
Sample Input

Sample Output

2
3
WWW
WBB
WBB
3
BWB
BWW
WWB

NO
YES

132.Problem: The ACM-ICPC world final hosting


There are n major cities in the world. These cities are labeled from 0 to
n 1, which in order to form a convex polygon on a single plane (see
the figure below). Each year, the ACM-ICPC Committee has to select
one city from these cities to host the ACM-ICPC world final. The
selection process is described as follows:
3- At the first phase, they create a shortlist. In order to do so, with a
starting city s and a selection step d, they put all the cities with label s
+ i*d into the shortlist for all i such that 0 i and s + i*d < n.
4- At the second phase, one city will be selected from the shortlist to
organize the ACM-ICPC world final. At that year, they might choose
the city which is the most to the North (maximal y coordinate), to the
South (minimum y coordinate), to the East (maximum x coordinate) or
to the West (minimum x coordinate). It is assumed that there are no
two cities having the same x, or y coordinate.
There is a cost associated with each city to organize the ACM-ICPC world final. It is assumed that this cost does
not change over years. Your task is to compute the total cost the ACM-ICPC Committee has to pay to organize
the ACM-ICPC world finals for a given number of years.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the first line contains the integer number n (1 n 100 000). Each line of the next n lines
describes one city, which contains three integer numbers x, y, and c separated by space. The pair (x, y) is a 2-D
coordinate specifying the location of the city (200 000 x, y 200 000). c is the associated cost to organize the
ACM-ICPC world final in that city (1 c 1000). The next line contains an integer number m, which is the number
of years the ACM-ICPC Committee want to compute the cost to organize the ACM-ICPC world finals (1 m 10
000). Each line of the next m lines contains three integer numbers s, d (0 s < n; 1 d), and p separated by
space. The value of p can be 0, 1, 2 or 3 for selecting the city most to the North, the South, the East or the West
respectively.
Output
For each data set, write in one line the total cost for the ACM-ICPC Committee to organize the ACM-ICPC world
finals.

Sample Input

Sample Output

2
4
-1 1 2
043
532
1 -1 2
2
010
021
3
002
113
2 10 2
2
111
020

5
5

133.Problem: Sorted bit sequence


Lets consider the 32 bit representation of all integers i from m up to n inclusive (m i n; m n 0, -231 m < n
231-1). Note that a negative number is represented in 32 bit Additional Code. That is the 32 bit sequence, the
binary sum of which and the 32 bit representation of the corresponding positive number is 2 32 (1 0000 0000 0000
0000 0000 0000 0000 0000 in binary).
For example, the 32 bit representation of 6 is
0000 0000 0000 0000 0000 0000 0000 0110
and the 32 bit representation of -6 is
1111 1111 1111 1111 1111 1111 1111 1010
and
0000 0000 0000 0000 0000 0000 0000 0110 (6)
+
1111 1111 1111 1111 1111 1111 1111 1010 (-6)
----------------------------------------------------= 1 0000 0000 0000 0000 0000 0000 0000 0000 (232)
Let's sort the 32 bit representations of these numbers in increasing order of the number of bit 1. If two 32 bit
representations that have the same number of bit 1, they are sorted in lexicographical order.
For example, with m = 0 and n = 5, the result of the sorting will be
No.

Decimal number

Binary 32 bit representation

0000 0000 0000 0000 0000 0000 0000 0000

0000 0000 0000 0000 0000 0000 0000 0001

0000 0000 0000 0000 0000 0000 0000 0010

0000 0000 0000 0000 0000 0000 0000 0100

0000 0000 0000 0000 0000 0000 0000 0011

0000 0000 0000 0000 0000 0000 0000 0101

with m = -5 and n = -2, the result of the sorting will be


No.

Decimal number

Binary 32 bit representation

-4

1111 1111 1111 1111 1111 1111 1111 1100

-5

1111 1111 1111 1111 1111 1111 1111 1011

-3

1111 1111 1111 1111 1111 1111 1111 1101

-2

1111 1111 1111 1111 1111 1111 1111 1110

Given m, n and k (1 k min{n m + 1, 2 147 473 547}), your task is to write a program to find a number
corresponding to k-th representation in the sorted sequence.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the only line contains 3 integers m, n and k separated by space.
Output
For each data set, write in one line the k-th number of the sorted numbers.

Sample Input

Sample Output

2
053
-5 -2 2

2
-5

134.Problem: Domino
A set of double-six dominoes with 28 tiles is the most popular size of dominoes set. In a double-six domino set,
the numbers on the tiles range from 0 (or blank) to 6. In a double-six set, there are seven suits (0 or blank, 1, 2, 3,
4, 5, 6), each with seven members.

The game can be started with any tile. Until the first double played, the game layout has only 2 end opens. After
the first double played (which is called spinner), the game can be played on two additional edges (the game layout
has 4 open ends now). All subsequent doubles can only played as other tiles except that its value is counted
twice when calculating the score of the game layout.
In one play turn, a tile can be added to an open end if the number of points in the added head of the tile matches
the number of points in this open end.
The Domino game usually is played by at least 2 persons. Lets consider a game played by just a single person.
The object of the game is to create as much as possible situations where the open ends of the game layout added
up to a multiple of five (5, 10, 15, 20, etc.). The score at each play turn is the total sum of open ends when they
added up to a multiple of five. This score is added up to the current score of the game.
In this case, the game is quite simple. At first, a sequence of 28 tiles in random order is given. Then the tiles are
taken from the sequence one by one. For each tile, the player might add it into the game layout or leave it out.
Your task is to write a program to play the game in order to obtain the highest total score.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, a single line contains 56 numbers separated by space represents 28 tiles of the game, 2
consecutive numbers for each tile.
Output
For each data set, write in one line the highest score that can be obtained.
Sample Input

2
0136251116032405444606152345005604335534026612352213142
6
1533222406113502361355040325454426140546000134566616122
3
Sample Output

150
145

Examples of how to calculate the score at each play turn:

Examples of how to calculate the score at each play turn:

The game layout to obtain the highest score for the first data set in the sample input

135. Problem: Spin Doctor

You are part of a team working on the simulation of a dynamic system of particles interacting according
to classical mechanics Newtonian physics with gravitational and electromagnetic forces. Your part
of the problem solution is to bring the system into a standard orientation following the simulation based
on rotating the coordinate system (or, if you like, you can think of it as rotating all of the particles).
In the final coordinate system, the first three particles are to lie in a plane parallel with the XY plane,
either on or above the XY plane. In addition, the first particle is to lie in the YZ plane with a nonnegative Y coordinate. If the first three points do not define a plane (that is, they either are not distinct
or are collinear), print an error message and go to the next problem.
Subscripting the first particle as subscript 0, the second as 1, and the third as 2, these conditions are
summarized thus:
z0 = z1 = z2 > 0
x0 = 0; y0 > 0
note that you may have y0 = 0
Only the coordinate system rotates; the particles retain their positions with respect to each other. If
youre thinking of this as a rotation of the particles, it is to be a rigid-body rotation with respect to the
origin of the coordinate system.
Input data specification
Sets of problem specifications:
(1) Number of particles in the complete system, followed by descriptive textual information (to the end
of the line) that needs to be retained for output, preserving any leading blanks and/or tabs.
(2) The required number of triples of numbers, giving the x, y, and z coordinates as white-space
delimited numbers (they may be on the same line or on successive lines), without any descriptive
text or commas to discard.
(3) A blank line separating problems.
The input data set ends when a system of fewer than three particles is specified. (It will in fact be zero.)
This trailer record will terminate with an end-of-line before the end-of-file.
Output data specification
For each valid problem specification, list on separate lines
(1) Number of particles in the complete system, followed by the descriptive textual information from the
input file, reproducing exactly the spacing of the input.
(2) The required number of triples of numbers, giving the x, y, and z coordinates, separated by a single
blank and with only three digits to the right of the decimal point. Note that you may report a value of
-0.000 in case the value is small and negative.
(3) A blank line. This includes a blank line at the end of the file.
For an invalid problem specification, print the following message:
Illegal data: points do not define a plane
followed by a blank line.

Sample input:
6 octahedral symmetry obscured by rotation
0.500000 0.500000 -0.707107
-0.146447 0.853553 0.500000
-0.853553 0.146447 -0.500000
-0.500000 -0.500000 0.707107
0.146447 -0.853553 -0.500000
0.853553 -0.146447 0.500000
3 Duplicate point test
1
2
3
123
5
3
1
4 null operation test
0 0 3
0 -3 3
2 3 3
-1 -2 -3
0 termination record

Matching output:
6 octahedral symmetry obscured by rotation
0.000 0.816 0.577
0.707 -0.408 0.577
-0.707 -0.408 0.577
-0.000 -0.816 -0.577
-0.707 0.408 -0.577
0.707 0.408 -0.577
Illegal data: points do not define a plane
4 null operation test
0.000 0.000 3.000
0.000 -3.000 3.000
2.000 3.000 3.000
-1.000 -2.000 -3.000

136.Problem: SpinLock

Simulate a locked spinner puzzle.


Description
A locked spinner puzzle is a puzzle where you can only change wheels in groups. It is a common
puzzle to achieve some value on the spinners with by only changing them in the allowed groups.
Assume a row of D numbered wheels, such as what is found on a combination lock on a briefcase.

(example: wheels of a briefcase lock)


Each wheel will be labeled sequentially with the digits 0 through 9. The initial state of the wheels is part
of the problem specification.
Below this are a series of B buttons with labels that are D digits long. For example, D may be 4 and the
labels are 1000 1200 1002 0111 and 0100. Pressing the button labeled 1000 moves the first wheel
once, but leaves the others alone, while pressing the button labeled 1002 moves the first wheel once
and the fourth wheel twice, leaving the center button unchanged.
Your task is to simulate such a locked spinner puzzle, providing the final readout of the wheels.
Input
The input to your program will be several spinner puzzles. Each puzzle will be D digits (at most 10)
representing the starting positions of the wheels. Following this, each line will have the button label for
which button is pressed next. The end of each spinner puzzle will be marked with the character x
alone on a single line. End of the input file will be marked with the character z.
Sample Input:
0001
1003
0206
0034
1111
1003
x
91234567
12340051
33402401
x
z

Output
The output file should print the final positions of each spinner puzzles wheels. Provide the output
header Spinlock Results on the first line. Each puzzle follows on a separate line, formatted as below:
Sample Output:
Spinlock Results
3348
36976919

137.Problem: A Mayor Problem


Overview
Your company has recently been awarded the contract to keep the town streets painted. A proper job will take
you two months to finish, but elections are coming soon and the Mayor wants it done sooner. The Mayor called
your companys director; the companys director called your boss; and your boss called you. Due to a lack of
underlings to delegate to, this is now your problem.
You have quickly acquired some knowledge of the Mayors daily activities by buying a supermarket tabloid. The
newspaper tells you that the Mayor is an efficiency freak that refuses to travel any route between his starting point
and his destination that is not of minimum length (note that there can be more than one path of minimum length,)
and it provides a list of every place in town he visits. However, it fails to inform you of the order in which he visits
these places.
You quickly decide that the best solution is to paint every bit of road the Mayor can see, in the hopes that he will
think you are done early. This subterfuge will buy you extra time to finish the job in the rest of the town.
Problem
Given a map of the city grid and a list of the places the Mayor visits, return the number of city blocks you need to
paint. Assume that the Mayor can only see streets he travels on. For the sake of simplicity, the Mayor will only
travel between street corners. All city blocks are the same length.
Hint: you only need to consider valid paths. If a location is unreachable from and to any other, this is fine.
Input
The input file begins with the number of test cases it contains. After that, the test cases appear one after the
other, each preceded by a line of white space. The input file will always end with an end-of-line (EOL.)
Each test case contains the city grid, followed by a number specifying the number of locations the Mayor can visit,
followed by the locations in row-column order (zero based, the origin being the northwest corner of town.) The
city grid is described by two lines of text, each at least 2 and at most 10 characters long. The first line contains
the directions of the East-West streets (E, W, or T for two-way.) The second line contains the directions of the
North-South streets (N, S, or T.) Every location specified will be valid for the provided street grid. Sample input
follows.
Sample Input:
2
EE
SS
2
00
11
EW
TT
2
00
11
Output

The output begins with a case number (starting at one) followed by a line stating how many man-hours are
required. Print a blank line after every output case (this means the output will have two newlines at the end
before the end-of-file.) Sample output follows.
Sample Output:
Case #1:
4 street blocks need to be painted.
Case #2:
4 street blocks need to be painted.

138.Problem: Matchmaker, Matchmaker, Make Me a Match!


Suppose seven 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 dont 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 dont 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 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 file will contain a single integer greater than 0 specifying the number of data sets.
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 whitespace, that represents the preferences of that
supervisor from most preferred to least preferred. More specifically, the first entry on the line will represent that
supervisors 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 a carriage return.
Output
For each data set, write the data set 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 one blank line.
Sample input and output are provided on the next page:
Sample Input
2
7
1234567
2134567
3124567
4123567
5123467
6123457
7123456
1234567
2134567
3124567
4123567
5123467
6123457
7123456
2
12

21
12
12
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

139.Problem: Toy Storage

Mom and dad have a problem: their child John never puts his toys away when he is finished playing
with them. They gave John a rectangular box to put his toys in. Unfortunately, John is rebellious and
obeys his parents by simply throwing his toys into the box. All the toys get mixed up, and it is
impossible for John to find his favorite toys anymore.
John's parents came up with the following idea. They put cardboard partitions into the box. Even if John
keeps throwing his toys into the box, at least toys that get thrown into different partitions stay separate.
The box looks like this from the top:

Problem
For each i > 0 such that there exists a partition with i toys, determine how many partitions have i toys.
Provide a list of the values of i and their count of associated partitions.
Input
The input consists of a number of cases. The first line consists of six integers n m x1 y1 x2 y2. The
number of cardboards to form the partitions is n (0 < n <= 1000) and the number of toys is given in m (0
< m <= 1000). The coordinates of the upper-left corner and the lower-right corner of the box are (x1,y1)
and (x2,y2), respectively. The following n lines each consists of two integers Ui Li, indicating that the
ends of the i-th cardboard is at the coordinates (Ui,y1) and (Li,y2). You may assume that the
cardboards do not intersect with each other. The next m lines each consists of two integers Xi Yi
specifying where the i-th toy has landed in the box. You may assume that no toy will land on a
cardboard or on the boundary of the box.

The input is terminated by a line consisting of a single 0. Each line of input in the file is
terminated by the end of line character (\n).
Output
For each box, first provide a header stating Box on a line of its own. After that, there will be one line
of output per count (i > 0) of toys in a partition. The value i will be followed by a colon and a space,
followed the number of partitions containing i toys. Output will be sorted in ascending order of i for
each box.
Sample Input
4 10 0 10 100 0
20 20
80 80
60 60
40 40
59
15 9
95 9
25 9

65 9
75 9
35 9
45 9
55 9
85 9
5 6 0 10 60 0
43
15 30
31
68
10 10
21
28
15
55
40 9
79
0
Sample Output
Box
2: 5
Box
1: 4
2: 1

140.Problem: Grandmas Help


Your grandmother wanted to help you by doing data entry in your science project, so you gave her the hard-copy
print-outs and sat her at your computer. She learned touch typing as a young woman preparing to be a secretary,
and she is very good at it, reproducing exactly the text and its spacing.
There is one problem, though. She learned typing on the typewriters in use in the 1950s. Numbers were
available only in the number row above the alphabetic keys (just as on present keyboards), and they ran from 2 to
9. For the number one (1) the typist used a lower-case el (l), and for the number zero (0) she used an upper-case
oh (O).
The data include alphabetic text segments as well as numeric. That means that a simple find and replace edit is
inappropriate.
Write the filter that will generate appropriate numeric data according to the following context rule: a candidate
character (l or O) should be replaced with the appropriate numeric character if it is in a white-space delimited
field as described here:

The field may begin with a minus sign or a plus sign.


The field may contain one decimal point in any position, or it may have none.
All other characters are either numeric digits, or candidate characters.

The output is to be identical to the input except for this filtering, including reproducing the spacing.
Input
The input text is terminated by the end-of-file, which may or may not be preceded by an end-of-line. Note that you
are reproducing the input text exactly except for filtering out the use of l for 1 and the use of O for 0.
Warning: use the specified context rule as stated above, not what you would have chosen as the transformation
rules. For instance, this will not handle exponential notation correctly or arithmetic expressions without embedded
blanks.
Example Input:
l23.O5 liters water
Use distilled or at least deionized
ll.OOl ml O-negative blood
Note: negative on ALL Rh factors
l3.2Ol ml O-positive blood
Use procedure OOO.OOl2.l234
Example Output:
123.05 liters water
Use distilled or at least deionized
11.001 ml O-negative blood
Note: negative on ALL Rh factors
13.201 ml O-positive blood
Use procedure OOO.OOl2.l234

141.Problem: Particular Palindromes


A palindromic decimal integer reads the same forward and backward. For example, the following numbers are
palindromic.
6, 55, 282, 5005, 78187, 904409, 3160613, 11111111
Palindromic integers are plentiful. In fact, any integer not divisible by 10 has an infinite number of multiples that
are palindromic. (The standard representation of a nonzero multiple of 10 cannot be palindromic since its reversal
would have a leading 0.)
Write a program to determine, for a given positive integer, how many of its positive multiples are palindromes of a
given length.
Input
The first line of the input will specify an integer n indicating the number of problem instances to follow, one to a
line. Each of the ensuing n lines will specify a pair of positive integers m,s separated by a single space, with
1 < m < 1000, s < 20. (For m,s in this range, there are fewer than 2
of m.) Each line will terminate with an end-of-line.

32

palindromes among the s-digit multiples

Output:
The output should indicate for each m,s, exactly how many s-digit positive palindromes are divisible by m, with
one problem instance per line.
Sample input and output appear on the next page.
SAMPLE Input
5
31
25 3
12 4
30 3
81 6
SAMPLE Output
3
2
7
0
0
Explanation. There are three positive 1-digit multiples of 3, namely, 3, 6, and 9; all 1-digit numbers are trivially
palindromes. Among the 3-digit palindromes, 525 and 575 are multiples of 25. The 4-digit multiples of 12 that are
palindromes are 2112, 2772, 4224, 4884, 6336, 6996, 8448. There are no positive palindromic numbers ending
in 0 (since we do not allow leading 0's). No 6-digit palindromes are divisible by 81.

142.Problem: Audit Time


Action Comic Magazines budget for their new Intranet order entry site was pretty low, so they decided to build
their own database engine. It stores a set of customer accounts and is able to retrieve balances and update with
a new balance. The new balance is calculated and provided to the database by the client application. This is the
good news!
The bad news is that ACM really didnt understand transactions or how databases protect the integrity of their
data. In fact, customers accounts can be reviewed and updated by multiple users at the same time, without the
transactional controls normally found in a database engine. The result is a set of transactions having steps mixed
together (interleaved), with no assurance that the final result is correct.
A sample history of a set of two interleaved transactions illustrates the issue:
Transaction ID Action
CustomerID
Step #
1
Retrieve
A
1
1
Retrieve
B
2
2
Update
B
3
2
Update
A
4
1
Update
A
5
As you can see, Transaction 2s update of Customer A will be overwritten by Transaction 1s update to the same
customer. (This is an example of a lost update.)
You have been hired to determine which sets of transactions need to be subjected to a detailed audit. You will do
this by determining which transaction sets would have provided the same ending data had they been serialized in
a properly-written database.
Definitions:
Conflicting pairs: A pair of steps are in conflict if they are not in the same transaction, they access the same
customer account, and at least one step is an update. In the example above, conflicts exist between steps 1 and
4, 2 and 3, and 4 and 5.
Serial History: A history is serial if for any two transactions Ti and Tj in it, where i <> j, all operations from Ti are
ordered in s before all operations from Tj, or vice versa. In the example above, there are two possible serial
histories (either all steps from transaction #1 followed by all steps from transaction #2, or the reverse).
Problem Requirement:
For each interleaved transaction set history s, you must determine if there is an equivalent serial history s that
contains the same steps and where all conflicting pairs of steps occur in the same order in both histories.
Transaction sets meeting both these criteria need not be subjected to further audit.
The example transaction above does not meet the requirements of this problem since situating Transaction 1
before Transaction 2 would reverse the order of the conflicting pair {step 4, step 5}, while situating Transaction 2
first would reverse the orders in the conflicting pair {step 1, step 4} as well as the order in the conflicting pair {step
2, step 3}.
Input
The input to your program will be several transaction set histories. The first line will indicate the number of
histories to analyze.
Each historys first line is 1 digit h indicating the number of steps in the history. (Note: while the input will not
specify the number of transactions in a history, you may assume 0 < number of transactions < 20.) The next h
lines of input contain the transaction number, R (retrieve) or U (update), and the associated Customer ID as
shown below. One space separates each item in the row. An entry of 1 R 55 would indicate Transaction #1,
Retrieve, Customer #55.
SAMPLE Input:

2
4
1 R 55
2 R 55
2 U 55
1 U 55
8
1 R 55
2 R 55
1 R 70
1 U 55
2 U 80
3 R 70
3 U 80
3 U 70
Output
Your output will list each history and whether it requires investigation, as seen below. There are four spaces
between the colon and the result for each history.
SAMPLE Output
History #1: Needs Investigation
History #2: OK
Note: in the case of History #2 in the example above, the valid serial history would be to perform Transaction #2
first, followed by Transaction #1, followed by Transaction #3.

143.Problem: Bad Birthday Present


On my birthday my cousin Larry gave me a box inside a box inside a box inside a box inside a box, and there
wasnt anything inside the innermost box! Now his birthday is coming up. Of course Im not so crass or
unimaginative
as to do the same thing to him, but if I were, how many boxes could I force him to open? Your team is to write a
program that will help me calculate that.
To do that, youll be given several lists of boxes. For each list, your programs job will be to compute the greatest
number of boxes in that list that can be nested. More specifically, youre to compute the size of the largest subset
of
the boxes in a list, such that the smallest box of the subset fits within the second smallest, the second smallest of
the
subset fits within the third smallest, the third smallest fits within the fourth smallest, and so forth.
Each dimension of a box is given as an integer between 1 and 999, inclusive. A box fits into a second if each
dimension of the first is strictly smaller than the corresponding dimension of the second. A box can be rotated in
any
way necessary to allow it and a second box to nest, although it must be rotated through 90-degree anglesboxes
are
not to be rotated at odd angles when placed inside other boxes. Given n boxes, its possible all n can be rotated
so that
all of them nest. Its also possible that no single box of the n can be rotated to fit into any other; in that case the
largest
number of nesting boxes is 1 (since any single standalone box forms a trivially nested singleton.)
Your program should read data from standard input. The data will contain one or more lists of boxes. The lists
will immediately follow one another until the end of the file. The first line for each list is the number of boxes in the
list, and each line that follows gives the dimensions of a single box in the list. No line will have any leading or
trailing
whitespace, and the integers of a boxs dimensions will be separated from each other by a single blank.
For each list of boxes, you should print a single integer that is the maximum number of boxes that can be selected
from the original set to form a fully nesting subset. The integer should be printed to standard output on a line by
itself
with no leading or trailing whitespace.
The sample input describes a list of five boxes followed by a list of four boxes. Since imaginary revenge is the
most fun when you go completely overboard, expect that lists can contain anywhere from one to five hundred
boxes.
Input
5
145 472 812
827 133 549
381 371 900
271 389 128
718 217 491
4
432 123 139
942 844 783
481 487 577
677 581 701
Ouput
2
4

144.Problem: Account Statement


Your team works for a foreign low tech bank which just told their customers they will have account statements
at the end of each month. The boss has directed your team to complete the work needed to print out the
statements.
These accounts are long term Certificates of Deposit so customers may not make additional deposits or
withdrawals.
The bank also truncates all fractions beyond the hundredths place (thats one way they make their money).
Input to your program will be a file on standard input. Each line will contain an account number, the previous
cycles ending account balance, the number of days in the current cycle and the interest rate separated from each
other
by single spaces.
Account numbers can only be numeric.
Account balances are numeric only, with two digits after the decimal point (dollars and cents).
Days in cycle is a numeric value in the range 031.
Interest rates are real numbers with at most 3 decimal places and are given as Annual Percentage Rates (with
365
days in the year).
For each input line, calculate the simple interest earned in the month using the data supplied and produce output
that follows the format:
Account Number
Interest Earned
New Account Balance
Print the account number on a line starting in the first column. On the next line print 10 spaces followed by the
interest
earned for the month with two digits after the decimal point (dollars and cents). On the following line print 10
spaces
followed by the new account balance with two digits after the decimal point (also dollars and cents).
Input
030091128 5000.12 31 4.500
030091129 12534.99 30 5.25
Output
030091128
19.11
5019.23
030091129
54.08
12589.07

145.Problem: CMDB
Swamp County College is embarking on an effort to improve the management of the Colleges data center. The
college is adopting the ITIL (Information Technology Information Library) model for IT service management.
Originally developed by the British Government, ITIL covers a wide spectrum of IT service, application, and
infrastructure management best practices. ITIL is now being adopted widely in both the public and private sectors
worldwide.
The college IT department has determined that it needs to improve its understanding of the infrastructure within
the data center. In accordance with the ITIL model, the IT managers want to build a Configuration Management
Data Base (a CMDB) that contains information about the equipment in the data center, the connections between
that equipment, and the databases and software applications that run on the equipment. The objective is to be
able to identify the potential impact of downtime or maintenance of one infrastructure component on the
databases and applications supported by the infrastructure.
Building a full CMDB is a major undertaking. In order to get some value out of the process quickly, and gain
executive support and funding for the full project, the college is asking your team to develop a proof-of-concept
database and tool that will demonstrate the basic functions of a CMDB and help them when planning upgrades to
their critical infrastructure.
This proof-of-concept database will handle the following infrastructure components and the relationships between
them:
Storage Arrays
Storage (Fibre Channel) Switches
Network (IP) Switches
Servers
Databases
Applications
Each of these infrastructure components is referred to by ITIL as a configuration item (CI). The database will
contain a type definition of each CI and a list of relationships between them. Each CI will be defined as one of the
above types (storage array, storage switch, network switch, server, database, or application). CI names are
strings of between 1 and 31 upper case letters and digits, with the first character being a letter. No two CIs will
have the same name.
Relationships will be defined as connections or usage relationships between CIs; for example, a storage array
connects to a storage switch, a server connects to a network switch, a server may connect to a storage switch, an
application runs on a server, an application may use a database, an application may use another application, and
a server may use a storage array. Databases and applications that depend on each other may reside on different
servers, communicating with each other over the IP network.
Storage switches provide connections between a server and a storage array. Every path between a server and its
external storage will pass through only one storage switch. However, connections to storage arrays may be
redundantthat is, a given server may have independent connections to multiple switches, as may a storage
array. This means that there may be multiple paths between a server and a storage array. These redundant paths
are used to provide additional
bandwidth and redundancy, so that if one storage switch fails or is taken down for maintenance, access to storage
is not interrupted.
Similarly, servers may have connections to multiple network switches, providing multiple paths for network traffic
among databases and applications. Unlike storage, there may be multiple IP switches in a path between server
network ports.
Your team is to write a program that will read CMDB entries, then use the CMDB entries to answer queries about
the impact that a single down CI would have on database and application CIs.
Input to your program will be a series of CI definitions, followed by a series of CI relationships, and ending with
a series of queries. Each definition, relationship, and query appears on a line by itself, with the fields separated
from each other by one or more spaces. No input line will exceed 80 columns.
Each CI will be defined on a line containing the string CI, the CI name, and the type:
storage-array
storage-switch
network-switch
server
database
application
Each relationship will be defined on a line containing the string RE, a CI, the type of relationship (as listed

below), and another CI. The relationship definitions are as follows:


hstorage-arrayi connects-to hstorage-switchi
hserveri connects-to hstorage-switchi
hserveri connects-to hnetwork-switchi
hnetwork-switchi connects-to hnetwork-switchi
hserveri uses hstorage-arrayi
hdatabasei runs-on hserveri
happlicationi runs-on hserveri
happlicationi uses hdatabasei
happlicationi uses happlicationi
The CI relationships will be fully definedthere will be no missing paths between components. Each application
and database runs on only one server. Any application may use the services of several other applications and
databases.
Queries to the CMDB will begin with ?? followed by a CI that has failed or is scheduled for maintenance. Your
program is to print the CI being queried, followed by a list of database and application CIs that would be affected.
The CI being queried is to be printed on a line with the string Query: starting in the first column, followed by a
single space and the name of the CI. The affected database CIs are to be printed next, each on a separate line
that begins with Database: followed by a single space and the affected CI name. Applications are to be listed
last, using the same formateach on a separate line that begins with Application: followed by a single space
and the affected CI name.
The database and application CIs should be listed in ASCII lexical order. The lines containing affected CI names
are to begin in the fourth column. If a CI is listed because it is in a degraded state, print an asterisk in the third
column.
A CMDB storage switch query is to report that the databases and applications running on a given server are
running in a degraded state if the server can reach all its storage on one or more other paths. Should such a
server lose all connectivity to a storage array it uses, all databases and applications running on that server will be
down. If a server should lose a network connection that affects needed connectivity for applications that run on
the server, those applications will be degraded or down (based on the availability of other network paths).
Your proof-of-concept implementation is to have the capacity to handle 250 CI definitions and 1,000 CI
relationships.
Input
CI AA storage-array
CI S1 server
CI S2 server
CI S3 server
CI FCSW storage-switch
CI IPSW network-switch
CI ODB database
CI PDB database
CI FINANCE application
CI CRM application
RE CRM uses ODB
RE FINANCE uses PDB
RE S1 uses AA
RE S2 uses AA
RE S1 connects-to FCSW
RE S2 connects-to FCSW
RE AA connects-to FCSW
RE ODB runs-on S2
RE PDB runs-on S1
RE S1 connects-to IPSW
RE S2 connects-to IPSW
RE S3 connects-to IPSW
RE FINANCE runs-on S1
RE CRM runs-on S2
?? PDB
?? S2

Output
Query: PDB
Application: FINANCE
Query: S2
Database: ODB
Application: CRM

146.Problem: Solar Powered Data Center


BigOh Corporation is expanding into Swamp County by building a new datacenter housing thousands of powerful
server computers. Operating a datacenter requires a significant amount of electrical power, which is a particular
challenge given Swamp Countys poor infrastructure. Given Swamp Countys sub-tropical location, one thing the
county does have in large amounts is sunshine. BigOh, being an environmentally responsible company, is
exploring the possibility of building and operating a completely solar-powered datacenter. Your task is to help
estimate the feasibility of such a datacenter under various conditions.
Given a four-day sunlight forecast, information about the solar panels and the servers, and a list of jobs to
process, your teamis to write a programthatwill determine if the requested jobs can be completedwithout running
out of power.
The four-day sunlight forecast consists of four input lines with one-day forecasts, each of which consists of a day
name, sunrise time, sunset time, and cloud index floating point value between 0.000 and 1.000, separated from
each other by whitespace. Times are specified on a 24-hour clock, so, for example, 1:00 PMwould be written as
13:00. Day names will be single words of no more than 20 characters.
The solar panels in the solar array are all flat, unobstructed, and aligned to be perpendicular to the sun at noon.
On a day with exactly 12 hours of sunlight and a cloud index of 0.000, the solar panel array will collect 100
kilowatt hours (kWh). The amount of power collected scales linearly with the sunshine duration and cloud index.
For example, on a day with 15-hours of sunshine and a cloud index of 0.5, the array would generate 62.5 kWh.
No power at all is collected before dawn or after sunset.
Power flows from the solar panel arrays to a high-capacity battery system. This battery system has a large
capacity, but it is still limited to a given number of output kWh. The battery system also loses a certain percentage
of the power put into it. For example, a battery system that has a maximum output capacity of 100 kWh and is
80% efficient would have an output of 100 kWh if and only if the solar panel arrays generated at least 125 kWh
that day. The battery system capacity in kWh and efficiency percentage will be specified on one input line after the
forecast, separated by whitespace.
To protect the capacity of the batteries over their lifetime, the entire battery system is completely drained just
before dawn each day. To minimize overheating, the servers operate only during the cool late-night hours. The
servers are fast enough to do all needed work between sunset and midnight, so the time needed to execute each
job will not be a limiting factoronly the power consumed matters.
Each processing job is a massively parallel task that all servers work on as a group, and only one job may be
active at any moment in time. Each job must run to completion in a single night. Some jobs are independent of
other jobs, while others can only be run after some other job has produced needed output. The program input
may specify from one to ten jobs. Each job is described by one line with a unique upper-case letter ID, the kWh of
power needed to complete the job as a floating point value, the IDs of zero or more prerequisite jobs, and a
human-readable string inside quotation marks that describes the purpose of the job. These fields are separated
from each other by whitespace.
Your program should determine a four-day job schedule. Your programs output is to be a single line with the job
IDs in the order in which the jobs should be run, with the days separated from each other by vertical-bar
characters.
If there are multiple possible schedules, print the one which is lexigraphically first in ASCII. If there is no possible
schedule that will allow all jobs to complete without running out of power, your program should instead print one
line:
Insufficent sunlight for requested jobs. If the input specifies dependencies between jobs that contain a cycle or a
dependency on a non-existent job, print the line Invalid job dependencies.
Input
Mon 06:02 17:58 0.000
Tue 06:02 17:58 0.000
Wed 06:03 17:57 0.200
Thu 06:03 17:57 0.250
100 80%
A 12.0 "crawl web sites"
B 22.0 A "parse web pages"
C 18.8 "filter out spam emails"
D 45.9 B "build web page index"
E 69.6 B "compute page rank"
F 13.3 "optimize text advertising bids"

G 10.0 "crawl news sites"


H 47.2 "stitch together satellite photos"
I 4.9 B "classify pages for safesearch"
J 18.8 "transcode video clips"
Output
ABCIJ|E|DF|GH

147.Problem: Fly, Rent, or Drive Your Own?


The Confusion State University business office has a policy that requires all staff traveling on business to use the
most cost-effective mode of transportation possible. Cost-effective does not necessarily mean cheapest, however,
as the cost of the time spent traveling is also taken into account. The State of Confusion has fairly good airline
coverage, and reasonable roads, but the bus and rail transporation network leaves much to be desired in terms of
availability and timely performance. Therefore, most travel of any significant distance comes down to a fly-or-drive
decision. It became apparent during a recent review of staff travel expenses that in some cases, it is less
expensive to rent a car from the approved rental agency and pay for fuel than it is to pay for staff members to
drive their personal vehicles at the IRS-approved standard mileage rate. This provides a third alternative to
consider when arranging travel. The business office has retained your team to develop a program that will select
the most cost-effective mode of travel when arranging trips for staff members.
Input to your program will be a series of round-trip requests. Each round-trip request will contain the following
information on three lines, with fields separated from each other by single spaces:
1. The first line will contain a trip name (a string of 1 to 31 upper and lower-case letters, digits, and hyphens), the
total one-way road mileage as an integer, and the effective hourly pay rate for the staff member in dollars and
cents.
2. The second line will contain flight information: the cost of the round-trip ticket (in dollars and cents), the total
one-way flight duration (in whole minutes), the integer number of miles to the airport (in the event a traveler
drives his/her personal car to the airport), the total cost of airport parking (in dollars and cents), and the cost of a
round-trip shuttle as an alternative to driving to/from and parking at the airport (also in dollars and cents).
3. The third line will contain rental car costs: the total rental charges (in dollars and cents) and the per-gallon cost
of gasoline (also in dollars and cents).
Your program is to compute the estimated total round-trip costs for flying, driving a rental car, and driving a
personal vehicle (taking into account the cost of the time spent traveling in each case). Your program is to make
the following assumptions:
When staff members drive on trips (other than to and from airports), their average speed is 55 miles
per hour.
The IRS-approved reimbursement rate is 44.5 cents per mile.
For flying trips, the travel time each way will be the sum of the actual flying time, the time to get
to/from theoriginating airport, and a two hour allowance. The two hour allowance covers the time
spent at airports at each end of the trip along with destination ground transporation.
The travel time to/from the originating airport is to be calculated using an average in-city speed of 40
miles per hour. Originating airport travel time is the same whether a traveler drives and parks his/her
personal car or if a shuttle is used. A traveler should use the shuttle if it is cheaper than driving to and
from the airport and paying parking charges.
You may assume that the flying time is the same on the outbound and return trips.
If a traveler flies, assume destination ground transporation will be taken care of at no cost (e. g., free
hotel shuttle).
The State authorizes the use of compact rental cars that average 25 miles per gallon in actual use.
The review showed that the average added time to rent, refuel, and return a rental car is one hour per
trip.
For each trip, your program should print one line containing the name of the trip followed by a colon and a single
space, an upper-case letter representing the most cost-effective mode of transporation (either F for flying, R for
using a rental car, or D for driving a personal vehicle), a single space, and the total travel charges of the
selected option that will appear on the expense report (that is, not including the staff members pay for the
duration of travel).
The travel charges are to be printed in dollars and cents with a dollar sign before the leading digit.
All costs being equal, travelers prefer to drive their own vehicles over the other options, and prefer renting a car
to flying.
Input
Campus-Visit 222 26.50
310.20 67 22 36.00 67.00
109.08 2.25
Management-Visit 709 52.00
250.00 120 22 48.00 67.00
184.79 2.35

Output
Campus-Visit: R $149.04
Management-Visit: F $317.00

148.Problem: Booklet Page Order


The reprographic center at Swamp County High School is a sorry collection of mimeographs and aging
photocopiers.
Just recently, it acquired a new laser printer that can print duplex (on both sides of the paper) and 2-up (two
half-size pages on one side of a sheet of paper). To show off the new capabilities, the school wants to print this
years graduation program as a booklet rather than a bunch of 8.5 by 11 inch single-sided papers stapled
together. A booklet is stack of 8.5 by 11 inch papers folded in half along the 5.5 inch midline, then stapled along
the fold to make a simple spine.
Mr. Hack, the journalism teacher and a capable editor, was unable to determine the page print order necessary
to produce a booklet from a document with sequentially ordered pages. He turned to your team, the webmasters
for the schools undergroundwebsite, to produce a program to reorder the pages for proper printing. Given the
number of sequential pages in a document, produce the required number of sheets and proper page reordering
for proper printing as a 2-up duplex booklet.
Input to your program will be a list of document sizes (in total pages), one per line, terminated by end-of-file.
Each page count will appear as a positive integer beginning in the first column.
Output is one (potentially fairly long) line for each input line, describing the number of sheets needed and the
necessary page reordering. For each document size, print the number of sheets of paper required in a booklet,
followed by a colon, then the page numbers to print on each separate sheet of paper. For each sheet, print a
space followed by four comma-separated page numbers, where a page number of zero indicates a blank page.
The laser printer prints pages in A,B,C,D order as indicated on the diagram at the end of this problem (see figure
1). Order the sheets such that laying the sheets down with the first two pages (6,3 in the seven-page sample)
showing, then the next sheets pages
showing (0,1 in the seven-page sample) produce a stack of papers with page 1 on the facing (right hand) page,
ready to be stapled from the top.
A recent donation of very lightweight paper combined with a heavy duty stapler has made it possible to staple up
to 50 sheets of paper together.
Input
7
5
2
Output
2: 6,3,4,5 0,1,2,7
2: 0,3,4,5 0,1,2,0
1: 0,1,2,0

149.Problem: Grade Dropping 101


Welcome to Discrete Math I. Forty percent of your final grade will be based on your homework assignments.
Now everyone can have a bad day from time to time, so you will be allowed to drop the scores of up to three of
these assignments, but you have to choose which assignment scores to drop. Each assignment may have a
different maximum score. Choose carefully, as the final homework grade will be the percentage ratio of your total
score to the maximum possible score for the retained assignments.
Your team is to write a program that, given a list of assignment results, will calculate the best homework
percentage grade that can be obtained by dropping zero, one, two, and three of the assignments. For example:
Assignment Score Possible
1 41 42
2 22 64
3 2 26
4 11 44
5 24 27
6 26 70
7 4 30
The homework grade without dropping any assignments is:
41 + 22 + 2 + 11 + 24 + 26 + 4
42 + 64 + 26 + 44 + 27 + 70 + 30
= 42.9% (1)
The best result that can be obtained by dropping one assignment comes from dropping assignment 3:
41 + 22 + 11 + 24 + 26 + 4
42 + 64 + 44 + 27 + 70 + 30
= 46.2% (2)
Similarly, one can choose the two and three assignments to drop that yield the best possible final percentage.
Input to your program will be a series of test cases terminated by end-of-file. Each test case will be a series of
integers on one ormore lines and will be terminated by a line that contains only an end-of-line character (an empty
line) or by the end-of-file. The numbers are separated by whitespace and may be preceded and followed by white
space.
No input line will be longer than 80 characters. The integers are in pairsthe first integer is the students score for
an assignment, the second integer is the maximum possible score for that assignment. There will be at least 4
and at most 30 assignment score pairs per test case. For each pair, the maximum score will range from 1 to 100,
and the student score will range from 0 to the maximum score (no extra credit is offered).
For each test case, your program is to print a single line containing the best possible final homework grade as a
percentage after dropping zero, one, two, and three assignments respectively. Each percentage is to be rounded
and printed with one digit after the decimal point. Percentages should be printed starting in the first column and
are to be separated from each other by single spaces. No trailing spaces should appear on the line. Do not print
excess leading or trailing zeroes, but do print single zeroes adjacent to the decimal point (such as 42.0 or 0.7).
Input
7 48 0
83 59 76 13
100
41 47 42 56 20 63 35 45 30 98 41 73 30 59 25 31 40 48 41 99
31 39 12 97 20 53 32 56 55 95 49 61 58 74 41 70 36 36 0 49
56 84 37 65 52 74 15 51 87 95 11 51 24 88 10 46 90 96 80 93
0 30 19 99 44 74 24 46 19 21 71 77 34 49 43 59 16 39 25 33
22 82 19 85 11 88 32 65 1 88 48 51 9 43 48 60 14 25 23 65
42 48 43 97 14 33 9 48 81 93 3 85 9 98 19 86 9 98 57 60
18 56 25 68 84 88 2 12 35 83 8 16 6 74
30 78 92 99 11 42 40 96 28 74 10 41 32 74
41 42 22 64 2 26 11 44 24 27 26 70 4 30
Output
25.7 35.3 53.2 77.6
57.3 59.6 61.2 62.9

42.0 43.9 45.9 48.1


44.8 53.3 57.7 65.1
48.2 50.3 52.7 56.6
42.9 46.2 50.2 56.8

150.Problem: Blurred Vision


Aliasing is the stair-step effect achieved when attempting to represent a smooth curve using a finite number
of discrete pixels. Of course, all computer displays consist of a finite number of pixels, and many strategies
have been devised to smooth the jagged edges with varying degrees of success.
Boudreaux and Thibodeaux are writing video game rendering software for the next big first-person shooter,
and they don't know much about any of the progress made in the field of anti-aliasing. Therefore, they've
decided to use a very simplistic (and visually unappealing) method to smooth the ragged edges.
Unfortunately, it blurs the entire image, but at least it gets rid of those jaggies!
Normally, the game displays in m x n pixels, but they perform an extra anti-aliasing step that converts that
image into an (m - 1) x (n - 1) image. Nobody will notice a pixel missing from each dimension, and
they can calculate the new pixels by averaging squares of 4 pixels from the original image (and rounding
down). For example, the images below represent the original image (left) and the anti-aliased image (right)
using numbers to represent varying shades of black and white.

Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be
formatted according to the following description, and there will be no blank lines separating data sets.
A single data set has 3 components:
1. Start line - A single line:
START R C
where R and C are integers (2 (R,C) 9) indicating the number of rows and columns in the input
image described by this data set.
2. Original Image - A series of R lines, each of which contains C integers from 0 to 9 inclusive. These
integers represent the grayscale value of a pixel in the original image and will not be separated by
spaces.
3. End line - A single line:
END
After the last data set, there will be a single line:
ENDOFINPUT
Output
The output will be the anti-aliased image, which will be R - 1 rows, each with C - 1 integer pixel values.
Each pixel in the output will be generated by averaging (and rounding down) the grayscale pixel values of
the corresponding square of four pixels in the Original Image.
Sample Input
START 2 2
00
00
END
START 2 9
012345678
012345678
END
START 4 4
4440
4400

4000
0000
END
START 9 9
900000009
090000090
009000900
000909000
000090000
000909000
009000900
090000090
900000009
END
ENDOFINPUT
Sample Output
00
1234567
431
310
100
42000024
24200242
02422420
00244200
00244200
02422420
24200242
42000024

151.Problem: Keep on Truckin'


Boudreaux and Thibodeaux are on the road again . . .
"Boudreaux, we have to get this shipment of mudbugs to Baton Rouge by tonight!"
"Don't worry, Thibodeaux, I already checked ahead. There are three underpasses and our 18-wheeler will fit
through all of them, so just keep that motor running!"
"We're not going to make it, I say!"
So, which is it: will there be a very messy accident on Interstate 10, or is Thibodeaux just letting the sound
of his own wheels drive him crazy?
Input
Input to this problem will consist of a single data set. The data set will be formatted according to the
following description.
The data set will consist of a single line containing 3 numbers, separated by single spaces. Each number
represents the height of a single underpass in inches. Each number will be between 0 and 300 inclusive.
Output
There will be exactly one line of output. This line will be:
NO CRASH
if the height of the 18-wheeler is less than the height of each of the underpasses, or:
CRASH X
otherwise, where X is the height of the first underpass in the data set that the 18-wheeler is unable to go
under (which means its height is less than or equal to the height of the 18-wheeler).
The height of the 18-wheeler is 168 inches.
Sample Input
180 160 170
Sample Output
CRASH 160

152.Problem: The Door/Key Problem


Thibodeaux has managed to once again lock himself inside his own house (this happens all too often).
Boudreaux, being the good buddy that he is, has taken the precaution of scattering keys to the locked rooms
throughout Thibodeaux's house. It is up to you to determine if Thibodeaux can make it to his bedroom
(room 0).
Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be
formatted according to the following description, and there will be no blank lines separating data sets.
A single data set has 4 components:
1. Start line - A single line:
START M N
where M indicates the starting room, and N indicates the number of rooms in the house (1 N 20).
2. Room list - A series of N lines. Each line lists, for a single room, every door that leads to a room of
higher number and the keys necessary to open the door from either side. Rooms will be represented
by numbers and each key will be represented by a single capital letter (A - Z). For example, if room
3 had doors to rooms 1, 5, and 7, and the door to room 1 took an A key, the door to room 5 took an F
key, and the door to room 7 took an X key and a P key, the line for room 1 would read:
3A
and the line for room 3 would read:
5F 7PX
The first line in the list represents room 0. The second line represents room 1, and so on until the last
line, which represents room N - 1. It is possible for lines to be empty (in particular, the last line will
always be empty since it is the highest numbered room). On each line, the adjacent rooms are always
listed in ascending order. It is possible for rooms to be connected by multiple doors and for doors to
require multiple keys; required keys for a door will be listed in alphabetical order.
3. Key list - A series of N lines. Each line lists, for a single room, the keys, in alphabetical order, that are
in that room.
4. End line - A single line:
END
After the last data set, there will be a single line:
ENDOFINPUT
Notes:
There will be no more than 100 doors in any data set.
No room will have more than 20 doors.
Some doors may not require keys.
In any data set, all keys are unique and can be used multiple times.
Output
For each data set, there will be exactly one line of output. If it is possible for Thibodeaux to reach his
bedroom (room 0), print a line:
YES
Otherwise, print a line:
NO
Sample Input
START 1 2
1A
AE
ND
START 1 5
1F
2A 2B 3CD 3E
BC
D
FA
E

END
START 1 10
9I
2A
3B
4C
5D
6E
7F
8G
9H
AB
CDEFGHXE
ND
ENDOFINPUT
Sample Output
YES
YES
NO

153.Problem: Exact Change Only


Boudreaux reached over and shook awake Thibodeaux, who had dozed off somewhere in New Mexico.
"Where we at?" Thibodeaux groggily yawned.
"Not in Vegas, I gua-ran-tee, but could you get my knapsack?" Boudreaux asked, gesturing to the worn,
leather backpack in the back seat of their cherry red Ford Miata.
"Why, is there a problem?"
"Just hand me my knapsack, problem or not."
Thibodeaux complied, glancing up as Boudreaux slowed the car to a stop in a line of vehicles approaching a
toll booth. "$1.65 -- Exact change only," Thibodeaux read the yellow sign on the front of a small wooden
building occupied by a lone toll booth operator. "I have to get $1.65 in exact change?" Thibodeaux asked,
digging through the knapsack, "all I have are ten quarters, four dimes, and three pennies. I don't have any
nickels . . ."
"Just give me five of the quarters and the four dimes," Boudreaux replied, holding out his hand.
"Oh yeah," Thibodeaux said, handing over the coins, "that does add up to $1.65. I wish there were an easy
way to figure out if you have an exact monetary amount, given a set of coins."
"Hmmm," Boudreaux shrugged, "sounds like a good programming problem."
Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be
formatted according to the following description, and there will be no blank lines separating data sets.
A single data set has 1 component:
1. Start line - A single line:
ABCDE
where:
A: (0.01 A 5.00) is a decimal number (to two decimal places) of a monetary amount.
B: (0 B 100) is an integer number of quarters (one quarter = $0.25).
C: (0 C 100) is an integer number of dimes (one dime = $0.10).
D: (0 D 100) is an integer number of nickels (one nickel = $0.05).
E: (0 E 100) is an integer number of pennies (one penny = $0.01).
Output
For each data set, there will be exactly one line of output. If there exists one or more subsets of the given
coins whose values add up to the given monetary amount exactly, the output will be a single line in the
form:
ABCD
where A is the number of quarters, B is the number of dimes, C is the number of nickels, and D is the number
of pennies, for the subset with the fewest number of coins. Otherwise, the output will be a single line with
the statement:
NO EXACT CHANGE
Sample Input
0.45 2 1 1 4
0.75 3 7 1 75
Sample Output
NO EXACT CHANGE
3000

154.Problem: Finding Nemo


Boudreaux and Thibodeaux are just returning from watching Finding Nemo and are finding themselves
pretty hungry after watching all those fish swim around for a couple of hours. Like the true Cajuns that they
are, they jump into their pickup and head on over to the local bayou. Upon arriving Boudreaux realizes that
in their mad hunger rush, they have completely forgotten their fishing poles and tackle. Boudreaux yells out
to Thibodeaux, "Hey couyon, you forgot about dem poles!" and Thibodeaux replies "Don't worry, I got me
some fish sticks out in the truck." Boudreaux later finds out that "fish sticks" are really dynamite, to which
he replies "Mais fool, now how you suppose we gonna know where to place dem sticks to catch some fish?"
at which point Thibodeaux then breaks out his fish finder and laptop and whips up a program that will tell
them just that.
Given the position of all the fish in the bayou and the spot Boudreaux and Thibodeaux want to drop their
dynamite (after lighting the fuses of course), you are to write a program that will tell how many fish they
will kill, ahem, I mean catch. Each dynamite stick has a certain fuse length that determines at which depth it
will blow up. Any fish within a one unit radius of the dynamite when it blows up is as good as fish fried.
Keep in mind that the fish never move from their location, and the dynamite sticks fall straight to the bottom
of the bayou.
Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be
formatted according to the following description, and there will be no blank lines separating data sets.
A single data set has 4 components:
1. Start Line - A single line:
START L W D
where (1 (L,W,D) 20). L is the length of the bayou along the x-axis, W is the width of the bayou
along the y-axis, and D is the depth of the bayou on the z-axis.
2. Dynamite List - A single line containing a space-separated list of 1 to 10 data elements. Each element
contains the location and fuse length of a single stick of dynamite as it is dropped into the bayou
formatted as:
x,y,f
x and y give the surface coordinates of the drop where (0 x L) and (0 y W). f is the length
of the fuse and is in the range (0 f 30).
3. Fish List - A single line containing a space-separated list of 1 to 15 data elements. Each element
represents the location of a fish in the bayou formatted as:
x,y,z
where (0 x L), (0 y W), and (0 z D), where z = 0 indicates the fish is at the surface
of the water.
4. End line A single line:
END
After the last data set, there will be a single line:
ENDOFINPUT
Note:
All numeric values will be given as integers.
The dynamite drops at a constant speed from the top of the bayou (z = 0).
The fuse burns up one unit of its length in precisely the amount of time it takes the dynamite to sink
one unit deeper into the bayou.
If the dynamite reaches the bottom of the bayou before the fuse runs out, it will stay there until it
detonates.
Multiple fish will not occupy the same position.
Fish are killed if their distance from any dynamite explosion is 1.
Output
For each data set, there will be exactly one line of output. The output will be a phrase stating how much fish
Boudreaux and Thibodeaux will be frying up tonight.
If they blow up at least one fish, the following phrase will be printed:
AIEE, I got N fish, me!
where N is the number of fish blown up. If they don't blow up any fish, the following phrase will be printed:
None of dem fish blowed up!

Sample Input
START 5 5 5
1,1,1 2,2,2 3,3,3
4,3,0 4,4,4 3,0,2 2,1,3 3,3,3
END
START 2 3 4
1,1,10 1,1,1 0,2,2
0,0,1
END
ENDOFINPUT
Sample Output
AIEE, I got 1 fish, me!
None of dem fish blowed up!

155.Problem: Series Determination


Boudreaux and Thibodeaux aren't very good at math, so they need you to write a program that can
determine the second degree polynomial used to generate a given sequence of three integers. As proof that
you've figured out the polynomial, they want your program to print out the next 3 integers in the sequence.
You know that each sequence is generated by a polynomial of the form f(x) = Ax2 + Bx + C, where A, B,
and C are integers in the range (-103 (A, B, C) 103). You are given the values f(0), f(1), f(2)
and are to determine the values f(3), f(4), f(5).
Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be
formatted according to the following description, and there will be no blank lines separating data sets.
Each data set consists of a single line containing the space-separated integer values of the polynomial
evaluated at 0, 1, and 2 (in that order). These values will be in the range (-103 (f(0), f(1), f(2))
103).
Output
For each data set, there will be exactly one line of output containing the space-separated integer values of
the polynomial evaluated at 3, 4, and 5 (in that order). These values will be in the range (-104 (f(3),
f(4), f(5)) 104).
Sample Input
000
111
123
014
028
Sample Output
000
111
456
9 16 25
18 32 50

156.Problem: T-Shirt Gumbo


Boudreaux and Thibodeaux are student volunteers for this year's ACM South Central Region's
programming contest. One of their duties is to distribute the contest T-shirts to arriving teams. The T-shirts
had to be ordered in advance using an educated guess as to how many shirts of each size should be needed.
Now it falls to Boudreaux and Thibodeaux to determine if they can hand out T-shirts to all the contestants
in a way that makes everyone happy.
Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be
formatted according to the following description, and there will be no blank lines separating data sets.
A single data set has 4 components:
1. Start line - A single line:
START X
where (1 < X < 20) is the number of contestants demanding shirts.
2. Tolerance line - A single line containing X space-separated pairs of letters indicating the size
tolerances of each contestant. Valid size letters are S - small, M - medium, L - large, X - extra large, T extra extra large. Each letter pair will indicate the range of sizes that will satisfy a particular
contestant. The pair will begin with the smallest size the contestant will accept and end with the
largest. For example:
MX
would indicate a contestant that would accept a medium, large, or extra large T-shirt. If a contestant is
very picky, both letters in the pair may be the same.
3. Inventory line - A single line:
SMLXT
indicating the number of each size shirt in Boudreaux and Thibodeaux's inventory. These values will
be between 0 and 20 inclusive.
4. End line - A single line:
END
After the last data set, there will be a single line:
ENDOFINPUT
Output
For each data set, there will be exactly one line of output. This line will reflect the attitude of the contestants
after the T-shirts are distributed. If all the contestants were satisfied, output:
T-shirts rock!
Otherwise, output: I'd rather not wear a shirt anyway...
Sample Input
START 1
ST
00100
END
START 2
SS TT
00100
END
START 4
SM ML LX XT
01110
END
ENDOFINPUT
Sample Output
T-shirts rock!
I'd rather not wear a shirt anyway...
I'd rather not wear a shirt anyway...

157.Problem: Window Pains


Boudreaux likes to multitask, especially when it comes to using his computer. Never satisfied with just
running one application at a time, he usually runs nine applications, each in its own window. Due to limited
screen real estate, he overlaps these windows and brings whatever window he currently needs to work with
to the foreground. If his screen were a 4 x 4 grid of squares, each of Boudreaux's windows would be
represented by the following 2 x 2 windows:

When Boudreaux
brings a window to the foreground, all of its squares come to the top, overlapping any
squares it shares with other windows. For example, if window 1 and then window 2 were brought to the
foreground, the resulting representation would be:

If window 4 were then brought to the foreground:

. . . and so on . . .
Unfortunately, Boudreaux's computer is very unreliable and crashes often. He could easily tell if a crash
occurred by looking at the windows and seeing a graphical representation that should not occur if windows
were being brought to the foreground correctly. And this is where you come in . . .
Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be
formatted according to the following description, and there will be no blank lines separating data sets.
A single data set has 3 components:

1. Start line - A single line:


START
2. Screen Shot - Four lines that represent the current graphical representation of the windows on
Boudreaux's screen. Each position in this 4 x 4 matrix will represent the current piece of window
showing in each square. To make input easier, the list of numbers on each line will be delimited by a
single space.
3. End line - A single line:
END
After the last data set, there will be a single line:
ENDOFINPUT
Note that each piece of visible window will appear only in screen areas where the window could appear
when brought to the front. For instance, a 1 can only appear in the top left quadrant.
Output
For each data set, there will be exactly one line of output. If there exists a sequence of bringing windows to
the foreground that would result in the graphical representation of the windows on Boudreaux's screen, the
output will be a single line with the statement:
THESE WINDOWS ARE CLEAN
Otherwise, the output will be a single line with the statement:
THESE WINDOWS ARE BROKEN
Sample Input
START
1233
4566
7899
7899
END
START
1133
4133
7799
7799
END
ENDOFINPUT
Sample Output
THESE WINDOWS ARE CLEAN
THESE WINDOWS ARE BROKEN

158.Problem: IM Poster Imposter


As part of the class pedagogy, your professor requires that all students participate in an on-line discussion group.
The professor suspects
that one student isn't contributing, rather that a fellow student is signing on and posting various messages as both
users.
The professor assumes that the two sets of messages posted by the same user will have more words in common
than any other pair of sets of
messages posted to the group. Your task is to write code to determine which two users have the "highest degree
of overlap" in word usage. The
specific measure of "degree of overlap" to be used is the ratio of distinct common words to total distinct words in
the two groups.
Case is ignored; punctuation, and any token not one of a-z or 0-9, is removed and not treated as a word
boundary. So, for example, the word
The_Decider$ is equivalent to the word thedecider.
Input
Input will be an unknown number of lines, each of the form:
user-name: list of words in post separated by spaces
Each post will be contained on a single line. There are an unknown number of distinct users.
As an example, consider the exchange:
Van: cool chat topic.
Gwen: sorry to be a PITA, but what's today's topic?
Bluto: queues.
Otter: 'Cuse? The orangemen? LOL
Bluto: what's a PITA?
Van: you can get a veggie pita for $5. LOL
Gwen: can we get back to queues?
The 4 users give us the following pairs:
(Van, Gwen), (Van, Bluto), (Van, Otter),
(Gwen, Bluto), (Gwen, Otter), (Otter, Bluto)
Van uses 12 distinct words:
{5 a can chat cool for get lol pita topic veggie you}
gwen uses 16 words, with only 15 distinct:
{a back be but can get pita queues sorry the to todays topic we whats}
Otter uses 4 words: {cuse lol orangemen the}
Bluto uses 4 words: {a pita queues whats}
The pair (Van,Gwen) uses 22 distinct words with 5 words of overlap for a ratio of 5/22 = 0.23. The pair (Van,Bluto)
uses 14 distinct words with 2 words of overlap for a ratio of 2/14 = 14. The pair (Van,Otter) uses 15 distinct words
with 1 word of overlap for a ratio of 1/15 = 07. The pair (Gwen,Bluto) uses 15 distinct words with 4 words of
overlap for a ratio of 4/15 = .27. The pair (Gwen,Otter) uses 18 distinct
words with 1 word overlap for a ratio of 1/18 = .05. The pair (Otter,Bluto) uses 8 distinct words with 0 overlap.
So, with a precision way beyond the reasonableness of our measure we can state that Bluto and Gwen are one
and the same student.
Output
The names of the users who are deemed to be the same are displayed.

159.Problem: Stakes on a Plane


A building site is laid out on a planar rectangular grid of M units by N units. K customers have ordered homes,
each with a specified area
for its footprint. You are to place stakes on the grid to show the outline of each home, or specify that no
arrangement is possible to
accommodate all the required homes.
Stakes can be placed only at multiples of integral unit points. Each house has a convex rectangular shape (i.e., no
L-shaped or U-shaped or
other irregularly formed homes; just rectangles, including squares.)
Input
consists of K+1 lines:
- line one contains M and N separated by a space
- each of the next K lines has a single integer specifying the square
units needed for each home
Input example
5 12
5
10
9
Output
Should be an ASCII image of the grid with the stakes suitably
placed. Each stake is represented by a number corresponding to the order in which that house's area was input.
Grid points with no stakes
should be represented with a lower case letter 'o'. There should be no spaces between the grid points
For example if a 5 X 12 grid were specified, you might have a mental image similar to that below, where the 'o's
denote where stakes may be
placed. Note that 5, the first number, denotes the number of units going down the page, while 12 is the number of
units across. Note also,
that the stake locations form a 6 x 13 grid since measurement starts at zero.
ooooooooooooo
ooooooooooooo
ooooooooooooo
ooooooooooooo
ooooooooooooo
ooooooooooooo
If you had to place three homes with areas 5, 10, and 9 on the lot, as shown above as our example input, one
solution would be:
111111222222o
1111112oooo2o
oooooo222222o
3333333333ooo
3333333333ooo
Ooooooooooooo
Notice that the 1's outline an area of 5 units, the 2's
outline the home with 10 unit area, and the 3's the
area for the home of 9 square units, since that is
the order in which the data appeared.

160.Problem: Lengths and Limits


The mystery sequence of numbers for positive integer X is defined by the following process:
to compute mysseq(X) do
if ( X = 1) then
record X
stop
else if ( X is even ) then
record X
mysseq(X/2)
else
record X
mysseq((3*X)+1)
end
end
Thus, for example:
mysseq(1) = < 1 >
mysseq(2) = < 2 1 >
mysseq(3) = < 3 10 5 16 8 4 2 1 >
mysseq(4) = < 4 2 1 >
mysseq(5) = < 5 16 8 4 2 1 >
mysseq(6) = < 6 3 10 5 16 8 4 2 1 >
mysseq(7) = < 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 >
mysseq(8) = < 8 4 2 1 >
mysseq(9) = < 9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 >
mysseq(10) = < 10 5 16 8 4 2 1 >
mysseq(11) = < 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 >
mysseq(12) = < 12 6 3 10 5 16 8 4 2 1 >
mysseq(13) = < 13 40 20 10 5 16 8 4 2 1 >
mysseq(14) = < 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 >
mysseq(15) = < 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 >
For any given positive integer X the length and limit of the mystery sequence corresponding to X are defined as
follows:
length(mysseq(x)) = the number of elements in the sequence
limit(mysseq(x)) = the highest number in the sequence
The Problem: Write a program to compute and display, labeled, the following two numbers:
1. The maximum length of the sequences corresponding to the values from 1 to 5000.
2. The maximum limit of the sequences corresponding to the values from 1 to 5000.
(Note that for the sequences corresponding to the values from 1 to 15 the maximum length is 20 (sequence 9)
and the maximum limit is 160 (sequence 15).)

161.Problem 4: Traveling Insect Problem


An insect is to fly in a sequence of shortest distance straight lines from the origin to a number of points in 3-space
and back to the origin. Your job is to find a sequence of the
points which produces a shortest distance for the entire trip.
The Problem: Write a program consistent with the following input/output specification.
Input
A positive integer followed by that number of points in three space. Assume that each point takes the form of a left
parenthesis followed by three integer values
between -100 and 100, each separated by a space, followed by a right parenthesis. For example, the following
are possible data sets:
1 (1 1 1)
2 (1 2 3)(3 2 1)
3 (62 19 -92)(5 -93 32)(-94 -97 -54)
4 (-58 -12 66)(-90 57 54)(94 -41 -69)(-50 38 26)
5 (1 2 3)(8 80 3)(1 1 1)(11 5 3)(-3 -4 -5)
6 (-48 -61 24) (63 6 36) (-62 27 86) (62 19 -92) (5 -93 32) (-94 -97 -54)
Output
The distance of a shortest route which starts at the origin, goes to each of the given points (in whichever order
produces a shortest route), and returns to the origin.
Example
If the input is
5 (1 2 3)(8 80 3)(1 1 1)(11 5 3)(-3 -4 -5)
then the answer would be 181.6 since the route (0 0 0) --> (1 1 1) --> (1 2 3) --> (11 5 3) --> (8 80 3) --> (-3 -4 -5)
--> (0 0 0) is of distance 181.6
and there is no shorter route by which the straight flying insect can visit each point, beginning and ending at the
origin.

162.Problem: Palindromic Sentences


You've just been hired as Secur's new computer security guru. Your boss thinks that the new security breaches
will be in the form of text files that contain palindromic
sentences. A sentence ends in any of ".", "!", or "?".
Your job is to find and report on all sentences in a file:
If the sentence is a palindrome, output "YES" followed by the sentence,
otherwise output "NO" followed by the sentence. Notice that a sentence may span more than one line.
Input
Go hang a salami, I'm a lasagna hog! Eve damned Eden (mad Eve!).
Bosnia gasps again -- sob! Er was I saw Elba. Stressed was I, sad, alas, to order a redroot salad as I saw
desserts. He was, was he? I did, did I
Output
YES Go hang a salami, I'm a lasagna hog!
YES Eve damned Eden (mad Eve!).
YES Bosnia gasps again -- sob!
NO Er was I saw Elba.
YES Stressed was I, sad, alas, to order a redroot salad as I saw desserts.
YES He was, was he?
YES I did, did I?

163.Problem 6: Hotter Colder


The childrens game Hotter Colder is played as follows. Player A leaves the room while player B hides an object
somewhere within. Player A re-enters at position (0, 0) and
then visits various other locations about the room. When player A visits a new position, player B announces
Hotter if this position is closer to the object, than the previous
position, Colder if it is farther, and Same if it is the same distance.
Input
Input consists of up to 50 lines, each containing an (x, y)-coordinate pair followed by Hotter, Colder, or Same.
Each pair represents a position within the room, which
may be assumed to be a square with opposite corners at (0, 0) and (10, 10).
Output
For each line of input, print a line giving the total area of the region in which the object may have been placed, to
two decimal places. If there is no such region, output
0.00.
Sample Input
10.0 10.0 Colder
10.0 0.0 Hotter
0.0 0.0 Colder
10.0 10.0 Hotter
Sample Output
50.00
37.50
12.50

164.Problem: Watch the Skies!


Air PC, an up-and-coming air cargo firm specializing in the transport of perishable goods, is
in the process of building its central depot in Peggys Cove, NS. At present, this depot can
handle at most one airplane on the ground at a time; however, given the increasing volume
of business, up to 8 airplanes may arrive simultaneously at this terminal at a particular
time T and need to land to offload cargo. Each of these airplanes has a servicing time st
(in minutes) required to land, offload, and take off again. Safety-conscious company that
it is, Air PC always makes sure that its airplanes carry enough fuel that any landing-order
of the airplanes is possible, i.e., does not result in crashes due to one or more airplanes
running out of fuel while waiting to land. However, courtesy of a contract clause devised by
an over-zealous (and now former) junior sales manager, all landing-orders are not equally
profitable this is so because each airplane also has a deadline time dt (in minutes) such
that if the airplane is not landed or in the process of landing by time T + dt, Air PC must
pay a perishable-cargo spoilage penalty sp (in dollars) to the customer.
Write a program which, given a set of n 1 simultaneously-arriving airplanes with their
respective servicing and deadline times and spoilage penalties, determines the landing-order
that minimizes the total spoilage penalty that must be paid out by Air PC. The input will
consist of a file in which the first line is the number of inputs and each input on n airplanes
consists of (n + 1) lines such that line 1 specifies n and lines 2 to (n + 1) specify the name,
st, dt, and sp for each airplane in that input. Each airplane name is a character string with
no embedded spaces and st, dt, and sp are positive, non-zero integers. You may assume that
all input files are formatted correctly and that each input file specifies an instance of the
problem that has exactly one optimal landing-order.
Sample input:
3
2
PC1175 30 20 100
PC1184 15 20 100
3
PC1175 30 20 350
PC0099 10 25 1000
PC1184 25 25 200
3
PC1175 30 30 350
PC0099 45 15 400
PC1184 25 25 100
Sample output
Note blank line after each input test case.
>>> Input #1:
Optimal Landing Schedule:
1: PC1184 (penalty = $0) [Lands at time T]
2: PC1175 (penalty = $0) [Lands at time T + 15 min]
>>> Total penalty: $0
>>> Input #2:
Optimal Landing Schedule:
1: PC0099 (penalty = $0) [Lands at time T]
2: PC1175 (penalty = $0) [Lands at time T + 10 min]
3: PC1184 (penalty = $200) [Lands at time T + 40 min]
>>> Total penalty: $200
>>> Input #3:
Optimal Landing Schedule:
1: PC1184 (penalty = $0) [Lands at time T]
2: PC1175 (penalty = $0) [Lands at time T + 25 min]
3: PC0099 (penalty = $400) [Lands at time T + 55 min]
>>> Total penalty: $400

165.Problem: OK Sudoku?
Sudoku is a popular puzzle game where one puts numbers on a grid. The grid has 9 rows
and 9 columns, and is divided into 9 blocks, each with 9 squares. In each square one of
the numbers from '1' to '9' is placed. For example, the following is an example of a
completed Sudoku grid:
123 456 789
456 789 123
789 123 456
234 567 891
567 891 234
891 234 567
345 678 912
678 912 345
912 345 678
The grid is considered valid if all of the following rules are met:
1.Each row contains the numbers from 1 to 9 (inclusive) exactly once each.
2. Each column contains the numbers from 1 to 9 (inclusive) exactly once each.
3. Each 3 by 3 block, of which there are 9, contains the numbers from 1 to 9
(inclusive) exactly once each.
Thus, the above example satisfies these rules and can be considered as valid. The grid is
considered invalid if any of the rules are broken. For example, the following is an
example of an invalid grid:
123 456 789
912 345 678
891 234 567
789 123 456
678 912 345
567 891 234
456 789 123
345 678 912
234 567 891
In this grid, the first block contains the number 1 three times, the number 2 twice, the
number 9 twice, and is missing the numbers 4, 5, 6, and 7. For these reasons, among
others, the grid is invalid. Your task is simple, to write a validity tester for Sudoku grids.
Input
Your input will consist of 11 lines of text. Lines 1 to 3, 5 to 7, and 9 to 11 each contain 3
groups of 3 integers separated by a single space. Each line is a row in a Sudoku grid, and
the 9 integers are the values in the 9 columns. Lines 4 and 8 are blank.
Output
Your output will consist of a single word. Output the word valid if the input represents
a valid Sudoku grid, otherwise output the word invalid if the input does not represent
a valid Sudoku grid.
Example Input
111 222 333
222 333 444
333 444 555
444 555 666
555 666 777
666 777 888
777 888 999
888 999 111
999 111 222

Example Output
invalid

166.Problem: Second Shortest Path


A number of agencies are after Max. Max is known to travel various graphs. His
practice was to always choose a shortest path from a start vertex to his end vertex but he
is suspects that the agencies are aware of this and are watching shortest paths. So Max
has decided to use second shortest paths. Write a program to help Max find second
shortest paths. In this problem only simple paths are considered, that is, paths which visit
a vertex at most once and do not contains "cycles".
A shortest path P is a sequence of edges whose total length is less than or equal to
the total length of any other path from the start to the end. A second shortest path Q has
length less than or equal to all other paths except P. The length of Q might be equal to
that of P in which case it is more likely that Max will be caught.
Input
The standard input will contain a positive integer n and then an n by n array of nonnegative
integer values. The i,j entry is the length of an edge from vertex i to vertex j or 0
if there is no such edge. Then there will be one or more pairs S,E of start,end verticies.
All verticies will be numbers in the range 0,1,...,n-1.
Output
Your program is to print a second shortest path from S to E on one line for each such
pair. There may not be two different paths (or even one) from S to E in which case the
output should be as shown in C.out. If there is more than one shortest path any one of
them will be accepted as second shortest.
Sample Input
4
0250
0022
0001
0200
03123033
Diagram for sample input:

Sample Output
SS 0 to 3: 0 1 2 3
SS 1 to 2: none
SS 3 to 0: none
SS 3 to 3: none
Note that the second shortest path from s to f in graph G is the shortest over all paths
from s to f over all graphs which are the same as G but are missing one of the edges from
the shortest path s to f in G.

167.Problem: Hansel and Gretel


Hansel and Gretel are wandering in the woods when an evil witch gives them a bucket of
chocolate. In the bucket there is a variable number of chocolate bars, from 0 to 1000.
The bars can weigh any amount, from 1 to 1000 grams, but will always be an exact
integer value. That is, bars can weigh 1 gram, 2 grams, 3 grams, and so on, and will
never have a fractional weight such as 1.5 grams or 3.75 grams. The witch is evil
because it is very hard for Hansel and Gretel to divide the chocolate fairly, causing them
to get into very bad arguments. Your task is to help prevent Hansel and Gretel from
fighting by dividing the chocolate for them.
Input
The first line of input will contain a single integer, b, indicating the number of buckets of
chocolate you will have to divide. After this, there are b sets of data, one for each bucket.
Each set of data begins with an a single integer, n, indicating the number of chocolate
bars in the bucket. Then, the next n lines will each contain a single integer indicating the
weight of a bar of chocolate.
Output
You are two output two integers, on the same line, with a single space between them.
The first integer is the amount of chocolate that Gretel gets and the second integer is the
amount of chocolate that Hansel gets. You must ensure that the difference between
Hansels and Gretels amounts is minimal for each bucket. If the bucket can not be
divided into two even sized piles, Gretel will get the larger pile.
Example Input
2
4
2
3
4
5
3
1
1
1
Example Output
77
21

168.Problem: Party Ditches


Politics has become very nasty. In a nearby country with only 2 parties voters feel
pressured to move if they happen to live in a district where the majority votes for the
other party.
One community has the idea to dig a big ditch through the town separating the voters for
one party from those for the other. You are to write a program to determine if this is
possible using a straight line.
The input is a series of one or more test cases separated by blank lines. Each test case has
two lines of one or more integer x,y coordinate pairs. The first line gives the coordinates
of each voter for one party. The second line gives those for the voters for the other party.
Your program should print YES if it is possible to draw a straight line separating the
points on the first line on one side from those on the second line, and NO otherwise. See
file E.in for sample input and E.out for the corresponding output expected. However all
programs should use standard input/output and not any named files.
The distance of a point x,y from a line through x1,y1 and x2,y2 is:
( x*(y1-y2) + y*(x2-x1) + x1*y2 - y1*x2 ) / sqrt( (x2-x1)2 + (y2-y1)2 )
and the numerator x*(y1-y2) + y*(x2-x1) + x1*y2 - y1*x2 is:
> 0 if the shortest path from x1,y1 to x2,y2 and then to x,y involves a left turn at x2,y2
= 0 it the points are colinear
< 0 if a right turn occurs.
Sample Input
1133
2244
21615141316242635364
433332
Sample Output
NO
YES

169.Problem: Enclosing Boxes in the Plane


For various reasons it is often useful to discover information about rectangular (or
square) regions in the plane, and sometimes (as in our case) the rectangular regions
(which we will simply call "boxes") can even have integer coordinates.
A box in the plane is determined by the (integer) coordinates of its lower left and upper
right corners. If two boxes intersect (have at least one point in common), we are
interested in finding the smallest box that encloses these two intersecting boxes.
Write a program that reads in the coordinates of the lower left corner and upper right
corner of two such boxes from a single line of input and then produces a corresponding
single line of output. Thus, a sample line of input would be as follows:
11334477
As you can see, there are 8 numbers per line of input. This line of input describes two
boxes, the first with lower left corner (1,1) and upper right corner (3,3) and the second
with lower left corner (4,4) and upper right corner (7,7). Note that these two boxes do
not intersect.
If the two boxes do in fact intersect, the output line looks like this:
1. Enclosing box: (1,2) (7,8)
in which the number at the left is the number of the current line of input (since there may
be several lines of input) and the first pair of integers is the lower left corner of the
enclosing box, while the second pair is the upper right corner.
If the two boxes do not intersect, the single line of output looks like this:
1. Boxes do not intersect.

170.Problem: Top Secret


A technique for encoding and decoding secret message is called cipher.
The original message is called the plaintext, and the encoded message is called the ciphertext. One method for
encoding message is transposition. The plaintext is first divided into blocks of equal length. We then choose a
permutation to reorder the characters in each block. For example, if the block length is 5 and the
permutation is
35214
then the third character in each block becomes the first, the fifth becomes second, the second becomes third, the
first becomes fourth and the fourth becomes fifth. Therefore, the message
Collegiate Programming Contest
is first divided into

and then permuted into


leoClaeigt orrPgmnmaio tCgntse
Note that blanks and punctuations and not counted in any block, and should be left in their original positions. Note
that the last block should be handled differently if it does not contain the full length of characters. In the example,
the last block is est. Since it contains only 3 characters, we eliminate 4 and 5 from the permutation:

and use

3 2 1

to reorder the last block and get tse.


You are to write a program to implement this technique. The first input line contains the block length, the second
input line contains the permutation. The subsequent input lines contain messages to be encoded or decoded.
Each of these lines contains a character on column one, which can either be E for encoding or D for decoding,
and starting on column 3 is the message to be processed. Your program should continue to process each
message and print the result until the sentinel line that contains a single character Q on column 1 is read.
Sample Input
5
35214
E Collegiate Programming Contest
D leoClaeigt orrPgmnmaio tCgntse
D ACM
E Springfield, MA
Q
Sample Output
leoClaeigt orrPgmnmaio tCgntse
Collegiate Programming Contest
MCA
rnpSiilfgeA, Md

171.Problem: SumPrimes
Dr. Prime is looking for SumPrimes. SumPrimes are primes whose sum of digits is also prime. For example,
11 is a SumPrime because
1 + 1 = 2, which is prime
Your program will identify and print all the SumPrimes in a given range along with the sum of their digits.
Your program will be given one line of input containing a minimum and maximum value (inclusive) of a range to
search. Minimum and maximum have the following constraints: 2 <= minimum <= 1000, 2 <= maximum <=
1000, minimum <= maximum.
Then, in increasing order, one per line, print each SumPrime and its sum separated by a single space.
Sample Input
2 20
Sample Output
22
33
55
77
11 2

172.Problem: Grand Central


The streets of a city are laid out in a grid, where all blocks are the same length. The city plans to build a new fire
station, and is in the process of deciding on the best location for the station. The city has identified a set of
intersections that must be protected and are the only valid locations for the new station. To minimize the response
time to these key intersections, the city wants the station to have the most central location with respect to the
other intersections in the set.
The distance between two intersections is defined as the shortest distance along the city streets, that is, the
shortest number of city blocks traveled between the two intersections. For a given intersection X, the
eccentricity of X is the distance to the furthest intersection in the set from X. To find the most central location(s)
among the given intersections, you must find which intersection(s) have the smallest eccentricity.
For example, suppose you are given the set of locations:
(4, 0) (0, 1) (3, 1) (6, 1) (2, 2) (3, 4) (5, 4) (4, 5) (2, 6)
The distance between (3, 1) and (2, 6) is 6 (traveling 5 blocks south and 1 block west). The eccentricity of (4, 0) is
8 since the intersection located at (2, 6) is furthest away with a distance of 8.

The most centrally located of the given intersections is (2, 2), with an eccentricity of 5.
The maximum size of the city grid is 100 100. The first line of the input contains the number N of intersections (2
N 50). The next N lines each contain the integer X and Y coordinates of a location, separated by a single
space (0 X 100 and 0 Y 100).
For the output, list all of the most centrally located intersections (that is, list all intersections with minimum
eccentricity). The locations must be output in ascending sorted order (sorted first by
X, then by Y).
Sample Input
9
40
01
31
61
22

34
54
45
26
Sample Output
22

173.Problem: Kakuros Little Helper


A Kakuro puzzle is composed of overlapping sequences of boxes and a clue associated with each sequence,
much like a crossword puzzle.
However, the clues are numbers. To solve a Kakuro, one fills each sequence with values from 1 to 9, without
duplicates, such that they sum to the clue value for the sequence.
To help determine the difficulty of a puzzle, we want a program that, given the number of boxes in a sequence the
clue value for that sequence, determines the number of possible solutions for that sequence.
For example, suppose we are given a sequence of 3 boxes and a clue value of 7. There are 6 possible solutions.
124
142
214
241
412
421
On one line, separated by a space, your program will be given a sequence length N (2 <= N <= 9) and a clue
value M (2 <= M <= 45).
Your program will then print the number of solutions for that sequence.
Sample Input
37
Sample Output
6

174.Problem: Map Fill Puzzle


Your program will be given several Map Fill Puzzles. A Map Fill Puzzle is comprised of a matrix of characters. A
group of cells connected horizontally and vertically that contain the same character (A-Z, 0, 1, -, and #) form a
region. Your goal is to fill each letter-labeled region (A-Z) with one of four symbols (0, 1, -, or #). The only rule is
that adjacent regions cannot be filled with the same symbol (otherwise we couldnt tell them apart).
Input consists of a series of maps to be filled. The first line of a map specification gives the maps height and width
(both less than 100). Subsequent lines contain the map itself. The series of maps is
terminated by a map whose height and width are 0.
Output will be each filled map, with a blank line between each map.
You may assume that each map, except the terminating map has o at least 4 regions, o no more than 36 regions,
o and a unique solution.
Sample Input
38
AAABBBBB
A0001--B
11111DDD
s4 8
-AA00BBCCCCBBEE
DD1CCCCE
DDDD-EEE
00
Sample Output
---#####
-0001--#
11111000
-110011####1100
001####0
0000-000

175.Problem: Dells Kriss Kross Puzzle


A Kriss Kross puzzle is like a crossword puzzle, but instead of clues and locations for words, you are given all the
words but none of their locations. Given a puzzle and a list of words, your program must determine the correct
placement of each word in the puzzle.
Each word must be used exactly once. Words are filled into blanks as they are in crossword puzzles: across left to
right, or down.
The first line of input gives the width (1 <= width <= 50) and height (1 <= height <= 100) of the puzzle. The
subsequent lines contain a matrix of hyphen and pound-sign characters. 2 or more horizontally or vertically
adjacent pound signs forms a blank in the puzzle that must be filled by a word. The next line after the matrix
contains the number of words (1 <= number of words <= 100). Each of the following lines each contains one word.
Print the correctly filled matrix.
Sample Input
22 17
######--######--######
-#---#---#---#---#---#
-#--######--######---#
-#---#---#---#---#####
#####-#####-#---#----#
--#-#-#---#####-######
#-#-#-#-#-#-#---#---##-#-#####-#-#---######
####-#--#--######---##----#--#--#--#---####
#-#--#-######-#---#--#####--#---#-######--#
--#--#-#-#-#---#--#--#
#-#--######--#-#-#####
####-#-#-#--######---#
#----#---#---#---#---#
######--######--######
53
stay
smash
either
ache
stoa
spats
etched
aria
stair
gather
both
stirs
mother
audio
cash
bantu
tahoe
rather
dews
block
teach
remain
each
cheer
there

scathe
echo
churl
tread
school
ecru
wrath
sharon
erect
erne
ether
sheath
shiver
acumen
hitch
hunt
luck
ketch
bleach
shunts
swathe
choose
match
math
rare
ocala
drover
tether
Sample Output
swathe--school--choose
-r---a---h---u---u---i
-a--scathe--acumen---t
-t---h---e---k---teach
there-stirs-c---s----e
--t-c-t---tahoe-mother
s-h-h-o-m-a-u---a---rhe-ocala-y-r---shiver
ecru-a--t--bleach---ca---s--c--l--c---both
t-s--h-sharon-h---a--hitch--p---c-remain--d
--a--t-a-k-k---a--t--r
e-i--rather--d-t-audio
rare-e-s-t--tether---v
n----a---c---w---i---e
etched--shuntsgather

176.Problem : Insiders

ACM TEAM SELECTION


177.Problem: The ACM team Selection
The ACM-ICPC brings together the top student programmers from all over the world, and provides
them with opportunities to develop critical skills which will give them a competitive edge
when they launch careers in information technology areas. More than 5,600 teams from 84
countries had competed in regional contests last year. An ever larger number of teams - more
than 7,000 teams from different countries worldwide - have registered in this years regional
contests. However, due to the limited capacity of each site, only a small amount of the registered
teams can be allowed to participate in the on-site contest. It is really hard for the contest
organizers to determine which teams should be allowed to participate. One of the possible solutions
is to hold a preliminary internet contest before the on-site competition. The following
part describes a simplified version of rules for team selection:
Up to three teams from each school can participate in the on-site contest, depending on how
many following conditions the school in question meets:
a) A team from this school has solved at least M problems in the preliminary contest;
b) Some of the teams from this school ranked top 20 in previous World Finals;
c) This school has hosted a provincial contest this year.
Your task is to write a program to help the contest holders to calculate how many teams are
allowed to participate in the on-site final contest.

Input
There are multiple test cases in the input file. Each test case starts with three integers S, T and
M (1 S 100; 1 T 2000; 0 M 10), representing the number of schools, the number
of teams participating in the preliminary contest, and the minimum number of problems which
is required to be solved in order to enter the on-site competition, respectively.
Each of the following S lines consists of three integers Id, P and Q, (1 Id S; 0 P;Q 1),
representing the Id of the school, whether this school satisfies condition b), and whether this
school satisfies condition c).
The last part of each test case consists of T lines. There are two integers on each of the T lines,
Sid and Tot (1 Sid S; 0 Tot 10), meaning that a team from school Sid had solved Tot
problems in the preliminary contest.
Two consecutive test cases are separated by a blank line. S = 0; T = 0;M = 0 indicates the end
of input and should not be processed by your program.

Output
For each test case, print the total number of teams which are allowed to participate in the on-site
competition on a separate line in the format as indicated in the sample output.

Sample Input
586
501
400
100
311
211
26
33
29
57
48
36
28
16
586

301
511
201
111
410
57
25
45
55
33
56
20
47
000
2
Output for the Sample Input
Case 1: 10
Case 2: 9

178.Problem: Balancing the scale


You are given a strange scale (see the figure below), and you are wondering how to balance
this scale. After several attempts, you have discovered the way to balance it you need to put
different numbers on different squares while satisfying the following two equations:
x1 * 4 + x2 * 3 + x3 * 2 + x4 = x5 + x6 * 2 + x7 * 3 + x8 * 4
y1 * 4 + y2 * 3 + y3 * 2 + y4 = y5 + y6 * 2 + y7 * 3 + y8 * 4
How many ways can you balance this strange scale with the given numbers?
Input
There are multiple test cases in the input file. Each test case consists of 16 distinct numbers in the range [1, 1024]
on one separate line. You are allowed to use each number only once.
A line with one single integer 0 indicates the end of input and should not be processed by your program.

Output
For each test case, if it is possible to balance the scale in question, output one number, the number
of different ways to balance this scale, in the format as indicated in the sample output. Rotations
and reversals of the same arrangement should be counted only once.
Sample Input
87 33 98 83 67 97 44 72 91 78 46 49 64 59 85 88
0
Output Input
Case 1: 15227223

179.Problem: Contestants division


In the new ACM-ICPC Regional Contest, a special monitoring and submitting system will be set
up, and students will be able to compete at their own universities. However theres one problem.
Due to the high cost of the new judging system, the organizing committee can only afford to set
the system up such that there will be only one way to transfer information from one university
to another without passing the same university twice. The contestants will be divided into two
connected regions, and the difference between the total numbers of students from two regions
should be minimized. Can you help the juries to find the minimum difference?
Input
There are multiple test cases in the input file. Each test case starts with two integers N and M,
(1 N 100000; 1 M 1000000), the number of universities and the number of direct
communication line set up by the committee, respectively. Universities are numbered from 1 to
N. The next line has N integers; the Kth integer is equal to the number of students in university
numbered K. The number of students in any university does not exceed 100000000. Each of
the following M lines has two integers s; t, and describes a communication line connecting
university s and university t. All communication lines of this new system are bidirectional.
N = 0;M = 0 indicates the end of input and should not be processed by your program.
Output
For every test case, output one integer, the minimum absolute difference of students between
two regions in the format as indicated in the sample output.
Sample Input
761111111
12
27
37
46
62
57
00
Sample Output
Case 1: 1

180.Problem: Distance Galaxy


You are observing a distant galaxy using a telescope above the Astronomy Tower, and you think
that a rectangle drawn in that galaxy whose edges are parallel to coordinate axes and contain
maximum star systems on its edges has a great deal to do with the mysteries of universe. However
you do not have the laptop with you, thus you have written the coordinates of all star systems
down on a piece of paper and decide to work out the result later. Can you finish this task?

Input
There are multiple test cases in the input file. Each test case starts with one integer N, (1
N 100), the number of star systems on the telescope. N lines follow, each line consists of
two integers: the X and Y coordinates of the Kth planet system. The absolute value of any
coordinate is no more than 109, and you can assume that the planets are arbitrarily distributed
in the universe.
N = 0 indicates the end of input file and should not be processed by your program.
Output
For each test case, output the maximum value you have found on a single line in the format as
indicated in the sample output.
Sample Input
10 2 3
92
74
34
57
15
10 4
10 6
11 4
46
0

Sample Output
Case 1: 7

181.Problem: Scape Plan


Without turning his head, Vader snarled through his mask, The Millennium Falcon?
Piett paused a moment before replying. He would have preferred to avoid that issue. Our
tracking scanners are on it now, he responded a bit fearfully.
Vader turned to face the admiral, his towering figure looming over the frightened officer. Piett
felt a chill course through his veins, and when the Dark Lord spoke again his voice conveyed an
image of the dreadful fate that would be inflicted if his commands were not executed.
I want that ship, he hissed.
The ice planet was rapidly shrinking to a point of dim light as the Millennium Falcon sped
into space. Soon that planet seemed nothing more than one of the billions of light specks scattered
throughout the black void.
But the Falcon was not alone in its escape into deep space. Rather, it was followed by an
Imperial fleet that included the Avenger Star Destroyer and a half-dozen TIE fighter. The fighters
moved ahead of the huge, slower-moving Destroyer
, and closed in on the fleeing Millennium Falcon.
Star Wars, Episode V, the Empire Strikes Back
You are driving Millennium Falcon, the fastest starship of the entire galaxy, to escape Imperial
pursuit. There are N planet systems, numbered from 0 to N - 1, and some of them are connected
by one-way hyperspace tunnels. Some hyperspace tunnels are passable at all times, while
others are only available at certain times. Initially you are at the ice planet Hoth, the system numbered
0, at time 0 and you need to get to Sullust, the system numbered N - 1. Since there are
K Imperial Star Destroyers following you, and they will also make the jump into the hyperspace
to continue the pursuit, you have decided to use the K + 1th shortest path from Hoth to Sullust
so as to minimize the possibility of being attacked halfway by Imperial starships; furthermore, in
order to avoid detection, you do not want to risk staying at a system longer than T seconds.
Note that multiple shortest paths may require same travel time, and your travel path may not be
simple (i.e. you are allowed to visit some systems and use some hyperspace tunnels more than
once during your journey).
Input
There are multiple test cases in the input file. Each test case starts with four integers N;M;K
and T, (1 N 100, 0 M 500, 0 K 9, 0 T 100), the number of planet systems,
the number of hyperspace tunnels between them, the pursuing Imperial Star Destroyers, and
the maximal allowed time to stay at the same system, respectively. M lines follow, each line
describes one of the hyperspace tunnels: four integers U; V;C, and W, (0 U; V N - 1,
1 C 10, 1 W 1000000) meaning theres a tunnel from U to V , traveling through this
path requires W seconds and it is only available every C seconds, starting from time 0 (i.e. 0, C,
2 * C, 3 * C seconds).
Two successive inputs are separated by a blank line. N = 0, M = 0, K = 0, T = 0 indicates the
end of input and should not be processed by your program.
Output
For every test case, you should output one integer on a separate line, the total time we need to
reach Sullust in the format as indicated in the sample output; output -1 if no such path can be
found.
Sample Input
5922
1255
2466
0218
1443
3018
1 3 5 10

0444
2334
3 1 5 10
10 0 0 0
0000
Output for the Sample Input
Case 1: 28
Case 2: -1
Explanation for Sample Input / Output
The 1st shortest path in this example is 0 -> 4, with a total travel time of 4 seconds; the 2nd
shortest path is 0 (Wait 2 seconds) -> 2 (Wait 2 seconds) -> 4, with a total travel time of 18
seconds; the 3rd shortest path is 0 (Wait 2 seconds) -> 2 (Wait 2 seconds) -> 3 -> 0 -> 4, with a
total travel time of 28 seconds.

182.Problem: Permutation Recovery


Professor Permula gave a number of permutations of the n integers 1, 2, . . . , n to her students.
For each integer i, (1 i n), she asks the students to write down the number of integers greater
than i that appear before i in the given permutation. This number is denoted ai. For example,
if n = 8 and the permutation is 2, 7, 3, 5, 4, 1, 8, 6, then a1 = 5 because there are 5 numbers
(2, 7, 3, 5, 4) greater than 1 appearing before it. Similarly, a4 = 2 because there are 2 numbers
(7, 5) greater than 4 appearing before it.
John, one of the students in the class, is studying for the final exams now. He found out
that he has lost the assignment questions. He only has the answers (the ais) but not the original
permutation. Can you help him determine the original permutation, so he can review how to obtain
the answers?
Input
The input consists of a number of test cases. Each test case starts with a line containing the integer
n (n 500). The next n lines give the values of a1, a2, . . . , an. The input ends with n = 0.
Output
For each test case, print a line specifying the original permutation. Adjacent elements of a permutation
should be separated by a comma. Note that some cases may require you to print lines
containing more than 80 characters.
Example Input
8
5
0
1
2
1
2
0
0
10
9
8
7
6
5
4
3
2
1
0
0
Example Output
2,7,3,5,4,1,8,6
10,9,8,7,6,5,4,3,2,1

183.Problem: Crosswords Insider


You have an insider at the New York Times who sends you a list of the answers for the crossword
puzzle, but his list does not say which answer goes with which clue. His list occasionally
contains errors or omissions, but is usually correct. Given the list of answers and the shape of the
crossword puzzle, figure out a valid assignment.
Input
The input will consist of one or more problem sets.
Each problem set begins with a line containing two integers M and N. Zero values for these will
indicate the end of the problem sets. M denotes the number of words to be placed into the puzzle
and will be in the range 1 . . . 150. N denotes the number of rows in the puzzle and will be in the
range 1 . . . 16.
This is followed by M lines, each containing a single word, left-justified on the line. A word
will contain only alphabetic characters and words will not be duplicated within any problem set.
Words will be 2 . . . 16 characters in length.
This is followed by N lines denoting a puzzle template as a series of . and # characters,
left-justified and followed immediately by the end of line. Each line will contain the same number
of these characters. That number may range from 1 . . . 16. A . indicates a position in the puzzle
where a character may be written. A # indicates a position at which a character may not appear.
Output
Your program should determine if all the given words can be arranged into the puzzle template in
such a way as to leave no . positions unfilled and without filling any # positions. Vertical and
horizontal words may intersect at a common letter, but two horizontal or two vertical words may
neither intersect nor be adjacent to one another without at least one intervening #.
Your program should print the string Problem followed by the problem set number. If no
solution is possible, it should then print, on the remainder of that output line, the string : No
layout is possible..
If a solution is possible, then the program should, beginning on the next line after the problem
set number, print the N lines of the crossword puzzle as presented in the input but with the
appropriate characters substituted for the . positions.
If multiple solutions are possible, you may print any solution.
Example Input
44
tow
cat
row
care
...
.#.
...
.##
00
Example Output
Problem 1
cat
a#o
row
e##
Problem 2: no layout is possible.

184.Problem: Doors and Penguins


The organizers of the Annual Computing Meeting have invited a number of vendors to set
up booths in a large exhibition hall during the meeting to showcase their latest products. As the
vendors set up their booths at their assigned locations, they discovered that the organizers did not
take into account an important fact each vendor supports either the Doors operating system or
the Penguin operating system, but not both. A vendor supporting one operating system does not
want a booth next to one supporting another operating system.
Unfortunately the booths have already been assigned and even set up. There is no time to
reassign the booths or have them moved. To make matter worse, these vendors in fact do not even
want to be in the same room with vendors supporting a different operating system.
Luckily, the organizers found some portable partition screens to build a wall that can separate
the two groups of vendors. They have enough material to build a wall of any length. The screens
can only be used to build a straight wall. The organizers need your help to determine if it is possible
to separate the two groups of vendors by a single straight wall built from the portable screens. The
wall built must not touch any vendor booth (but it may be arbitrarily close to touching a booth).
This will hopefully prevent one of the vendors from knocking the wall over accidentally.
Input
The input consists of a number of cases. Each case starts with 2 integers on a line separated by a single
space: D and P, the number of vendors supporting the Doors and Penguins operating system,
respectively (1 D, P 500). The next D lines specify the locations of the vendors supporting
Doors. This is followed by P lines specifying the locations of the vendors supporting Penguins.
The location of each vendor is specified by four positive integers: x1, y1, x2, y2. (x1, y1) specifies
the coordinates of the southwest corner of the booth while (x2, y2) specifies the coordinates of the
northeast corner. The coordinates satisfy x1 < x2 and y1 < y2. All booths are rectangular and
have sides parallel to one of the compass directions. The coordinates of the southwest corner of
the exhibition hall is (0, 0) and the coordinates of the northeast corner is (15000, 15000). You may
assume that all vendor booths are completely inside the exhibition hall and do not touch the walls
of the hall. The booths do not overlap or touch each other.
The end of input is indicated by D = P = 0.
Output
For each case, print the case number (starting from 1), followed by a colon and a space. Next, print
the sentence:
It is possible to separate the two groups of vendors.
if it is possible to do so. Otherwise, print the sentence:
It is not possible to separate the two groups of vendors.
Print a blank line between consecutive cases.
Example Input
33
10 40 20 50
50 80 60 90
30 60 40 70
30 30 40 40
50 50 60 60
10 10 20 20
21
10 10 20 20
40 10 50 20
25 12 35 40
00
Example Output
Case 1: It is possible to separate the two groups of vendors.

Case 2: It is not possible to separate the two groups of vendors.

185.Problem: Gypsy Moths


The number of infestations is getting worse, said the Ranger. If we dont get those moths
under control, there wont be a healthy tree left in the whole park. Let me show you.
He spread out a map, liberally decorated with red Xs. With our remote-control camera atop
Mount Hiabove, we can easily spot the infested trees. Each mark on this map shows an infested
site.
Well, said the Park Manager, we have a congressional delegation visiting tomorrow. I dont
think theyll be impressed by a map, but if we could show them the feed from that camera as it
pans around...
Thats a problem, said the Ranger. The temperature on the mountain is dropping. By the
time they get here, the camera will probably be frozen in place. We better not assume well be able
to move the camera. And, remember, it doesnt have a very wide field of view. It only shows a
rather narrow angle.
Well have to do the best we can, said the Manager. Lets point the camera right now in the
direction that will show the most infested trees. Lets see. . . . He began to study the map.
Input
Input consists of one or more data sets.
In each data set, line 1 contains the non-negative number N of infested trees. A value of 0
indicates end of input.
For each data set, line 2 contains the X,Y coordinates of the camera and the field of view of the
camera. Lines 3 . . .N +2 each contain the X,Y coordinates of an infested tree. None of these will
be the same as the coordinates of the camera;
Coordinates are given as floating point numbers in the range 500.0 . . . 500.0. The field of
view is given as a floating-point angle, in degrees, in the range 0.1 . . . 179.9.
Output
Determine the angle A that maximizes the number of infested trees visible within the angular range
A V/2 where V is the angular field of view of the camera. The camera positioning system is
calibrated in tenths of a degree and clicks into place at each tenth of a degree intermediate
values are not possible. A tree is considered visible if it lies inside the A V/2 - trees that lie
exactly on the border are not considered visible.
The angle 0.0 corresponds to the positive Y axis and the angle 90.0 corresponds to the positive
X axis. Assume that distance is not a factor in the visibility of trees.
If more than one angle allows viewing of the same maximal number of infestations, choose the
smallest such angle.
For each input set, produce a single line of output of the form:
Point the camera at angle ### to view ## infested trees.
The angle should be printed in degrees in the range 0.0 . . . 359.9 with one digit after the decimal.
The number of visible infested trees should be printed as an integer.
Example Input
5
25.0 25.0 45.0
25.5 35.0
35.0 30.0
45.0 45.0
40.0 48.5
20.0 18.0
0
Example Output
Point the camera at angle 22.6 to view 3 infested trees.

186.Problem: Marbles in Three Baskets


Each of three baskets contains a certain number of marbles. You may move from one basket
into another basket as many marbles as are already there, thus doubling the quantity in the basket
that received the marbles. You must find a sequence of moves that will yield the same number of
marbles in the three baskets. Moreover, you must achieve the goal in the smallest possible number
of moves. Your program must also recognize the case in which there is no such sequence of moves.
Input
Each line of the input file will contain data for one instance of the problem: three positive integers,
with one blank space separating adjacent integers. The three integers represent the initial numbers
of marbles in the three baskets. The sum of the three integers will be at most 60.
End of input will be signaled by a line with three zeros.
Output
The output will begin with the initial configuration from the input.
Thereafter, on successive lines, the number of marbles in the respective baskets will be printed
after each move, concluding with the line in which the three numbers are identical. As stated
above, the goal must be achieved in the smallest possible number of moves. If there is more than
one sequence of moves that can achieve the goal in the same minimal number of steps, any such
sequence may be printed.
If there is no sequence of moves to achieve the goal, only the initial configuration will be
printed.
In all the above lines of output, each integer in the output will be right-justified in a field of
width 4.
Each instance of the problem will be concluded by a line of 12 equal signs.
Example Input
6 7 11
15 18 3
567
000
Example Output
6 7 11
6 14 4
12 8 4
888
============
15 18 3
12 18 6
12 12 12
============
567
============
000
============

187.Problem: Generic Units Conversion


Design a program that can read a description of two systems of measurement for some common
quantity (e.g., length, weight, area, time, etc.), a conversion rule that relates the two systems to one
another, and a quantity expressed in one measurement system, and that can express that same
quantity in the other system.
Input
The input will consist of 1 or more problem sets. Each problem set consists of specifications for
two systems of measurement, a conversion rule, and a set of quantities to be converted.
Each problem set begins with a specification of the first system of measurement.
The first line of this specification gives the unit names for the system, presented as a set of one
or more words on a single line, separated by single blanks. This line will be at most 80 characters
long. Each word on that line names a single unit of measurement and is made up entirely of
alphabetic characters. The order of the words will be from the largest unit to the smallest within
that system of measurement, and no unit name will be repeated within this line.
This is followed by N 1 lines (where N is the number of units named on the first line) giving
internal conversion rules in the form
### unit1 = ### unit2
where the ### are positive integer or floating point numbers and unit1 and unit2 are unit
names drawn from the first line of the specification. This set of N 1 lines will be well-formed
in the sense of providing enough information to convert any unit in the system into an appropriate
value in any other unit.
The first system specification is followed immediately by a second, in the same format.
The second specification is followed by a conversion rule, in the same format as the internal
conversion rule described above, but unit1 will be drawn from the first system of measurement
and unit2 from the second.
The conversion rule is followed by one or more lines, each line giving a quantity in the first
system. A quantity is expressed as one or more pairs, each pair consisting of a non-negative number
followed by a unit name. Unit names in a quantity will be presented in descending order of size,
though not all units in the system will necessarily be mentioned in every quantity.
All specification rules, conversion rules, and quantities will be restricted to ranges for which
the desired output (see below) can be contained in normal (not long) integers.
The end of the list of quantities, and the end of that problem set, is indicated by a completely
empty line.
If the next line after that empty one is non-empty, it represents the start of another problem set.
If that next line is also empty, however, that indicates the end of the input to this program.
Output
For each input quantity, print a single line giving the equivalent quantity in the second system of
measurement. The output will be presented as a series of pairs, each pair a number and a unit
name, with all units in the system included (even if the corresponding number for that unit is zero).
The pairs must be presented in decreasing order by unit size and should maximize the value of the
larger units over the smaller. All numbers will be integers, and the number for the smallest unit
will be rounded to the nearest integral value. Within the output line, numbers and unit names shall
be separated from one another by a single space.
Example Input
miles yards feet
5280 feet = 1 miles
3 feet = 1 yards
km m cm
1000 m = 1 km
0.01 m = 1 cm
1 feet = 30.48 cm
2 miles 1 feet
0.0833 feet

furlongs fathoms
1 furlongs = 110 fathoms
feet inches
12 inches = 1 feet
1 fathoms = 6 feet
1 furlongs
0.5 furlongs 0.25 fathoms
Example Output
3 km 218 m 99 cm
0 km 0 m 3 cm
660 feet 0 inches
331 feet 6 inches

188.Problem: Zoned Out


You want to build an office building in our town? Wonderful! Were so glad to have you! The
mayor was beaming as he led me back into City Hall. We just need to make sure your building
permit application meets all the town zoning regulations. We can check that immediately.
He led me through a door labelled Zoning. I was staggered by the sight of a huge room with
row after row of desks. At each desk sat a clerk with a logbook, an inbox, and a generaous supply
of pencils and erasers.
The mayor took my application form, then flourished a sheet of paper containing several lines
of numbered boxes. He placed the paper in the inbox of the nearest desk and said, We just run
this past our zoning clerks, and if it gets back to this desk with all the boxes checked, then your
application is approved. The clerk at the desk grabbed the form from the inbox, marked checks in
a few boxes, wrote a few lines into a logbook on his desk, then ran to a nearby copier, made copies
of the form and distributed to several other desks. I watched as the clerks at those other desks each
added more checks but also erased some, wrote in their logbooks, made copies, and distributed the
altered forms. Soon copies of the form seemed to be flying all around the room.
I turned to the mayor and said, But none of them actually looked at my application!.
Oh no, said the Mayor, each of our clerks has carefully studied a few parts of our zoning
regulations. Some are convinced that any application will automatically satisfy some of the zoning
rules. They also believe that no application will ever satisfy some of the other rules. So each clerk
simply checks off some boxes and erases the check marks from some others.
Were very proud, he added, of the decisive nature of our zoning process. We recruit our
staff from the nearby law school and choose only the most officious and argumentative junior
students.
How, I asked, do they decide where the marked-up copies should go?
Im not really sure, said the mayor. I think they mainly give them to their fellow clerks that
they most dislike, trying to increase the workload of their enemies. Just then a sheet of paper was
placed on the closest desk. Lets see how youre coming along, he said, picking up the paper.
No, still four boxes left empty. Well just have to wait and see if you can do better.
I sighed and said, It seems to me that this could go on forever.
No, said the mayor. Each clerk keeps a logbook recording all the versions of your application
that they have sent on. When they get a form, they start by adding all marks they have
ever seen on prior versions of the form, then do their own marks and erasures. If, after all that, it
matches one of the previous versions, they wont send it on a second time.
I resigned myself to a long wait.
Input
The input consists of one or more problem sets.
The first line in each set contains the number of boxes on the form and the number of clerks in
the office. Both are positive integers. The end of input is signalled by a line with zeros for both of
these numbers.
The remainder of the input consists of three lines of data for each clerk, starting with clerk #0.
(Boxes and clerks are both identified by number, starting at 0.) Each line will contain 0 or more
integers, separated by whitespace, as follows:
One line contains the numbers of the boxes that always marked by that clerk.
The next line contains the numbers of the boxes that are always erased by that clerk.
The third line contains the numbers of all those clerks to whom this one sends copies of the
altered form.
Output
For each problem set, print a single line containing the numbers of the boxes marked on the last
copy of the form that leaves the desk of clerk #0. The numbers should be printed in ascending
order, separated by a single blank space.
Example Input
65

1
12
23
4
4
5
1
3
2
1
4
2
10
00
Example Output
1345

189.Problem: Shrew-ology
Dr. Montgomery Moreau has been observing a population of Northern Madagascar Pie-bald
Shrews in the wild for many years. He has made careful observations of all the shrews in the area,
noting their distinctive physical characteristics and naming each one.
He has made a list of significant physical characteristics (e.g., brown fur, red eyes, white feet,
prominent incisor teeth, etc.) and taken note of which if these appear to be dominant (if either
parent has this characteristic, their children will have it) or recessive (the children have this characteristic only if
both parents have it).
Unfortunately, his funding from the International Zoological Institute expired and he was
forced to leave the area for several months until he could obtain a new grant. During that time
a new generation was born and began to mature. Upon returning, Dr. Moreau hopes to resume his
work, starting by determining the likely parentage of the each member of the new generation.
Input
The first line of input will containing a sequence of 1 to 80 consecutive D and R characters
describing a list of physical characteristics, indicating whether each is dominant or recessive.
After this line will follow several lines, each describing a single adult shrew. Each shrew is
described by a name of 1-32 non-blank characters terminated by a blank space, then a single M
or F character indicating the gender of the animal, another blank space, then a list of consecutive
0 or 1 characters, describing the animal. A 1 indicates that the animal possesses that physical
characteristic, a 0 indicates that it does not. The list of adults is terminated by a line containing
only the string ***.
This is followed by one or more lines describing juvenile animals. These contain a name and
description, each formatted identically to those for the adults, separated by a blank space. The list
of juveniles is terminated by a line containing only the string ***.
Output
For each juvenile animal, print a single line consisting of the animals name, the string by , then
a (possibly empty) list of all possible parents for that animal. A set of parents should be printed
as the name of the mother, a hyphen, then the name of the father. If the animal has multiple pairs
of possible parents, these pairs should be printed in alphabetic (lexicographic) order first by the
mothers name, then by the fathers name among pairs where the mother is the same. Each pair
should be printed separated by the string or .
Example Input
RDDR
Speedy M 0101
Jumper F 0101
Slowpoke M 1101
Terror F 1100
Shadow F 1001
***
Frisky 0101
Sleepy 1101
***
Example Output
Frisky by Jumper-Slowpoke or Jumper-Speedy or Shadow-Speedy
Sleepy by Shadow-Slowpoke

190.Problem: ASCII Art


ASCII art is an art of creating pictures with a grid of ASCII characters. There are many styles of ASCII
art, but we are interested in the most primitive one, where just an overall character density is used to
represent differently shaded areas of the picture.
You should write a proof-of-concept program that renders a filled closed polygon with a rectangular grid
of ASCII characters. The whole process is explained in detail below.
Let OXY be a Cartesian coordinate system with OX pointing to the right and OY pointing up. Drawing
canvas is bounded with (0; 0) (w; h) rectangle. Pixels on the canvas are (x; y) (x + 1; y + 1) squares
where x and y are integers such that 0 x < w and 0 y < h. A filled closed polygon without selfintersections
and self-touchings (but not necessarily convex) is drawn on the canvas. Pixels of the canvas
become partially filled during the process. Each pixel is represented by an ASCII character depending
on the percentage of its filled area according to the following table:

The resulting ASCII characters for all pixels are printed top-to-bottom and left-to-right to get a visual
representation of the drawing.

Input
The first line of the input file contains integers n, w, and h (3 n 100, 1 w; h 100) number
of vertices in the polygon, width and height of the canvas respectively. The following n lines contain
coordinates of the polygon vertices in clockwise order. Point i is described by two integers xi and yi
(0 xi w, 0 yi h).
Output
Write to the output file h lines with w ASCII characters each that represent ASCII art drawing of the
given polygon.
Sample input
687
76
10
17
55
24
23
Sample output

.$+.....
.##$+...
.#$oo+..
.#+$o...
.##o....
.#o.....
.o......

191.Problem: Billing Tables


In the world of telecommunications phone calls to different phone numbers have to be charged using
different rate or different billing plan. International Carrier of Phone Communications (ICPC) has an
antique billing table that determines which phone call has to be charged using which billing plan.
Each international phone number has 11 digits. The billing table has n lines. Each line specifies a range of
prefixes of phone numbers like 7919 - 921. This specification means that all phone numbers starting from 7919,
7920, and 7921 match this line. A billing plan name is specified for each prefix. To determine a billing plan for a
call, the table is scanned from top to bottom and the first matching line determines the billing plan. If no match is
found, the phone number is invalid and no billing plan is needed. A special billing plan named invalid (without
quotes) is used as an alternative way to define invalid phone numbers. Some billing plans are used for quite
differently looking phone numbers and their names may be specified on different lines in different places of the
table.
ICPCs billing table is old and contains many entries. Some of those entries may not be even used
anymore. It is very hard to figure out which phone numbers each billing plan is actually used for. The
ICPCs management has reached a decision to transform this billing table into a more legible format. In
this new format table consists of the lexicographically ordered list of simple prefixes (without the -
range feature of the old format) with a billing plan name for each prefix. No prefix of this new billing
table should be a prefix of any other prefix from the table. Thus, a simple dictionary lookup (binary
search, for example) will be sufficient to figure out a billing plan for a given phone number. Finding all
phone numbers for a given billing plan will also become quite a simple task. The number of lines in the
new billing table should be minimized. Billing plan named invalid should not be present in the new
billing table at all, since invalid phone numbers will be denoted by absence of the corresponding prefix
in the new billing table.
Input
The first line of the input file contains a single integer number n (1 n 100) the number of lines
in the old billing table. The following n lines describe the old billing table with one rule on a line. Each
rule contains four tokens separated by spaces prefix A, minus sign (-), prefix B, and billing plan
name. Prefixes contain from 1 to 11 digits each, and the billing plan name contains from 1 to 20 lower
case letters.
Further, let us denote with |A| the number of digits in the prefix A. It is true that 1 |B| |A| 11.
Moreover, last |B| digits of prefix A form a string that is lexicographically equal or precedes B.
Such pair of prefixes A and B matches all phone numbers with the first |A| - |B| digits matching the
first digits of A and with the following |B| digits being lexicographically between the last |B| digits of A
and B (inclusive).
Output
Write to the output file a single integer number k the minimal number of lines that the new table
should contain to describe the given old billing table. Then write k lines with the lexicographically
ordered new billing table. Write two tokens separated by a space on each line the prefix and the
billing plan name. Note, that the prefix in the new billing table shall contain at least one digit.
If all phone numbers are invalid (every phone number has no matching line or matches line with billing
plan invalid) then the output file should contain just number zero.
Sample Input
8
7919 - 921 cell
7921800 - 999 priv
1 - 1 usa
760 - 9 rsv
7928 - 29 rsv
7600 - 7899 spec
73 - 77 invalid
6- 7 cis

Sample Output
35
1 usa
70 cis
71 cis
72 cis
76 rsv
77 spec
78 spec
790 cis
7910 cis
7911 cis
7912 cis
7913 cis
7914 cis
7915 cis
7916 cis
7917 cis
7918 cis
7919 cell
7920 cell
7921 cell
7922 cis
7923 cis
7924 cis
7925 cis
7926 cis
7927 cis
7928 rsv
7929 rsv
793 cis
794 cis
795 cis
796 cis
797 cis
798 cis
799 cis

192.Problem: Cellular Automaton


A cellular automaton is a collection of cells on a grid of specified shape that evolves through a number
of discrete time steps according to a set of rules that describe the new state of a cell based on the states of
neighboring cells. The order of the cellular automaton is the number of cells it contains. Cells of the automaton of
order n are numbered from 1 to n.
The order of the cell is the number of different values it may contain. Usually, values of a cell of order
m are considered to be integer numbers from 0 to m - 1.
One of the most fundamental properties of a cellular automaton is the type of grid on which it is computed.
In this problem we examine the special kind of cellular automaton circular cellular automaton of order n with
cells of order m. We will denote such kind of cellular automaton as n,m-automaton.
A distance between cells i and j in n,m-automaton is defined as min(|i j |; n | i j |). A d-environment
of a cell is the set of cells at a distance not greater than d.
On each d-step values of all cells are simultaneously replaced by new values. The new value of cell i after d-step
is computed as a sum of values of cells belonging to the d-enviroment of the cell i modulo m.
The following picture shows 1-step of the 5,3-automaton.

The problem is to calculate the state of the n,m-automaton after k d-steps.


Input
The first line of the input file contains four integer numbers n, m, d, and k (1 n 500,
1 m 1 000 000, 0 d < n/2 , 1 k 10 000 000). The second line contains n integer numbers
from 0 to m - 1 ( initial values of the automatons cells).
Output
Output the values of the n,m-automatons cells after k d-steps.
Sample input
5311
12212
5 3 1 10
12212
Sample output
22221
20022

193.Problem: Driving Directions


Contrary to the popular belief, alien flying saucers cannot fly arbitrarily around our planet Earth. Their
touch down and take off maneuvers are extremely energy consuming, so they carefully plan their mission to Earth
to touch down in one particular place, then hover above the ground carrying out their mission, then take off. It was
all so easy when human civilization was in its infancy, since flying saucers can hover above all the trees and
building, and their shortest path from one mission point to the other was usually a simple straight line the most
efficient way to travel. However, modern cities have so tall skyscrapers that flying saucers cannot hover above
them and the task of navigating modern city became quite a complex one. You were hired by an alien spy to write
a piece of software that will ultimately give flying saucers driving directions throughout the city. As your first
assignment (to prove your worth to your alien masters) you should write a program that computes the shortest
distance for a flying saucer from one point to another. This program will be used by aliens as an aid in planning of
mission energy requirements.
The problem is simplified by several facts. First of all, since flying saucer can hover above most of the
buildings, you are only concerned with locations of skyscrapers. Second, the problem is actually two dimensional
you can look at everything from above and pretend that all objects are situated on
OXY Cartesian plane. Flying saucer is represented by a circle of radius r, and since modern cities with
skyscrapers tend to be regular, every skyscraper is represented with a rectangle whose sides are parallel to OX
and OY axes.
By definition, the location of flying saucer is the location of its center, and the length of the path it
travels is the length of the path its center travels. During its mission flying saucer can touch skyscrapers
but it cannot intersect them.
At the first picture a flying saucer of r = 1 has to get from point A to point B. The straight dashed
line would have been the shortest path if not for skyscraper 1. The shortest way to avoid skyscraper 1
is going around its top right corner, but skyscraper 2 is too close to fly there. Thus, the answer is to go
around the bottom left corner of skyscraper 1 for a total path length of 10:570796.
In the second picture it is impossible for a flying saucer of r = 2 to get from point A to point B, since
all skyscrapers are too close to fly in between them.
In the third picture flying saucer of r = 1 has to fly in a slalom-like way around two skyscrapers in order
to achieve the shortest path of length 11:652892 between A and B.

Input
The first line of the input file contains integer numbers r and n (1 r 100, 0 n 30), where r is
the radius of the flying saucer, and n is the number of skyscrapers. The next line contains four integer
numbers xA, yA, xB, and yB (-1000 xA, yA, xB, yB 1000), where (xA; yA) are the coordinates of
the starting point of the flying saucers mission and (xB; yB) are the coordinates of its finishing point.
The following n lines describe skyscrapers. Each skyscraper is represented by four integer numbers x1,
y1, x2, and y2 (-1000 x1, y1, x2, y2 1000, x1 < x2, y1 < y2) coordinates of the corners of the
corresponding rectangle.
Skyscrapers neither intersect nor touch each other. Starting and finishing points of the flying saucers
mission are valid locations for flying saucer, that is, it does not intersect any skyscraper in those points,
but may touch some of them.

Output
Write to the output file text no solution (without quotes) if the flying saucer cannot reach its finishing
point from the starting one. Otherwise, write to the output file a single number the shortest distance
that the flying saucer needs to travel to get from the starting point to the finishing point. Answer has to
be precise to at least 6 digits after the decimal point.
Sample input
13
2771
3264
7598
1859
24
0056
8 3 10 6
5 9 9 10
1428
3153
12
0 5 10 5
2245
6588
Sample output
10.570796
11.652892
no solution

194.Problem: Exchange
You are taking part in a large project to automate operations for Northeastern Exchange of Resources
and Commodities (NEERC). Different resources and commodities are traded on this exchange via public auction.
Each resource or commodity is traded independently of the others and your task is to write a core engine for this
exchange its order book. There is a separate instance of an order book for each traded resource or commodity
and it is not your problem to get the correct orders into order books.
The order book instance you will be writing is going to receive the appropriate orders from the rest of
exchange system.
Order book receives a stream of messages. Messages are orders and requests to cancel previously issued
orders. Orders that were not cancelled are called active. There are orders to buy and orders to sell. Each order to
buy or to sell has a positive size and a positive price. Order book maintains a list of active orders and generates
quotes and trades. Active order to buy at the highest price is the best buy order and its price is called bid price.
Active order to sell at the lowest price is the best sell order and its price is called ask price. Ask price is always
lower than bid price, that is, buyers are willing to pay less than sellers want to receive in return.
A current quote from the order book contains current bid size, bid price, ask size, and ask price. Here
bid and ask sizes are sums of the the sizes of all active orders with the current bid price and the current
ask price correspondingly.
A trade records information about transaction between buyer and seller. Each trade has size and price.
If an order to buy arrives to the order book at a price greater or equal to the current ask price, then the
corresponding orders are matched and trade happens buyer and seller reached agreement on a price.
Vice versa, if an order to sell arrives to the order book at a price less or equal to the current bid price,
then trade happens, too. For the purpose of order matching, order book works like a FIFO queue for
orders with the same price (read further for details).
When an order to buy arrives to the order book at a price greater or equal to the current ask price it is
not immediately entered into the order book. First, a number of trades is generated, possibly reducing
the size of incoming order. Trade is generated between incoming buy order and the best order to sell.
If there are multiple best orders (at the ask price), then the order that entered the order book first is
chosen. Trade is generated at the current ask price with the size of the trade being equal to the smaller
of the sizes of two matching orders. Sizes of both matching orders are reduced by the size of the trade.
If that reduces the size of sell order to zero, then it becomes inactive and is removed from the order
book. If the size of incoming buy order becomes zero, then the process is over incoming order becomes
inactive. If the size of incoming buy order is still positive and there is another sell order to match with, then the
process continues generating further trades at the new ask price (ask price can increase as sell orders are traded
against and become inactive). If there is no sell order to match with (current ask price became greater than
incoming buy order price), then incoming buy order is added to the order book with its remaining size.
For incoming sell order everything works similarly it is matched with buy orders from the order book
and trades are generated on bid price.
On incoming cancel request the corresponding order is simply removed from the order book and becomes
inactive. Note, that by the time of the cancel request the quantity of the corresponding order might have been
already partially reduced or the order might have become inactive. Requests to cancel inactive order do not
change anything in the order book.
On every incoming message the order book has to generate all trades it causes and the current quote
(bid size, bid price, ask size, ask price) after processing of the corresponding message, even when nothing has
changed in the order book as a result of this message. Thus, the number of quotes the order book generates is
always equal to the number of incoming messages.
Input
The first line of the input file contains a single integer number n (1 n 10 000) the number of
incoming messages that the order book has to process. The following n lines contain messages. Each line starts
with a word describing the message type BUY, SELL, or CANCEL followed after a space by the message
parameters.
BUY and SELL denote an order to buy or to sell correspondingly, and are followed by two integers q and p (1 q
99 999, 1 p 99 999) order size and price. CANCEL denotes a request to cancel previously issued order. It

is followed by a single integer i which is the number of the message with some preceding order to buy or to sell
(messages are numbered from 1 to n).
Output
Write to the output file a stream of quotes and trades that the incoming messages generate. For every
trade write TRADE followed after space by the trade size and price. For every quote write QUOTE followed after
space by the quote bid size, bid price, minus sign (-), ask size, ask price (all separated by spaces).
There is a special case when there are no active orders to buy or to sell in the order book (bid and/or ask are not
defined). This case is treated as follows. If there is no active order to buy, then it is assumed that bid size is zero
and bid price is zero. If there is no active order to sell, then it is assumed that ask size is zero and ask price is 99
999. Note, that zero is not a legal price, but 99 999 is a legal price. Recipient of quote messages distinguishes
actual 99 999 ask price from the special case of absent orders to sell by looking at its ask size.
See example for further clarification.
Sample input
11
BUY 100 35
CANCEL 1
BUY 100 34
SELL 150 36
SELL 300 37
SELL 100 36
BUY 100 38
CANCEL 4
CANCEL 7
BUY 200 32
SELL 500 30
Sample output
QUOTE 100 35 - 0 99999
QUOTE 0 0 - 0 99999
QUOTE 100 34 - 0 99999
QUOTE 100 34 - 150 36
QUOTE 100 34 - 150 36
QUOTE 100 34 - 250 36
TRADE 100 36
QUOTE 100 34 - 150 36
QUOTE 100 34 - 100 36
QUOTE 100 34 - 100 36
QUOTE 100 34 - 100 36
TRADE 100 34
TRADE 200 32
QUOTE 0 0 - 200 30

195.Problem: Fools Game


A card game, often called Fools Game, is quite popular in Russia. We will describe a game for two
players. A standard deck of 36 cards is used. One suit is declared to be a trump.
A game consists of rounds. Before the round each player has several cards, one of the players is starting, the
other one is covering. The starting player starts by laying one or several cards of the same rank down on the
table. The number of cards must not exceed the number of cards the covering player has. The covering player
must in turn cover all the cards with some of her cards, laying them on the table above the uncovered cards. A
card can cover another if one of the following is true:
it has the same suit and higher rank (ranks are ordered as usually: 6, 7, 8, 9, 10, J, Q, K, A);
it is a trump and the card to cover is not a trump (a trump can only be covered by a higher trump).
After the cards on the table are all covered, the starting player can toss some more cards to be covered.
The rank of each card tossed must be among the ranks of the cards already on the table at the moment.
Now the newly added cards must be covered by the covering player, after that the starting player can
toss more cards, and so on. The starting player cannot toss more cards than the covering player has at
the moment.
The round ends when either the covering player cannot or does not want to cover all uncovered cards on the
table, or when the starting player cannot or does not want to toss more cards.
In the first case, when the covering player declares that she does not want to cover all uncovered cards
on the table, the starting player is given a chance to toss in more cards. The ranks of the cards tossed
must be among the ranks of the cards already on the table. The number of uncovered cards on the table cannot
exceed the number of cards that the covering player has at the moment. After that, the covering player loses the
round and takes all the cards from the table, adding them to her cards.
Starting player
keeps her starting role and moves again in the next round.
In the second case, when all cards on the table are covered and the starting player cannot or does not
want to toss more cards, the covering player wins the round and the cards on the table are removed from the
game. The players roles for the next round are swapped: the covering player becomes the starting one and vice
versa.
If, after the end of the round, one of the players has no cards, and the other one has one or more cards,
then the player with no cards wins the game. If both players have no cards, then the player who was
starting in the last round wins the game.
Given the trump suit and the cards the players initially have, find out who wins the game if both play
optimally. Both players have full information about cards in the game.
Input
The first line of the input file contains n1 and n2 the number of cards that each of the players has in
the beginning of the round (1 n1; n2 6), and the trump suit (suit is specified using one letter: S for
spades, C for clubs, D for diamonds, H for hearts).
The second line contains n1 card descriptions the cards of the first player. Each card is specified by
its rank (6. . . 9, T for 10, J for Jack, Q for Queen, K for King, A for Ace) followed by its suit.
The third line contains n2 card descriptions the cards of the covering player. The first player is the
starting player in the first round.
All cards in players hands are different.
Output
Output FIRST if the first player wins the game, or SECOND if the second player does.
Sample input
22S
KC AD
6S 7S
22D
KC AD
6S 7S

45C
AS 6S 7S 8S
9S TS JS QS KS
32C
6H JS JD
AD 6C
Sample output
SECOND
FIRST
SECOND
FIRST

196.Problem: Graveyard
Programming contests became so popular in the year 2397 that the governor of New Earck the largest humaninhabited planet of the galaxy opened a special Alley of Contestant Memories (ACM) at the local graveyard.
The ACM encircles a green park, and holds the holographic statues of famous contestants placed equidistantly
along the park perimeter. The alley has to be renewed from time to time when a new group of memorials arrives.
When new memorials are added, the exact place for each can be selected arbitrarily along the ACM, but the
equidistant disposition must be maintained by moving some of the old statues along the alley.
Surprisingly, humans are still quite superstitious in 24th century: the graveyard keepers believe the
holograms are holding dead people souls, and thus always try to renew the ACM with minimal possible
movements of existing statues (besides, the holographic equipment is very heavy). Statues are moved
along the park perimeter. Your work is to find a renewal plan which minimizes the sum of travel distances of all
statues. Installation of a new hologram adds no distance penalty, so choose the places for newcomers wisely!
Input
Input file contains two integer numbers: n the number of holographic statues initially located at the
ACM, and m the number of statues to be added (2 n 1000; 1 m 1000). The length of the
alley along the park perimeter is exactly 10 000 feet.
Output
Write a single real number to the output file the minimal sum of travel distances of all statues (in
feet). The answer must be precise to at least 4 digits after decimal point.
Sample input
21
23
31
10 10
Sample output
1666.6667
1000.0
1666.6667
0.0

Pictures show the first three examples. Marked circles denote original statues, empty circles denote new
equidistant places, arrows denote movement plans for existing statues.

197.Problem: Hard Life


John is a Chief Executive Officer at a privately owned medium size company. The owner of the company has
decided to make his son Scott a manager in the company. John fears that the owner will ultimately give CEO
position to Scott if he does well on his new manager position, so he decided to make Scotts life as hard as
possible by carefully selecting the team he is going to manage in the company.
John knows which pairs of his people work poorly in the same team. John introduced a hardness factor
of a team it is a number of pairs of people from this team who work poorly in the same team divided
by the total number of people in the team. The larger is the hardness factor, the harder is this team to
manage. John wants to find a group of people in the company that are harderst to manage and make it
Scotts team. Please, help him.

In the example on the picture the hardest team consists of people 1, 2, 4, and 5. Among 4 of them 5
pairs work poorly in the same team, thus hardness factor is equal to 5/ 4 . If we add person number 3 to
the team then hardness factor decreases to 6/ 5 .
Input
The first line of the input file contains two integer numbers n and m (1 n 100, 0 m 1000). Here
n is a total number of people in the company (people are numbered from 1 to n), and m is the number
of pairs of people who work poorly in the same team. Next m lines describe those pairs with two integer
numbers ai and bi (1 ai; bi n, ai bi) on a line. The order of people in a pair is arbitrary and no
pair is listed twice.
Output
Write to the output file an integer number k (1 k n) the number of people in the hardest team,
followed by k lines listing people from this team in ascending order. If there are multiple teams with the
same hardness factor then write any one.
Sample input
56
15
54
42
25
12
31
40
Sample output
4
1
2
4

5
1
1
Note, that in the last example any team has hardness factor of zero, and any non-empty list of people is
a valid answer.

198.Problem: Interconnect
There are two serious problems in the Kingdom of Lipshire: the roads and the fools who build them.
Once upon a time, the King of Lipshire has decided to improve the road system because some roads
became completely impassable it was easier to travel cross-country instead of using those roads.
By Kings decree, new roads are to be built in Lipshire. Of course, the new road system must interconnect all
towns, i. e. there must be a path connecting any two towns of Lipshire.
The road administration of Lipshire has resources to build exactly one road per year. Unfortunately, the
fools who build these roads are completely out of control. So, regardless of the orders given, the fools
randomly select two different towns a and b and build a road between them, even when those towns are already
connected by a road. All possible choices are equiprobable. The road is build in such a manner that the only
points where a traveler can leave it are the towns connected by this road. The only good thing is that all roads are
bidirectional.
The King knows about the problem, but he cannot do anything about it. The only thing King needs to
know is the expected number of years to wait before the road system of Lipshire becomes interconnected.
He asked you to provide this information.
Input
The first line of the input contains two integers n and m (2 n 30, 0 m 1 000) the number of
towns in Lipshire, and the number of roads which are still good. The following m lines describe roads,
one per line. Each road is described with two endpoints two integer numbers ui and vi (1 ui; vi n,
ui vi). There can be multiple roads between two towns, but the road from a town to itself is not
allowed.
Output
Output the expected number of years to wait for the interconnected road system. If the system is already
interconnected, output zero as an answer. Output the number with at least six precise digits after the decimal
point.
Sample input
21
12
42
12
34
Sample output
0.0
1.5

199.Problem: Java vs C++


Apologists of Java and C++ can argue for hours proving each other that their programming language is
the best one. Java people will tell that their programs are clearer and less prone to errors, while C++
people will laugh at their inability to instantiate an array of generics or tell them that their programs
are slow and have long source code.
Another issue that Java and C++ people could never agree on is identifier naming. In Java a multiword
identifier is constructed in the following manner: the first word is written starting from the small letter,
and the following ones are written starting from the capital letter, no separators are used. All other
letters are small. Examples of a Java identifier are javaIdentifier, longAndMnemonicIdentifier,
name, nEERC.
Unlike them, C++ people use only small letters in their identifiers. To separate words they use underscore
character . Examples of C++ identifiers are c identifier, long and mnemonic identifier, name (you see that when
there is just one word Java and C++ people agree), n e e r c.
You are writing a translator that is intended to translate C++ programs to Java and vice versa. Of
course, identifiers in the translated program must be formatted due to its language rules otherwise
people will never like your translator.
The first thing you would like to write is an identifier translation routine. Given an identifier, it would
detect whether it is Java identifier or C++ identifier and translate it to another dialect. If it is neither,
then your routine should report an error. Translation must preserve the order of words and must only
change the case of letters and/or add/remove underscores.
Input
The input file consists of one line that contains an identifier. It consists of letters of the English alphabet
and underscores. Its length does not exceed 100.
Output
If the input identifier is Java identifier, output its C++ version. If it is C++ identifier, output its Java
version. If it is none, output Error! instead.
Sample input
Long_and_mnemonic_identifier
anotherExample
i
bad Style
Sample output
longAndMnemonicIdentifier
another example
i
Error!

200.Problem: Kickdown
A research laboratory of a world-leading automobile company has received an order to create a special
transmission mechanism, which allows for incredibly efficient kickdown an operation of switching to
lower gear. After several months of research engineers found that the most efficient solution requires
special gears with teeth and cavities placed non-uniformly. They calculated the optimal flanks of the
gears. Now they want to perform some experiments to prove their findings.
The first phase of the experiment is done with planar toothed sections, not round-shaped gears. A section of
length n consists of n units. The unit is either a cavity of height h or a tooth of height 2h. Two sections are
required for the experiment: one to emulate master gear (with teeth at the bottom) and one for the driven gear
(with teeth at the top).

There is a long stripe of width 3h in the laboratory and its length is enough for cutting two engaged
sections together. The sections are irregular but they may still be put together if shifted along each
other.

The stripe is made of an expensive alloy, so the engineers want to use as little of it as possible. You need to find
the minimal length of the stripe which is enough for cutting both sections simultaneously.
Input
There are two lines in the input file, each contains a string to describe a section. The first line describes
master section (teeth at the bottom) and the second line describes driven section (teeth at the top). Each
character in a string represents one section unit 1 for a cavity and 2 for a tooth. The sections can not be flipped
or rotated.
Each string is non-empty and its length does not exceed 100.
Output
Write a single integer number to the output file the minimal length of the stripe required to cut off
given sections.
Sample input
2112112112
2212112
12121212
21212121

2211221122
21212
Sample output
10
8
15

You might also like