Professional Documents
Culture Documents
ACM Problem Set Volume 1
ACM Problem Set Volume 1
Background
Problems in Computer Science are often classied as belonging to a certain class of problems (e.g.,
NP, Unsolvable, Recursive). In this problem you will be analyzing a property of an algorithm whose
classication is not known for all possible inputs.
The Problem
The Input
The input will consist of a series of pairs of integers i and j , one pair of integers per line. All integers
will be less than 10,000 and greater than 0.
You should process all pairs of integers and for each pair determine the maximum cycle length over
all integers between and including i and j .
The Output
For each pair of input integers i and j you should output i, j , and the maximum cycle length for integers
between and including i and j . These three numbers should be separated by at least one space with all
three numbers on one line and with one line of output for each line of input. The integers i and j must
appear in the output in the same order in which they appeared in the input and should be followed by
the maximum cycle length (on the same line).
Sample Input
1 10
100 200
201 210
900 1000
Sample Output
1 10 20
100 200 125
201 210 89
900 1000 174
101
Ba
kground
Many areas of Computer S
ien
e use simple, abstra
t domains for both analyti
al and empiri
al studies.
For example, an early AI study of planning and roboti
s (STRIPS) used a blo
k world in whi
h a robot
arm performed tasks involving the manipulation of blo
ks.
In this problem you will model a simple blo
k world under
ertain rules and
onstraints. Rather
than determine how to a
hieve a spe
ied state, you will \program" a roboti
arm to respond to a
limited set of
ommands.
The Problem
The problem is to parse a series of
ommands that instru
t a robot arm in how to manipulate blo
ks
that lie on a
at table. Initially there are n blo
ks on the table (numbered from 0 to n 1) with blo
k
bi adja
ent to blo
k bi+1 for all 0 i < n 1 as shown in the diagram below:
0
n-1
move a onto b
where a and b are blo
k numbers, puts blo
k a onto blo
k b after returning any blo
ks that are
sta
ked on top of blo
ks a and b to their initial positions.
move a over b
where a and b are blo
k numbers, puts blo
k a onto the top of the sta
k
ontaining blo
k b, after
returning any blo
ks that are sta
ked on top of blo
k a to their initial positions.
pile a onto b
where a and b are blo
k numbers, moves the pile of blo
ks
onsisting of blo
k a, and any blo
ks
that are sta
ked above blo
k a, onto blo
k b. All blo
ks on top of blo
k b are moved to their
initial positions prior to the pile taking pla
e. The blo
ks sta
ked above blo
k a retain their order
when moved.
pile a over b
where a and b are blo
k numbers, puts the pile of blo
ks
onsisting of blo
k a, and any blo
ks
that are sta
ked above blo
k a, onto the top of the sta
k
ontaining blo
k b. The blo
ks sta
ked
above blo
k a retain their original order when moved.
quit
terminates manipulations in the blo
k world.
Any
ommand in whi
h a = b or in whi
h a and b are in the same sta
k of blo
ks is an illegal
ommand. All illegal
ommands should be ignored and should have no ae
t on the
onguration of
blo
ks.
The Input
The input begins with an integer n on a line by itself representing the number of blo
ks in the blo
k
world. You may assume that 0 < n < 25.
The number of blo
ks is followed by a sequen
e of blo
k
ommands, one
ommand per line. Your
program should pro
ess all
ommands until the quit
ommand is en
ountered.
You may assume that all
ommands will be of the form spe
ied above. There will be no synta
ti
ally
in
orre
t
ommands.
The Output
The output should
onsist of the nal state of the blo
ks world. Ea
h original blo
k position numbered
i (0 i < n where n is the number of blo
ks) should appear followed immediately by a
olon. If there
is at least a blo
k on it, the
olon must be followed by one spa
e, followed by a list of blo
ks that appear
sta
ked in that position with ea
h blo
k number separated from other blo
k numbers by a spa
e. Don't
put any trailing spa
es on a line.
There should be one line of output for ea
h blo
k position (i.e., n lines of output where n is the
integer on the rst line of input).
Sample Input
10
move
move
move
move
pile
pile
move
move
quit
9
8
7
6
8
8
2
4
onto
over
over
over
over
over
over
over
1
1
1
1
6
5
1
9
Sample Output
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
0
1 9 2 4
3
5 8 7 6
Background
Bin packing, or the placement of objects of certain weights into dierent bins subject to certain constraints, is an historically interesting problem. Some bin packing problems are NP-complete but are
amenable to dynamic programming solutions or to approximately optimal heuristic solutions.
In this problem you will be solving a bin packing problem that deals with recycling glass.
The Problem
Recycling glass requires that the glass be separated by color into one of three categories: brown glass,
green glass, and clear glass. In this problem you will be given three recycling bins, each containing a
specied number of brown, green and clear bottles. In order to be recycled, the bottles will need to be
moved so that each bin contains bottles of only one color.
The problem is to minimize the number of bottles that are moved. You may assume that the only
problem is to minimize the number of movements between boxes.
For the purposes of this problem, each bin has innite capacity and the only constraint is moving
the bottles so that each bin contains bottles of a single color.
The Input
The input consists of a series of lines with each line containing 9 integers. The rst three integers on a
line represent the number of brown, green, and clear bottles (respectively) in bin number 1, the second
three represent the number of brown, green and clear bottles (respectively) in bin number 2, and the
last three integers represent the number of brown, green, and clear bottles (respectively) in bin number
3. For example, the line
10 15 20 30 12 8 15 8 31
indicates that there are 20 clear bottles in bin 1, 12 green bottles in bin 2, and 15 brown bottles in bin
3.
Integers on a line will be separated by one or more spaces. Your program should process all lines in
the input le.
The Output
For each line of input there will be one line of output indicating what color bottles go in what bin
to minimize the number of bottle movements. You should also print the minimum number of bottle
movements.
The output should consist of a string of the three upper case characters 'G', 'B', 'C' (representing
the colors green, brown, and clear) representing the color associated with each bin.
The rst character of the string represents the color associated with the rst bin, the second character
of the string represents the color associated with the second bin, and the third character represents the
color associated with the third bin.
The integer indicating the minimum number of bottle movements should follow the string.
If more than one order of brown, green, and clear bins yields the minimum number of movements
then the alphabetically rst string representing a minimal conguration should be printed.
Sample Input
1 2 3 4 5 6 7 8 9
5 10 5 20 10 5 10 20 10
Sample Output
BCG 30
CBG 50
Background
Some concepts in Mathematics and Computer Science are simple in one or two dimensions but become
more complex when extended to arbitrary dimensions. Consider solving dierential equations in several dimensions and analyzing the topology of an n-dimensional hypercube. The former is much more
complicated than its one dimensional relative while the latter bears a remarkable resemblance to its
\lower-class" cousin.
The Problem
Consider an n-dimensional \box" given by its dimensions. In two dimensions the box (2,3) might
represent a box with length 2 units and width 3 units. In three dimensions the box (4,8,9) can represent
a box 4 8 9 (length, width, and height). In 6 dimensions it is, perhaps, unclear what the box
(4,5,6,7,8,9) represents; but we can analyze properties of the box such as the sum of its dimensions.
In this problem you will analyze a property of a group of n-dimensional boxes. You are to determine
the longest nesting string of boxes, that is a sequence of boxes b1; b2; : : :; bk such that each box bi nests
in box bi+1 (1 i < k).
A box D = (d1; d2; : : :; dn) nests in a box E = (e1; e2 ; : : :; en ) if there is some rearrangement of the
di such that when rearranged each dimension is less than the corresponding dimension in box E. This
loosely corresponds to turning box D to see if it will t in box E. However, since any rearrangement
suces, box D can be contorted, not just turned (see examples below).
For example, the box D = (2,6) nests in the box E = (7,3) since D can be rearranged as (6,2) so that
each dimension is less than the corresponding dimension in E. The box D = (9,5,7,3) does NOT nest in
the box E = (2,10,6,8) since no rearrangement of D results in a box that satises the nesting property,
but F = (9,5,7,1) does nest in box E since F can be rearranged as (1,9,5,7) which nests in E.
Formally, we dene nesting as follows: box D = (d1; d2; : : :; dn) nests in box E = (e1; e2; : : :; en )
if there is a permutation of 1 : : :n such that (d(1); d(2); : : :; d(n)) \ts" in (e1; e2; : : :; en ) i.e., if
d(i) < ei for all 1 i n.
The Input
The input consists of a series of box sequences. Each box sequence begins with a line consisting of the
the number of boxes k in the sequence followed by the dimensionality of the boxes, n (on the same line.)
This line is followed by k lines, one line per box with the n measurements of each box on one line
separated by one or more spaces. The ith line in the sequence (1 i k) gives the measurements for
the ith box.
There may be several box sequences in the input le. Your program should process all of them and
determine, for each sequence, which of the k boxes determine the longest nesting string and the length
of that nesting string (the number of boxes in the string).
In this problem the maximum dimensionality is 10 and the minimum dimensionality is 1. The
maximum number of boxes in a sequence is 30.
The Output
For each box sequence in the input le, output the length of the longest nesting string on one line followed
on the next line by a list of the boxes that comprise this string in order. The \smallest" or \innermost"
box of the nesting string should be listed rst, the next box (if there is one) should be listed second, etc.
The boxes should be numbered according to the order in which they appeared in the input le (rst
box is box 1, etc.).
If there is more than one longest nesting string then any one of them can be output.
Sample Input
5 2
3 7
8 10
5 2
9 11
21 18
8 6
5 2 20 1 30 10
23 15 7 9 11 3
40 50 34 24 14 4
9 10 11 12 13 14
31 4 18 8 27 17
44 32 13 19 41 19
1 2 3 4 5 6
80 37 47 18 21 9
Sample Output
5
3 1 2 4 5
4
7 2 5 6
104 Arbitrage
Background
The use of computers in the nance industry has been marked with controversy lately as programmed
trading | designed to take advantage of extremely small
uctuations in prices | has been outlawed
at many Wall Street rms. The ethics of computer programming is a
edgling eld with many thorny
issues.
The Problem
Arbitrage is the trading of one currency for another with the hopes of taking advantage of small dier-
ences in conversion rates among several currencies in order to achieve a prot. For example, if $1.00
in U.S. currency buys 0.7 British pounds currency, $1 in British currency buys 9.5 French francs,
and 1 French franc buys 0.16 in U.S. dollars, then an arbitrage trader can start with $1.00 and earn
1 0 7 9 5 0 16 = 1 064 dollars thus earning a prot of 6.4 percent.
You will write a program that determines whether a sequence of currency exchanges can yield a
prot as described above.
To result in successful arbitrage, a sequence of exchanges must begin and end with the same currency,
but any starting currency may be considered.
:
The Input
The input le consists of one or more conversion tables. You must solve the arbitrage problem for each
of the tables in the input le.
Each table is preceded by an integer on a line by itself giving the dimensions of the table. The
maximum dimension is 20; the minimum dimension is 2.
The table then follows in row major order but with the diagonal elements of the table missing (these
are assumed to have value 1.0). Thus the rst row of the table represents the conversion rates between
country 1 and ? 1 other countries, i.e., the amount of currency of country (2 ) that can be
purchased with one unit of the currency of country 1.
Thus each table consists of + 1 lines in the input le: 1 line containing and lines representing
the conversion table.
n
The Output
For each table in the input le you must determine whether a sequence of exchanges exists that results
in a prot of more than 1 percent (0.01). If a sequence exists you must print the sequence of exchanges
that results in a prot. If there is more than one sequence that results in a prot of more than 1 percent
you must print a sequence of minimal length, i.e., one of the sequences that uses the fewest exchanges
of currencies to yield a prot.
Because the IRS (United States Internal Revenue Service) notices lengthy transaction sequences, all
proting sequences must consist of or fewer transactions where is the dimension of the table giving
conversion rates. The sequence 1 2 1 represents two conversions.
If a proting sequence exists you must print the sequence of exchanges that results in a prot. The
sequence is printed as a sequence of integers with the integer representing the th line of the conversion
table (country ). The rst integer in the sequence is the country from which the proting sequence
starts. This integer also ends the sequence.
n
should be printed.
Sample Input
3
1.2 .89
.88 5.1
1.1 0.15
4
3.1
0.0023
0.21 0.00353
200
180.559
2.11 0.089
2
2.0
0.45
0.35
8.13
10.339
0.06111
Sample Output
1 2 1
1 2 4 1
no arbitrage sequence exists
105
With the advent of high speed graphics workstations, CAD (computer-aided design) and other areas
(CAM, VLSI design) have made increasingly effective use of computers. One of the problems with
drawing images is the elimination of hidden lines lines obscured by other parts of a drawing.
You are to design a program to assist an architect in drawing the skyline of a city given the locations
of the buildings in the city. To make the problem tractable, all buildings are rectangular in shape and
they share a common bottom (the city they are built in is very flat). The city is also viewed as twodimensional. A building is specified by an ordered triple (Li , Hi , Ri ) where Li and Ri are the left and
right coordinates, respectively, of building i (0 < Li < Ri ) and Hi is the height of the building. In the
diagram below buildings are shown on the left with triples
(1, 11, 5), (2, 6, 7), (3, 13, 9), (12, 7, 16), (14, 3, 25), (19, 18, 22), (23, 13, 29), (24, 4, 28)
the skyline, shown on the right, is represented by the sequence:
(1, 11, 3, 13, 9, 0, 12, 7, 16, 3, 19, 18, 22, 3, 23, 13, 29, 0)
Input
The input is a sequence of building triples. All coordinates of buildings are integers less than 10,000
and there will be at least one and at most 5,000 buildings in the input file. Each building triple is
on a line by itself in the input file. All integers in a triple are separated by one or more spaces. The
triples will be sorted by Li , the left x-coordinate of the building, so the building with the smallest left
x-coordinate is first in the input file.
Output
The output should consist of the vector that describes the skyline as shown in the example above. In the
skyline vector (v1 , v2 , v3 , . . . , vn2 , vn1 , vn ), the vi such that i is an even number represent a horizontal
line (height). The vi such that i is an odd number represent a vertical line (x-coordinate). The skyline
vector should represent the path taken, for example, by a bug starting at the minimum x-coordinate
and traveling horizontally and vertically over all the lines that define the skyline. Thus the last entry
in all skyline vectors will be a 0.
Sample Input
1 11 5
2 6 7
3 13 9
12 7 16
14 3 25
19 18 22
23 13 29
24 4 28
Sample Output
1 11 3 13 9 0 12 7 16 3 19 18 22 3 23 13 29 0
2/2
Computer generated and assisted proofs and verication occupy a small niche in the realm of Computer
Science. The rst proof of the four-color problem was completed with the assistance of a computer
program and current eorts in verication have succeeded in verifying the translation of high-level code
down to the chip level.
This problem deals with computing quantities relating to part of Fermat's Last Theorem: that there
are no integer solutions of an + bn = cn for n > 2.
The Problem
Given a positive integer N , you are to write a program that computes two quantities regarding the
solution of
2
2
2
x +y = z
where x, y , and z are constrained to be positive integers less than or equal to N . You are to compute
the number of triples (x; y; z ) such that x, y , and z are relatively prime, i.e., have no common divisor
larger than 1. You are also to compute the number of values 0 < p N such that p is not part of any
triple (not just relatively prime triples).
The Input
The input consists of a sequence of positive integers, one per line. Each integer in the input le will be
less than or equal to 1,000. Input is terminated by end-of-le.
The Output
For each integer N in the input le print two integers separated by a space. The rst integer is the
number of relatively prime triples (such that each component of the triple is N ). The second number
is the number of positive integers N that are not part of any triple whose components are all N .
There should be one output line for each input line.
Sample Input
10
25
100
Sample Output
1 4
4 9
16 27
Background
The Problem
A clever cat walks into a messy room which he needs to clean. Instead of doing the work alone, it decides
to have its helper cats do the work. It keeps its (smaller) helper cats inside its hat. Each helper cat also
has helper cats in its own hat, and so on. Eventually, the cats reach a smallest size. These smallest cats
have no additional cats in their hats. These unfortunate smallest cats have to do the cleaning.
The number of cats inside each (non-smallest) cat's hat is a constant, N . The height of these
cats-in-a-hat is N 1+1 times the height of the cat whose hat they are in.
The smallest cats are of height one;
these are the cats that get the work done.
All heights are positive integers.
Given the height of the initial cat and the number of worker cats (of height one), nd the number
of cats that are not doing any work (cats of height greater than one) and also determine the sum of all
the cats' heights (the height of a stack of all cats standing one on top of another).
The Input
The input consists of a sequence of cat-in-hat specications. Each specication is a single line consisting
of two positive integers, separated by white space. The rst integer is the height of the initial cat, and
the second integer is the number of worker cats.
A pair of 0's on a line indicates the end of input.
The Output
For each input line (cat-in-hat specication), print the number of cats that are not working, followed by
a space, followed by the height of the stack of cats. There should be one output line for each input line
other than the \0 0" that terminates input.
Sample Input
216 125
5764801 1679616
0 0
Sample Output
31 671
335923 30275911
Background
A problem that is simple to solve in one dimension is often much more dicult to solve in more than one
dimension. Consider satisfying a boolean expression in conjunctive normal form in which each conjunct
consists of exactly 3 disjuncts. This problem (3-SAT) is NP-complete. The problem 2-SAT is solved
quite eciently, however. In contrast, some problems belong to the same complexity class regardless of
the dimensionality of the problem.
The Problem
Given a 2-dimensional array of positive and negative integers, nd the sub-rectangle with the largest
sum. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the
sub-rectangle with the largest sum is referred to as the maximal sub-rectangle. A sub-rectangle is any
contiguous sub-array of size 1 1 or greater located within the whole array. As an example, the maximal
sub-rectangle of the array:
0 ?2 ?7 0
9 2 ?6 2
?4 1 ?4 1
?1 8 0 ?2
9 2
?4 1
?1 8
The input consists of an N N array of integers. The input begins with a single positive integer N on
a line by itself indicating the size of the square two dimensional array. This is followed by N 2 integers
separated by white-space (newlines and spaces). These N 2 integers make up the array in row-major
order (i.e., all numbers on the rst row, left-to-right, then all numbers on the second row, left-to-right,
etc.). N may be as large as 100. The numbers in the array will be in the range [?127; 127].
The output is the sum of the maximal sub-rectangle.
Sample Input
4
0 -2 -7 0 9 2 -6 2
-4 1 -4 1 -1
8 0 -2
Sample Output
15
Background
Some problems are dicult to solve but have a simplication that is easy to solve. Rather than deal
with the diculties of constructing a model of the Earth (a somewhat oblate spheroid), consider a
pre-Columbian
at world that is a 500 kilometer 500 kilometer square.
In the model used in this problem, the
at world consists of several warring kingdoms. Though
warlike, the people of the world are strict isolationists; each kingdom is surrounded by a high (but thin)
wall designed to both protect the kingdom and to isolate it. To avoid ghts for power, each kingdom
has its own electric power plant.
When the urge to ght becomes too great, the people of a kingdom often launch missiles at other
kingdoms. Each SCUD missile (Sanitary Cleansing Universal Destroyer) that lands within the walls of
a kingdom destroys that kingdom's power plant (without loss of life).
The Problem
Given coordinate locations of several kingdoms (by specifying the locations of houses and the location
of the power plant in a kingdom) and missile landings you are to write a program that determines the
total area of all kingdoms that are without power after an exchange of missile re.
In the simple world of this problem kingdoms do not overlap. Furthermore, the walls surrounding
each kingdom are considered to be of zero thickness. The wall surrounding a kingdom is the minimalperimeter wall that completely surrounds all the houses and the power station that comprise a kingdom;
the area of a kingdom is the area enclosed by the minimal-perimeter thin wall.
There is exactly one power station per kingdom.
There may be empty space between kingdoms.
The Input
The input is a sequence of kingdom specications followed by a sequence of missile landing locations.
A kingdom is specied by a number N (3 N 100) on a single line which indicates the number of
sites in this kingdom. The next line contains the x and y coordinates of the power station, followed by
N ? 1 lines of x; y pairs indicating the locations of homes served by this power station. A value of ?1
for N indicates that there are no more kingdoms. There will be at least one kingdom in the data set.
Following the last kingdom specication will be the coordinates of one or more missile attacks,
indicating the location of a missile landing. Each missile location is on a line by itself. You are to
process missile attacks until you reach the end of the le.
Locations are specied in kilometers using coordinates on a 500 km by 500 km grid. All coordinates
will be integers between 0 and 500 inclusive. Coordinates are specied as a pair of integers separated by
white-space on a single line. The input le will consist of up to 20 kingdoms, followed by any number of
missile attacks.
The Output
The output consists of a single number representing the total area of all kingdoms without electricity
after all missile attacks have been processed. The number should be printed with (and correct to) two
decimal places.
Sample Input
12
3 3
4 6
4 11
4 8
10 6
5 7
6 6
6 3
7 9
10 4
10 9
1 7
5
20 20
20 40
40 20
40 40
30 30
3
10 10
21 10
21 13
-1
5 5
20 12
Sample Output
70.50
A Hint
=1
where the x, y coordinates of v = (x ; y ); the edges of the polygon are from v to v +1 for i = 0 : : : n ? 1.
If the points describing the polygon are given in a counterclockwise direction, the value of a will
be positive, and if the points of the polygon are listed in a clockwise direction, the value of a will be
negative.
i
Meta-Loopless Sorts
Background
Sorting holds an important place in computer science. Analyzing and implementing various sorting
algorithms forms an important part of the education of most computer scientists, and sorting accounts
for a signicant percentage of the world's computational resources. Sorting algorithms range from the
bewilderingly popular Bubble sort, to Quicksort, to parallel sorting algorithms and sorting networks. In
this problem you will be writing a program that creates a sorting program (a meta-sorter).
The Problem
The problem is to create a program whose output is a standard Pascal program that sorts n numbers
where n is the only input to the program you will write. The Pascal program generated by your program
must have the following properties:
For those unfamiliar with Pascal syntax, the example at the end of this problem completely denes
the small subset of Pascal needed.
The Input
The Output
The output is a compilable standard Pascal program meeting the criteria specied above.
Sample Input
Sample Output
program sort(input,output);
var
a,b,c : integer;
begin
readln(a,b,c);
if a < b then
if b < c then
writeln(a,b,c)
else if a < c then
writeln(a,c,b)
else
writeln(c,a,b)
else
if a < c then
writeln(b,a,c)
else if b < c then
writeln(b,c,a)
else
writeln(c,b,a)
end.
Background
Many problems in Computer Science involve maximizing some measure according to constraints.
Consider a history exam in which students are asked to put several historical events into chronological
order. Students who order all the events correctly will receive full credit, but how should partial credit
be awarded to students who incorrectly rank one or more of the historical events?
Some possibilities for partial credit include:
1. 1 point for each event whose rank matches its correct rank
2. 1 point for each event in the longest (not necessarily contiguous) sequence of events which are in
the correct order relative to each other.
For example, if four events are correctly ordered 1 2 3 4 then the order 1 3 2 4 would receive a score of
2 using the rst method (events 1 and 4 are correctly ranked) and a score of 3 using the second method
(event sequences 1 2 4 and 1 3 4 are both in the correct order relative to each other).
In this problem you are asked to write a program to score such questions using the second method.
The Problem
The Input
The rst line of the input will consist of one integer n indicating the number of events with 2 n 20.
The second line will contain n integers, indicating the correct chronological order of n events. The
remaining lines will each consist of n integers with each line representing a student's chronological
ordering of the n events. All lines will contain n numbers in the range [1 : : : n], with each number
appearing exactly once per line, and with each number separated from other numbers on the same line
by one or more spaces.
The Output
For each student ranking of events your program should print the score for that ranking. There should
be one line of output for each student ranking.
Sample Input 1
4
4
1
3
2
2
3
2
3
3
2
1
4
1
4
4
1
Sample Output 1
1
2
3
Sample Input 2
10
3 1 2 4 9 5 10 6 8 7
1 2 3 4 5 6 7 8 9 10
4 7 2 3 10 6 9 1 5 8
3 1 2 4 9 5 10 6 8 7
2 10 1 3 8 4 9 5 7 6
Sample Output 2
6
4
10
5
LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest
languages currently being used. Lists, which are the fundamental data structures in LISP, can easily be
adapted to represent other important data structures such as trees.
This problem deals with determining whether binary trees represented as LISP S-expressions possess
a certain property.
The Problem
Given a binary tree of integers, you are to write a program that determines whether there exists a
root-to-leaf path whose nodes sum to a specied integer. For example, in the tree shown below there
are exactly four root-to-leaf paths. The sums of the paths are 27, 22, 26, and 18.
11
13
Binary trees are represented in the input le as LISP S-expressions having the following form.
empty tree ::= ()
tree
::= empty tree j (integer tree tree)
The tree diagrammed above is represented by the expression
(5 (4 (11 (7 () ()) (2 () ()) ) ()) (8 (13 () ()) (4 () (1 () ()) ) ) )
Note that with this formulation all leaves of a tree are of the form
(integer () () )
Since an empty tree has no root-to-leaf paths, any query as to whether a path exists whose sum is a
specied integer in an empty tree must be answered negatively.
The Input
The input consists of a sequence of test cases in the form of integer/tree pairs. Each test case consists
of an integer followed by one or more spaces followed by a binary tree formatted as an S-expression
as described above. All binary tree S-expressions will be valid, but expressions may be spread over
several lines and may contain spaces. There will be one or more test cases in an input le, and input is
terminated by end-of-le.
The Output
There should be one line of output for each test case (integer/tree pair) in the input le. For each pair
(I represents the integer, T represents the tree) the output is the string yes if there is a root-to-leaf
path in T whose sum is I and no if there is no path in T whose sum is I .
I; T
Sample Input
22 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
20 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
10 (3
(2 (4 () () )
(8 () () ) )
(1 (6 () () )
(4 () () ) ) )
5 ()
Sample Output
yes
no
yes
no
Background
Current work in cryptography involves (among other things) large prime numbers and computing powers
of numbers modulo functions of these primes. Work in this area has resulted in the practical use of results
from number theory and other branches of mathematics once considered to be of only theoretical interest.
This problem involves the ecient computation of integer roots of numbers.
The Problem
n p, the positive
Given an integer n 1 and an integer p 1 you are to write a program that determines p
th
n root of p. In this problem, given such integers n and p, p will always be of the form kn for an integer
k (this integer is what your program must nd).
The Input
The input consists of a sequence of integer pairs n and p with each integer on a line by itself. For all
such pairs 1 n 200, 1 p < 10101 and there exists an integer k, 1 k 109 such that kn = p.
The Output
Sample Input
2
16
3
27
7
4357186184021382204544
Sample Output
4
3
1234
Background
Simulation is an important application area in computer science involving the development of computer
models to provide insight into real-world events. There are many kinds of simulation including (and
certainly not limited to) discrete event simulation and clock-driven simulation. Simulation often involves
approximating observed behavior in order to develop a practical approach.
This problem involves the simulation of a simplistic pinball machine. In a pinball machine, a steel ball
rolls around a surface, hitting various objects (bumpers) and accruing points until the ball \disappears"
from the surface.
The Problem
You are to write a program that simulates an idealized pinball machine. This machine has a
at surface
that has some obstacles (bumpers and walls). The surface is modeled as an m n grid with the origin in
the lower-left corner. Each bumper occupies a grid point. The grid positions on the edge of the surface
are walls. Balls are shot (appear) one at a time on the grid, with an initial position, direction, and
lifetime. In this simulation, all positions are integral, and the ball's direction is one of: up, down, left, or
right. The ball bounces around the grid, hitting bumpers (which accumulates points) and walls (which
does not add any points). The number of points accumulated by hitting a given bumper is the value
of that bumper. The speed of all balls is one grid space per timestep. A ball \hits" an obstacle during
a timestep when it would otherwise move on top of the bumper or wall grid point. A hit causes the
ball to \rebound" by turning right (clockwise) 90 degrees, without ever moving on top of the obstacle
and without changing position (only the direction changes as a result of a rebound). Note that by this
denition sliding along a wall does not constitute \hitting" that wall.
A ball's lifetime indicates how many time units the ball will live before disappearing from the surface.
The ball uses one unit of lifetime for each grid step it moves. It also uses some units of lifetime for each
bumper or wall that it hits. The lifetime used by a hit is the cost of that bumper or wall. As long as
the ball has a positive lifetime when it hits a bumper, it obtains the full score for that bumper. Note
that a ball with lifetime one will \die" during its next move and thus cannot obtain points for hitting
a bumper during this last move. Once the lifetime is non-positive (less than or equal to zero), the ball
disappears and the game continues with the next ball.
The Input
Your program should simulate one game of pinball. There are several input lines that describe the
game. The rst line gives integers m and n, separated by a space. This describes a cartesian grid where
1 x m and 1 y n on which the game is \played". It will be the case that 2 < m < 51 and
2 < n < 51. The next line gives the integer cost for hitting a wall. The next line gives the number of
bumpers, an integer p 0. The next p lines give the x position, y position, value, and cost, of each
bumper, as four integers per line separated by space(s). The x and y positions of all bumpers will be in
the range of the grid. The value and cost may be any integer (i.e., they may be negative; a negative cost
adds lifetime to a ball that hits the bumper). The remaining lines of the le represent the balls. Each
line represents one ball, and contains four integers separated by space(s): the initial x and y position of
the ball, the direction of movement, and its lifetime. The position will be in range (and not on top of any
bumper or wall). The direction will be one of four values: 0 for increasing x (right), 1 for increasing y
(up), 2 for decreasing x (left), and 3 for decreasing y (down). The lifetime will be some positive integer.
The Output
There should be one line of output for each ball giving an integer number of points accumulated by that
ball in the same order as the balls appear in the input. After all of these lines, the total points for all
balls should be printed.
Sample Input
4
0
2
2
3
2
2
2
2
2
4
2
3
3
3
3
3
3
1
1
1
1
1
1
1
0
0
1
2
3
4
5
Sample Output
0
0
1
2
2
5
Expression trees, B and B* trees, red-black trees, quad trees, PQ trees; trees play a signicant role in
many domains of computer science. Sometimes the name of a problem may indicate that trees are used
when they are not, as in the Articial Intelligence planning problem traditionally called the Monkey and
Bananas problem. Sometimes trees may be used in a problem whose name gives no indication that trees
are involved, as in the Human code.
This problem involves determining how pairs of people who may be part of a \family tree" are related.
The Problem
Given a sequence of child-parent pairs, where a pair consists of the child's name followed by the (single)
parent's name, and a list of query pairs also expressed as two names, you are to write a program
to determine whether the query pairs are related. If the names comprising a query pair are related
the program should determine what the relationship is. Consider academic advisees and advisors as
exemplars of such a single parent genealogy (we assume a single advisor, i.e., no co-advisors).
In this problem the child-parent pair p q denotes that p is the child of q . In determining relationships
between names we use the following denitions:
p is a 0-descendent of q (respectively 0-ancestor) if and only if the child-parent pair p q (respectively
q p) appears in the input sequence of child-parent pairs.
p is a k-descendent of q (respectively k-ancestor) if and only if the child-parent pair p r (respectively
q r) appears in the input sequence and r is a (k ? 1)-descendent of q (respectively p is a (k ? 1)ancestor of r).
For the purposes of this problem the relationship between a person p and a person q is expressed as
exactly one of the following four relations:
1. child | grand child, great grand child, great great grand child, etc.
By denition p is the \child" of q if and only if the pair p q appears in the input sequence of
child-parent pairs (i.e., p is a 0-descendent of q); p is the \grand child" of q if and only if p is a
1-descendent of q ; and
p is the \ great
great
: : : great} grand child" of q
|
{z
n times
3. cousin | 0th cousin, 1st cousin, 2nd cousin, etc.; cousins may be once removed, twice removed,
three times removed, etc.
By denition p and q are \cousins" if and only if they are related (i.e., there is a path from p to q
in the implicit undirected parent-child tree). Let r represent the least common ancestor of p and
q (i.e., no descendent of r is an ancestor of both p and q), where p is an m-descendent of r and q
is an n-descendent of r.
Then, by denition, cousins p and q are \kth cousins" if and only if k = min(n; m), and, also by
denition, p and q are \cousins removed j times" if and only if j = j n ? m j.
4. sibling | 0th cousins removed 0 times are \siblings" (they have the same parent).
The Input
The input consists of parent-child pairs of names, one pair per line. Each name in a pair consists of
lower-case alphabetic characters or periods (used to separate rst and last names, for example). Child
names are separated from parent names by one or more spaces. Parent-child pairs are terminated by a
pair whose rst component is the string \no.child". Such a pair is NOT to be considered as a parent-child
pair, but only as a delimiter to separate the parent-child pairs from the query pairs. There will be no
circular relationships, i.e., no name p can be both an ancestor and a descendent of the same name q .
The parent-child pairs are followed by a sequence of query pairs in the same format as the parentchild pairs, i.e., each name in a query pair is a sequence of lower-case alphabetic characters and periods,
and names are separated by one or more spaces. Query pairs are terminated by end-of-le.
There will be a maximum of 300 dierent names overall (parent-child and query pairs). All names
will be fewer than 31 characters in length. There will be no more than 100 query pairs.
The Output
For each query-pair p q of names the output should indicate the relationship p is-the-relative-of q by
the appropriate string of the form
child, grand child, great grand child, great great : : : great grand child
parent, grand parent, great grand parent, great great : : : great grand parent
sibling
n cousin removed m
no relation
If an m-cousin is removed 0 times then only m cousin should be printed, i.e., removed 0 should NOT be
printed. Do not print st, nd, rd, th after the numbers.
Sample Input
alonzo.church oswald.veblen
stephen.kleene alonzo.church
dana.scott alonzo.church
martin.davis alonzo.church
pat.fischer hartley.rogers
mike.paterson david.park
dennis.ritchie pat.fischer
hartley.rogers alonzo.church
les.valiant mike.paterson
bob.constable stephen.kleene
david.park hartley.rogers
no.child no.parent
stephen.kleene bob.constable
hartley.rogers stephen.kleene
les.valiant alonzo.church
les.valiant dennis.ritchie
dennis.ritchie les.valiant
pat.fischer michael.rabin
Sample Output
parent
sibling
great great grand child
1 cousin removed 1
1 cousin removed 1
no relation
116
Unidirectional TSP
Background
Problems that require minimum paths through some domain appear in many dierent areas of computer
science. For example, one of the constraints in VLSI routing problems is minimizing wire length. The
Traveling Salesperson Problem (TSP) | nding whether all the cities in a salesperson's route can be
visited exactly once with a specied limit on travel time | is one of the canonical examples of an
NP-complete problem; solutions appear to require an inordinate amount of time to generate, but are
simple to check.
This problem deals with nding a minimal path through a grid of points while traveling only from
left to right.
The Problem
Given an m n matrix of integers, you are to write a program that computes a path of minimal weight.
A path starts anywhere in column 1 (the rst column) and consists of a sequence of steps terminating
in column n (the last column). A step consists of traveling from column i to column i +1 in an adjacent
(horizontal or diagonal) row. The rst and last rows (rows 1 and m) of a matrix are considered adjacent,
i.e., the matrix \wraps" so that it represents a horizontal cylinder. Legal steps are illustrated below.
R
The weight of a path is the sum of the integers in each of the n cells of the matrix that are visited.
For example, two slightly dierent 5 6 matrices are shown below (the only dierence is the numbers
in the bottom row).
2
The minimal path is illustrated for each matrix. Note that the path for the matrix on the right
takes advantage of the adjacency property of the rst and last rows.
The Input
The input consists of a sequence of matrix specications. Each matrix specication consists of the row
and column dimensions in that order on a line followed by m n integers where m is the row dimension
and n is the column dimension. The integers appear in the input in row major order, i.e., the rst n
integers constitute the rst row of the matrix, the second n integers constitute the second row and so
on. The integers on a line will be separated from other integers by one or more spaces. Note: integers
are not restricted to being positive. There will be one or more matrix specications in an input le.
Input is terminated by end-of-le.
For each specication the number of rows will be between 1 and 10 inclusive; the number of columns
will be between 1 and 100 inclusive. No path's weight will exceed integer values representable using 30
bits.
The Output
Two lines should be output for each matrix specication in the input le, the rst line represents a
minimal-weight path, and the second line is the cost of a minimal path. The path consists of a sequence
of n integers (separated by one or more spaces) representing the rows that constitute the minimal path.
If there is more than one path of minimal weight the path that is lexicographically smallest should be
output.
Sample Input
5
3
6
5
8
3
5
3
6
5
8
3
2
9
6
4 1 2 8
1 8 2 7
9 3 9 9
4 1 3 2
7 2 8 6
6
4 1 2 8
1 8 2 7
9 3 9 9
4 1 3 2
7 2 1 2
2
10 9 10
6
4
5
6
4
6
4
5
6
3
Sample Output
1 2 3 4 4 5
16
1 2 1 5 4 5
11
1 1
19
Background
Graph algorithms form a very important part of computer science and have a lineage that goes back
at least to Euler and the famous Seven Bridges of Konigsberg problem. Many optimization problems
involve determining ecient methods for reasoning about graphs.
This problem involves determining a route for a postal worker so that all mail is delivered while the
postal worker walks a minimal distance, so as to rest weary legs.
The Problem
Given a sequence of streets (connecting given intersections) you are to write a program that determines
the minimal cost tour that traverses every street at least once. The tour must begin and end at the
same intersection.
The \real-life" analogy concerns a postal worker who parks a truck at an intersection and then walks
all streets on the postal delivery route (delivering mail) and returns to the truck to continue with the
next route.
The cost of traversing a street is a function of the length of the street (there is a cost associated with
delivering mail to houses and with walking even if no delivery occurs).
In this problem the number of streets that meet at a given intersection is called the degree of the
intersection. There will be at most two intersections with odd degree. All other intersections will have
even degree, i.e., an even number of streets meeting at that intersection.
The Input
The input consists of a sequence of one or more postal routes. A route is composed of a sequence of
street names (strings), one per line, and is terminated by the string \deadend " which is NOT part of
the route. The rst and last letters of each street name specify the two intersections for that street,
the length of the street name indicates the cost of traversing the street. All street names will consist of
lowercase alphabetic characters.
For example, the name foo indicates a street with intersections f and o of length 3, and the name
computer indicates a street with intersections c and r of length 8. No street name will have the same
rst and last letter and there will be at most one street directly connecting any two intersections. As
specied, the number of intersections with odd degree in a postal route will be at most two. In each
postal route there will be a path between all intersections, i.e., the intersections are connected.
The Output
For each postal route the output should consist of the cost of the minimal tour that visits all streets
at least once. The minimal tour costs should be output in the order corresponding to the input postal
routes.
Sample Input
one
two
three
deadend
mit
dartmouth
linkoping
tasmania
york
emory
cornell
duke
kaunas
hildesheim
concord
arkansas
williams
glasgow
deadend
Sample Output
11
114
Background
Robotics, robot motion planning, and machine learning are areas that cross the boundaries of many of
the subdisciplines that comprise Computer Science: articial intelligence, algorithms and complexity,
electrical and mechanical engineering to name a few. In addition, robots as \turtles" (inspired by work
by Papert, Abelson, and diSessa) and as \beeper-pickers" (inspired by work by Pattis) have been studied
and used by students as an introduction to programming for many years.
This problem involves determining the position of a robot exploring a pre-Columbian
at world.
The Problem
Given the dimensions of a rectangular grid and a sequence of robot positions and instructions, you are to
write a program that determines for each sequence of robot positions and instructions the nal position
of the robot.
A robot position consists of a grid coordinate (a pair of integers: x-coordinate followed by ycoordinate) and an orientation (N,S,E,W for north, south, east, and west). A robot instruction is a
string of the letters 'L', 'R', and 'F' which represent, respectively, the instructions:
Left: the robot turns left 90 degrees and remains on the current grid point.
Right: the robot turns right 90 degrees and remains on the current grid point.
Forward: the robot moves forward one grid point in the direction of the current orientation and
mantains the same orientation.
The direction North corresponds to the direction from grid point (x; y ) to grid point (x; y + 1).
Since the grid is rectangular and bounded, a robot that moves \o" an edge of the grid is lost forever.
However, lost robots leave a robot \scent" that prohibits future robots from dropping o the world at
the same grid point. The scent is left at the last grid position the robot occupied before disappearing
over the edge. An instruction to move \o" the world from a grid point from which a robot has been
previously lost is simply ignored by the current robot.
The Input
The rst line of input is the upper-right coordinates of the rectangular world, the lower-left coordinates
are assumed to be 0,0.
The remaining input consists of a sequence of robot positions and instructions (two lines per robot).
A position consists of two integers specifying the initial coordinates of the robot and an orientation
(N,S,E,W), all separated by white space on one line. A robot instruction is a string of the letters 'L',
'R', and 'F' on one line.
Each robot is processed sequentially, i.e., nishes executing the robot instructions before the next
robot begins execution.
Input is terminated by end-of-le.
You may assume that all initial robot positions are within the bounds of the specied grid. The
maximum value for any coordinate is 50. All instruction strings will be less than 100 characters in
length.
The Output
For each robot position/instruction in the input, the output should indicate the nal grid position and
orientation of the robot. If a robot falls o the edge of the grid the word \LOST" should be printed
after the position and orientation.
Sample Input
5 3
1 1 E
RFRFRFRF
3 2 N
FRRFLLFFRRFLL
0 3 W
LLFFFLFLFL
Sample Output
1 1 E
3 3 N LOST
2 3 S
Background
The Problem
This problem involves determining, for a group of gift-giving friends, how much more each person gives
than they receive (and vice versa for those that view gift-giving with cynicism).
In this problem each person sets aside some money for gift-giving and divides this money evenly
among all those to whom gifts are given.
However, in any group of friends, some people are more giving than others (or at least may have
more acquaintances) and some people have more money than others.
Given a group of friends, the money each person in the group spends on gifts, and a (sub)list of
friends to whom each person gives gifts; you are to write a program that determines how much more (or
less) each person in the group gives than they receive.
The Input
The Output
For each group of gift-givers, the name of each person in the group should be printed on a line followed
by the net gain (or loss) received (or spent) by the person. Names in a group should be printed in the
same order in which they rst appear in the input.
The output for each group should be separated from other groups by a blank line. All gifts are
integers. Each person gives the same integer amount of money to each friend to whom any money is
given, and gives as much as possible. Any money not given is kept and is part of a person's \net worth"
printed in the output.
Sample Input
5
dave laura owen vick amr
dave 200 3 laura owen vick
owen 500 1 dave
amr 150 2 vick owen
laura 0 2 amr vick
vick 0 0
3
liz steve dave
liz 30 1 steve
steve 55 2 liz dave
dave 0 2 steve liz
Sample Output
dave 302
laura 66
owen -359
vick 141
amr -150
liz -3
steve -24
dave 27
Background
Stacks and Queues are often considered the bread and butter of data structures and nd use in architecture, parsing, operating systems, and discrete event simulation. Stacks are also important in the theory
of formal languages.
This problem involves both butter and sustenance in the form of pancakes rather than bread in
addition to a nicky server who
ips pancakes according to a unique, but complete set of rules.
The Problem
Given a stack of pancakes, you are to write a program that indicates how the stack can be sorted so
that the largest pancake is on the bottom and the smallest pancake is on the top. The size of a pancake
is given by the pancake's diameter. All pancakes in a stack have dierent diameters.
Sorting a stack is done by a sequence of pancake \
ips". A
ip consists of inserting a spatula between
two pancakes in a stack and
ipping (reversing) all the pancakes on the spatula (reversing the sub-stack).
A
ip is specied by giving the position of the pancake on the bottom of the sub-stack to be
ipped
(relative to the whole stack). The pancake on the bottom of the whole stack has position 1 and the
pancake on the top of a stack of n pancakes has position n.
A stack is specied by giving the diameter of each pancake in the stack in the order in which the
pancakes appear.
For example, consider the three stacks of pancakes below (in which pancake 8 is the top-most pancake
of the left stack):
8
4
6
7
5
2
7
6
4
8
5
2
2
5
8
4
6
7
The stack on the left can be transformed to the stack in the middle via
ip(3). The middle stack can
be transformed into the right stack via the command
ip(1).
The Input
The input consists of a sequence of stacks of pancakes. Each stack will consist of between 1 and 30
pancakes and each pancake will have an integer diameter between 1 and 100. The input is terminated
by end-of-le. Each stack is given as a single line of input with the top pancake on a stack appearing
rst on a line, the bottom pancake appearing last, and all pancakes separated by a space.
The Output
For each stack of pancakes, the output should echo the original stack on one line, followed by some
sequence of
ips that results in the stack of pancakes being sorted so that the largest diameter pancake
is on the bottom and the smallest on top. For each stack the sequence of
ips should be terminated by
a 0 (indicating no more
ips necessary). Once a stack is sorted, no more
ips should be made.
Sample Input
1 2 3 4 5
5 4 3 2 1
5 1 2 3 4
Sample Output
1
0
5
1
5
1
2 3 4 5
4 3 2 1
0
1 2 3 4
2 0
Background
Filters, or programs that pass \processed" data through in some changed form, are an important class
of programs in the UNIX operating system. A pipe is an operating system concept that permits data to
\
ow" between processes (and allows lters to be chained together easily.)
This problem involves maximizing the number of pipes that can be t into a storage container (but
it's a pipe tting problem, not a bin packing problem).
The Problem
A company manufactures pipes of uniform diameter. All pipes are stored in rectangular storage containers, but the containers come in several dierent sizes. Pipes are stored in rows within a container
so that there is no space between pipes in any row (there may be some space at the end of a row), i.e.,
all pipes in a row are tangent, or touch. Within a rectangular cross-section, pipes are stored in either
a grid pattern or a skew pattern as shown below: the two left-most cross-sections are in a grid pattern,
the two right-most cross-sections are in a skew pattern.
grid patterns
skew patterns
Note that although it may not be apparent from the diagram, there is no space between adjacent
pipes in any row. The pipes in any row are tangent to (touch) the pipes in the row below (or rest on
the bottom of the container). When pipes are packed into a container, there may be \left-over" space
in which a pipe cannot be packed. Such left-over space is packed with padding so that the pipes cannot
settle during shipping.
The Input
The input is a sequence of cross-section dimensions of storage containers. Each cross-section is given
as two real values on one line separated by white space. The dimensions are expressed in units of pipe
diameters. All dimensions will be less than 27. Note that a cross section with dimensions a b can also
be viewed as a cross section with dimensions b a.
The Output
For each cross-section in the input, your program should print the maximum number of pipes that can
be packed into that cross section. The number of pipes is an integer | no fractional pipes can be packed.
The maximum number is followed by the word \grid" if a grid pattern results in the maximal number
of pipes or the word \skew" if a skew pattern results in the maximal number of pipes. If the pattern
doesn't matter, that is the same number of pipes can be packed with either a grid or skew pattern, then
the word \grid" should be printed.
Sample Input
3 3
2.9 10
2.9 10.5
11 11
Sample Output
9 grid
29 skew
30 skew
126 skew
Background
Trees are fundamental in many branches of computer science1 . Current state-of-the art parallel computers such as Thinking Machines' CM-5 are based on fat trees. Quad- and octal-trees are fundamental to
many algorithms in computer graphics.
This problem involves building and traversing binary trees.
The Problem
Given a sequence of binary trees, you are to write a program that prints a level-order traversal of each
tree. In this problem each node of a binary tree contains a positive integer and all binary trees have
have fewer than 256 nodes.
In a level-order traversal of a tree, the data in all nodes at a given level are printed in left-to-right
order and all nodes at level k are printed before all nodes at level k + 1.
For example, a level order traversal of the tree
11
13
The Input
The input is a sequence of binary trees specied as described above. Each tree in a sequence consists
of several pairs (n; s) as described above separated by whitespace. The last entry in each tree is (). No
whitespace appears between left and right parentheses.
All nodes contain a positive integer. Every tree in the input will consist of at least one node and no
more than 256 nodes. Input is terminated by end-of-le.
1
The Output
For each completely specied binary tree in the input le, the level order traversal of that tree should
be printed. If a tree is not completely specied, i.e., some node in the tree is NOT given a value or a
node is given a value more than once, then the string \not complete" should be printed.
Sample Input
(11,LL) (7,LLL) (8,R)
(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
(3,L) (4,R) ()
Sample Output
5 4 8 11 13 4 7 2 1
not complete
Background
Searching and sorting are part of the theory and practice of computer science. For example, binary search
provides a good example of an easy-to-understand algorithm with sub-linear complexity. Quicksort is
an ecient O(n log n) [average case] comparison based sort.
KWIC-indexing is an indexing method that permits ecient \human search" of, for example, a list
of titles.
The Problem
Given a list of titles and a list of \words to ignore", you are to write a program that generates a KWIC
(Key Word In Context) index of the titles. In a KWIC-index, a title is listed once for each keyword that
occurs in the title. The KWIC-index is alphabetized by keyword.
Any word that is not one of the \words to ignore" is a potential keyword.
For example, if words to ignore are \the, of, and, as, a" and the list of titles is:
Descent of Man
The Ascent of Man
The Old Man and The Sea
A Portrait of The Artist As a Young Man
The Input
The input is a sequence of lines, the string :: is used to separate the list of words to ignore from the list
of titles. Each of the words to ignore appears in lower-case letters on a line by itself and is no more than
10 characters in length. Each title appears on a line by itself and may consist of mixed-case (upper and
lower) letters. Words in a title are separated by whitespace. No title contains more than 15 words.
There will be no more than 50 words to ignore, no more than than 200 titles, and no more than
10,000 characters in the titles and words to ignore combined. No characters other than 'a'{'z', 'A'{'Z',
and white space will appear in the input.
The Output
The output should be a KWIC-index of the titles, with each title appearing once for each keyword in
the title, and with the KWIC-index alphabetized by keyword. If a word appears more than once in a
title, each instance is a potential keyword.
The keyword should appear in all upper-case letters. All other words in a title should be in lowercase letters. Titles in the KWIC-index with the same keyword should appear in the same order as they
appeared in the input le. In the case where multiple instances of a word are keywords in the same title,
the keywords should be capitalized in left-to-right order.
Case (upper or lower) is irrelevant when determining if a word is to be ignored.
The titles in the KWIC-index need NOT be justied or aligned by keyword, all titles may be listed
left-justied.
Sample Input
is
the
of
and
as
a
but
::
Descent of Man
The Ascent of Man
The Old Man and The Sea
A Portrait of The Artist As a Young Man
A Man is a Man but Bubblesort IS A DOG
Sample Output
a portrait of the ARTIST as a
the ASCENT of man
a man is a man but BUBBLESORT
DESCENT of man
a man is a man but bubblesort
descent of MAN
the ascent of MAN
the old MAN and the sea
a portrait of the artist as a
a MAN is a man but bubblesort
a man is a MAN but bubblesort
the OLD man and the sea
a PORTRAIT of the artist as a
the old man and the SEA
a portrait of the artist as a
young man
is a dog
is a DOG
young MAN
is a dog
is a dog
young man
YOUNG man
Background
Order is an important concept in mathematics and in computer science. For example, Zorn's Lemma
states: \a partially ordered set in which every chain has an upper bound contains a maximal element."
Order is also important in reasoning about the x-point semantics of programs.
This problem involves neither Zorn's Lemma nor x-point semantics, but does involve order.
The Problem
Given a list of variable constraints of the form x < y, you are to write a program that prints all orderings
of the variables that are consistent with the constraints.
For example, given the constraints x < y and x < z there are two orderings of the variables x, y,
and z that are consistent with these constraints: x y z and x z y.
The Input
The input consists of a sequence of constraint specications. A specication consists of two lines: a list
of variables on one line followed by a list of contraints on the next line. A constraint is given by a pair
of variables, where x y indicates that x < y.
All variables are single character, lower-case letters. There will be at least two variables, and no
more than 20 variables in a specication. There will be at least one constraint, and no more than 50
constraints in a specication. There will be at least one, and no more than 300 orderings consistent with
the contraints in a specication.
Input is terminated by end-of-le.
The Output
For each constraint specication, all orderings consistent with the constraints should be printed. Orderings are printed in lexicographical (alphabetical) order, one per line. Characters on a line are separated
by whitespace.
Output for dierent constraint specications is separated by a blank line.
Sample Input
a
a
v
v
b
b
w
y
f
b
x
x
g
f
y z
v z v w v
Sample Output
abfg
abgf
agbf
gabf
wxzvy
wzxvy
xwzvy
xzwvy
zwxvy
zxwvy
Background
Problems that process input and generate a simple \yes" or \no" answer are called decision problems.
One class of decision problems, the NP-complete problems, are not amenable to general ecient solutions.
Other problems may be simple as decision problems, but enumerating all possible \yes" answers may be
very dicult (or at least time-consuming).
This problem involves determining the number of routes available to an emergency vehicle operating
in a city of one-way streets.
The Problem
Given the intersections connected by one-way streets in a city, you are to write a program that determines
the number of dierent routes between each intersection. A route is a sequence of one-way streets
connecting two intersections.
Intersections are identied by non-negative integers. A one-way street is specied by a pair of
intersections. For example, j k indicates that there is a one-way street from intersection j to intersection
k. Note that two-way streets can be modeled by specifying two one-way streets: j k and k j .
Consider a city of four intersections connected by the following one-way streets:
0
0
1
2
1
2
2
3
There is one route from intersection 0 to 1, two routes from 0 to 2 (the routes are 0 ! 1 ! 2 and 0 ! 2),
one route from 2 to 3, and no other routes.
It is possible for an innite number of dierent routes to exist. For example if the intersections above
are augmented by the street 3 2, there is still only one route from 0 to 1, but there are innitely many
dierent routes from 0 to 2. This is because the street from 2 to 3 and back to 2 can be repeated yielding
a dierent sequence of streets and hence a dierent route. Thus the route 0 ! 2 ! 3 ! 2 ! 3 ! 2 is a
dierent route than 0 ! 2 ! 3 ! 2.
The Input
The input is a sequence of city specications. Each specication begins with the number of one-way
streets in the city followed by that many one-way streets given as pairs of intersections. Each pair j k
represents a one-way street from intersection j to intersection k. In all cities, intersections are numbered
sequentially from 0 to the \largest" intersection. All integers in the input are separated by whitespace.
The input is terminated by end-of-le.
There will never be a one-way street from an intersection to itself. No city will have more than 30
intersections.
The Output
For each city specication, a square matrix of the number of dierent routes from intersection j to
intersection k is printed. If the matrix is denoted M , then M [j ][k] is the number of dierent routes from
intersection j to intersection k. The matrix M should be printed in row-major order, one row per line.
Each matrix should be preceded by the string \matrix for city k" (with k appropriately instantiated,
beginning with 0).
If there are an innite number of dierent paths between two intersections a -1 should be printed.
DO NOT worry about justifying and aligning the output of each matrix. All entries in a row should
be separated by whitespace.
Sample Input
7
5
0
0
9
0
0
2
3
3
0 1 0 2 0 4 2 4 2 3 3 1 4 3
2
1 1 5 2 5 2 1
1 0 2 0 3
4 1 4 2 1
0
0
1
Sample Output
matrix for city 0
0 4 1 3 2
0 0 0 0 0
0 2 0 2 1
0 1 0 0 0
0 1 0 1 0
matrix for city 1
0 2 1 0 0 3
0 0 0 0 0 1
0 1 0 0 0 2
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
matrix for city 2
-1 -1 -1 -1 -1
0 0 0 0 1
-1 -1 -1 -1 -1
-1 -1 -1 -1 -1
0 0 0 0 0
13 2
y
11
Unfortunately, such problems are so trivial that the great man's mind keeps drifting o the job,
and he gets the wrong answers. As a consequence, several nuclear warheads that he has designed have
detonated prematurely, wiping out ve major cities and a couple of rain forests.
You are to write a program to perform such multiplications and save the world.
Input
The le of input data will contain pairs of lines, with each line containing no more than 80 characters. The
nal line of the input le contains a # as its rst character. Each input line contains a polynomial written
without spaces and without any explicit exponentiation operator. Exponents are positive non-zero
unsigned integers. Coecients are also integers, but may be negative. Both exponents and coecients
are less than or equal to 100 in magnitude. Each term contains at most one factor in x and one in y.
Output
Your program must multiply each pair of polynomials in the input, and print each product on a pair
of lines, the rst line containing all the exponents, suitably positioned with respect to the rest of the
information, which is in the line below.
The following rules control the output format:
1. Terms in the output line must be sorted in decreasing order of powers of x and, for a given power
of x, in increasing order of powers of y.
2. Like terms must be combined into a single term. For example, 40x2y 3 ? 40x2y 3 is replaced by
2x2y 3 .
3. Terms with a zero coecient must not be displayed.
4. Coecients of 1 are omitted, except for the case of a constant term of 1.
5. Exponents of 1 are omitted.
6. Factors of x0 and y 0 are omitted.
7. Binary pluses and minuses (that is the pluses and minuses connecting terms in the output) have a
single blank column both before and after.
8. If the coecient of the rst term is negative, it is preceded by a unary minus in the rst column,
with no intervening blank column. Otherwise, the coecient itself begins in the rst output
column.
9. The output can be assumed to t into a single line of at most 80 charactes in length.
10. There should be no blank lines printed between each pair of output lines.
11. The pair of lines that contain a product should be the same length|trailing blanks should appear
after the last non-blank character of the shorter line to achieve this.
Sample Input
-yx8+9x3-1+y
x5y+1+x3
1
1
#
Sample Output
13 2
11
8
6
5
5 2
3 3
-x y - x y + 8x y + 9x - x y + x y + 8x +x y - 1 + y
1
Input
Input data to the program species the order in which cards are dealt from the pack. The input contains
pairs of lines, each line containing 26 cards separated by single space characters. The nal line of the
input le contains a # as its rst character. Cards are represented as a two character code. The rst
character is the face-value (A=Ace, 2{9, T=10, J=Jack, Q=Queen, K=King) and the second character
is the suit (C=Clubs, D=Diamonds, H=Hearts, S=Spades).
Output
One line of output must be produced for each pair of lines (that between them describe a pack of 52
cards) in the input. Each line of output shows the number of cards in each of the piles remaining after
playing \Accordian patience" with the pack of cards as described by the corresponding pairs of input
lines.
Sample Input
QD AD 8H 5S 3H 5H TC 4D JH KS 6H 8S JS AC AS 8D 2H QS TS 3S AH 4H TH TD 3C 6S
8C 7D 4C 4S 7S 9H 7C 5D 2S KD 2D QH JD 6D 9D JC 2C KH 3D QC 6C 9S KC 7H 9C 5C
#
Sample Output
6 piles remaining: 40 8 1 1 1 1
CRC Generation
The message to be transmitted is viewed as a long positive binary number. The rst byte
of the message is treated as the most signicant byte of the binary number. The second
byte is the next most signicant, etc. This binary number will be called \m" (for message).
Instead of transmitting \m" you will transmit a message, \m2", consisting of \m" followed
by a two-byte CRC value.
The CRC value is chosen so that \m2" when divided by a certain 16-bit value \g" leaves
a remainder of 0. This makes it easy for the receiving program to determine whether the
message has been corrupted by transmission errors. It simply divides any message received
by \g". If the remainder of the division is zero, it is assumed that no error has occurred.
You notice that most of the suggested values of \g" in the book are odd, but don't see
any other similarities, so you select the value 34943 for \g" (the generator value).
You are to devise an algorithm for calculating the CRC value corresponding to any message that might
be sent. To test this algorithm you will write a program which reads lines (each line being all characters
up to, but not including the end of line character) as input, and for each line calculates the CRC value
for the message contained in the line, and writes the numeric value of the CRC bytes (in hexadecimal
notation) on an output line. Each input line will contain no more than 1024 ASCII characters. The
input is terminated by a line that contains a # in column 1. Note that each CRC printed should be in
the range 0 to 34942 (decimal).
Sample Input
this is a test
A
#
Sample Output
77 FD
0C 86
129
Krypton Factor
You have been employed by the organisers of a Super Krypton Factor Contest in which contestants
have very high mental and physical abilities. In one section of the contest the contestants are tested on
their ability to recall a sequenace of characters which has been read to them by the Quiz Master. Many
of the contestants are very good at recognising patterns. Therefore, in order to add some diculty to
this test, the organisers have decided that sequences containing certain types of repeated subsequences
should not be used. However, they do not wish to remove all subsequences that are repeated, since in
that case no single character could be repeated. This in itself would make the problem too easy for the
contestants. Instead it is decided to eliminate all sequences containing an occurrence of two adjoining
identical subsequences. Sequences containing such an occurrence will be called \easy". Other sequences
will be called \hard".
For example, the sequence ABACBCBAD is easy, since it contains an adjoining repetition of the
subsequence CB. Other examples of easy sequences are:
BB
ABCDACABCAB
ABCDABCD
D
DC
ABDAB
CBABCBA
In order to provide the Quiz Master with a potentially unlimited source of questions you are asked to
write a program that will read input lines that contain integers n and L (in that order), where n > 0
and L is in the range 1 L 26, and for each input line prints out the nth hard sequence (composed
of letters drawn from the rst L letters in the alphabet), in increasing alphabetical order2 , followed (on
the next line) by the length of that sequence. The rst sequence in this ordering is A. You may assume
that for given n and L there do exist at least n hard sequences.
For example, with L = 3, the rst 7 hard sequences are:
A
AB
ABA
ABAC
ABACA
ABACAB
ABACABA
As each sequence is potentially very long, split it into groups of four (4) characters separated by a
space. If there are more than 16 such groups, please start a new line for the 17th group.
Therefore, if the integers 7 and 3 appear on an input line, the output lines produced should be
ABAC ABA
7
Input is terminated by a line containing two zeroes. Your program may assume a maximum sequence
length of 80.
Sample Input
30 3
0 0
Sample Output
ABAC ABCA CBAB CABA CABC ACBA CABA
28
Your program must read input lines containing values for n and k (in that order), and for each input line
output the number of the person with which the counting should begin in order to ensure that you are
the sole survivor. For example, in the above case the safe starting position is 3. Input will be terminated
by a line containing values of 0 for n and k.
Your program may assume a maximum of 100 people taking part in this event.
Sample Input
1 1
1 5
0 0
Sample Output
1
1
Input will consist of a series of lines, each containing the initial ve cards in the hand then the rst
ve cards on top of the deck. Each card is represented as a two-character code. The rst character is
the face-value (A=Ace, 2{9, T=10, J=Jack, Q=Queen, K=King) and the second character is the suit
(C=Clubs, D=Diamonds, H=Hearts, S=Spades). Cards will be separated by single spaces. Each input
line will be from a single valid deck, that is there will be no duplicate cards in each hand and deck.
Each line of input should produce one line of output, consisting of the initial hand, the top ve cards
on the deck, and the best value of hand that is possible. Input is terminated by end of le.
Use the sample input and output as a guide. Note that the order of the cards in the player's hand
is irrelevant, but the order of the cards in the deck is important because the discarded cards must be
replaced from the top of the deck. Also note that examples of all types of hands appear in the sample
output, with the hands shown in decreasing order of value.
Sample Input
TH
2H
2H
2H
AC
KS
AH
6C
3D
JH
2S
2S
AD
2D
AH
2C
9C
5S
QC
3H
3H
5H
9C
2H
9S
8C
2H
QD
3S
3S
AC
3S
3C
AD
2D
QD
QS
3C
3C
7H
KD
4H
3C
7C
TD
QH
2D
2D
AH
5S
KC
QH
2H
6S
KH
3D
9C
6H
4D
2C
KS
TC
KH
AH
6C
3D
9H
KS
TC
JS
4C
9H
2S
9C
6C
4H
AS
2D
JD
9S
AD
6S
TH
TH
3C
4C
AS
KD
AH
QH
QS
3C
3C
7H
KD
4H
3C
7C
TD
Deck:
Deck:
Deck:
Deck:
Deck:
Deck:
Deck:
Deck:
Deck:
QH
2D
2D
AH
5S
KC
QH
2H
6S
Sample Output
Hand:
Hand:
Hand:
Hand:
Hand:
Hand:
Hand:
Hand:
Hand:
TH
2H
2H
2H
AC
KS
AH
6C
3D
JH
2S
2S
AD
2D
AH
2C
9C
5S
QC
3H
3H
5H
9C
2H
9S
8C
2H
QD
3S
3S
AC
3S
3C
AD
2D
QD
KH
3D
9C
6H
4D
2C
KS
TC
KH
AH
6C
3D
9H
KS
TC
JS
4C
9H
2S
9C
6C
4H
AS
2D
JD
9S
AD
6S
TH
TH
3C
4C
AS
KD
AH
QH
Best
Best
Best
Best
Best
Best
Best
Best
Best
hand:
hand:
hand:
hand:
hand:
hand:
hand:
hand:
hand:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pairs
one-pair
highest-card
7
8
1
2
3
4
1
5
6
Object 1
3
Object 2
4
Square
Consider objects such as these. They are polygons, specied by the coordinates of a centre of mass
and their vertices. In the gure, centres of mass are shown as black squares. The vertices will be
numbered consecutively anti-clockwise as shown.
An object can be rotated to stand stably if two vertices can be found that can be joined by a straight
line that does not intersect the object, and, when this line is horizontal, the centre of mass lies above the
line and strictly between its endpoints. There are typically many stable positions and each is dened by
one of these lines known as its base line. A base line, and its associated stable position, is identied by
the highest numbered vertex touched by that line.
Write a program that will determine the stable position that has the lowest numbered base line. Thus
for the above objects, the desired base lines would be 6 for object 1, 6 for object 2 and 2 for the square.
You may assume that the objects are possible, that is they will be represented as non self-intersecting
polygons, although they may well be concave.
Input and Output
Successive lines of a data set will contain: a string of less than 20 characters identifying the object; the
coordinates of the centre of mass; and the coordinates of successive points terminated by two zeroes (0
0), on one or more lines as necessary. There may be successive data sets (objects). The end of data will
be dened by the string '#'.
Output will consist of the identication string followed by the number of the relevant base line.
Sample input
Object2
4 3
3 2 5 2 6 1 7 1 6 3 4 7 1 1 2 1 0 0
Square
2 2
1 1 3 1 3 3 1 3 0 0
#
Sample output
Object2
Square
6
2
Input
Write a program that will successively read in (in that order) the three numbers (N, k and m; k, m >
0, 0 < N < 20) and determine the order in which the applicants are sent o for retraining. Each set of
three numbers will be on a separate line and the end of data will be signalled by three zeroes (0 0 0).
Output
For each triplet, output a single line of numbers specifying the order in which people are chosen. Each
number should be in a eld of 3 characters. For pairs of numbers list the person chosen by the counterclockwise ocial rst. Separate successive pairs (or singletons) by commas (but there should not be a
trailing comma).
Sample input
10 4 3
0 0 0
Sample output
444448,449445,443441,442446,410,447
where 4 represents a space.
) ajejijoju
) ga j ge j gi j go j gu
) ba j be j bi j bo j bu
) da j de j di j do j du
) la j le j li j lo j lu
) fall namesg
) fall predicatesg
) <statement> j <predclaim>
) <predname> BA <preds> j DA <preds>
) <predstring> j <preds> A <predstring>
) LA <predstring> j NAM
) PREDA j <predstring> PREDA
) <predname> <verbpred> <predname> j <predname> <verbpred>
) MOD <predstring>
Write a program that will read a succession of strings and determine whether or not they are correctly
formed Loglan sentences.
Each Loglan sentence will start on a new line and will be terminated by a period (.). The sentence may
occupy more than one line and words may be separated by more than one space. The input will be
terminated by a line containing a single `#'. You can assume that all words will be correctly formed.
Output will consist of one line for each sentence containing either `Good' or `Bad!'.
Sample input
la mutce bunbo mrenu bi ditca.
la fumna bi le mrenu.
djan ga vedma le negro ketpi.
#
Sample output
Good
Bad!
Good
135 No Rectangles
Consider a grid such as the one shown. We wish to mark k intersections in each of n rows and n columns
in such a way that no 4 of the selected intersections form a rectangle with sides parallel to the grid.
Thus for k = 2 and n = 3, a possible solution is:
It can easily be shown that for any given value of k, k2 ? k + 1 is a lower bound on the value of n,
and it can be shown further that n need never be larger than this.
Write a program that will nd a solution to this problem for k = 12, n = 133.
There is no input to this program. Output will consist of n lines of k points indicating the selected
points on that line.
Example: if the problem had called for a solution to the problem for k = 2, n = 3; then the output
could look like this:
Sample output
1 2
1 3
2 3
There is no input to this program. Output should consist of a single line as shown below, with <number>
replaced by the number computed.
Sample output
The 1500'th ugly number is
<number>.
137 Polygons
Given two convex polygons, they may or may not overlap. If they do overlap, they will do so to diering
degrees and in dierent ways. Write a program that will read in the coordinates of the corners of two
convex polygons and calculate the `exclusive or' of the two areas, that is the area that is bounded by
exactly one of the polygons. The desired area is shaded in the following diagram:
Input
Input will consist of pairs of lines each containing the number of vertices of the polygon, followed by
that many pairs of integers representing the x,y coordinates of the corners in a clockwise direction. All
the coordinates will be positive integers less than 100. For each pair of polygons (pair of lines in the
data le), your program should print out the desired area correct to two decimal places. The input will
end with a line containing a zero (0).
Output
Output will consist of a single line containing the desired area written as a succession of eight (8) digit
elds with two (2) digits after the decimal point. There will not be enough cases to need more than one
line.
Sample input
3
3
4
6
0
5
5
1
6
5
5
2
3
8
8
1
8
1
1
4
2
2
2
5
8
3
3
4 5 2
1 4 1 4 2 5 3
Sample output
4 4 440.0044 413.50
where 4 represents a single space.
8
49
There is no input for this program. Output will consist of 10 lines each containing a pair of numbers,
each printed right justied in a eld of width 10 (as shown above).
Input
Input will be in two parts. The rst part will be a table of IDD and STD codes, localities and prices as
follows:
Code4Locality name$price in cents per minute
where 4 represents a space. Locality names are 25 characters or less. This section is terminated by a
line containing 6 zeroes (000000).
The second part contains the log and will consist of a series of lines, one for each call, containing the
number dialled and the duration. The le will be terminated a line containing a single #. The numbers
will not necessarily be tabulated, although there will be at least one space between them. Telephone
numbers will not be ambiguous.
Output
Output will consist of the called number, the country or area called, the subscriber's number, the
duration, the cost per minute and the total cost of the call, as shown below. Local calls are costed at
zero. If the number has an invalid code, list the area as \Unknown" and the cost as ?1:00.
Sample input
088925 Broadwood$81
03 Arrowtown$38
0061 Australia$140
000000
031526
22
0061853279 3
0889256287213 122
779760 1
002832769 5
#
Sample output
1
031526
0061853279
0889256287213
779760
002832769
17
51
56
Arrowtown
1526 22
Australia 853279
3
Broadwood 6287213 122
Local
779670
1
Unknown
5
62
69
0.38 8.36
1.40 4.20
0.81 98.82
0.00 0.00
-1.00
140 Bandwidth
Given a graph (V,E) where V is a set of nodes and E is a set of arcs in VxV, and an ordering on
the elements in V, then the bandwidth of a node v is dened as the maximum distance in the ordering
between v and any node to which it is connected in the graph. The bandwidth of the ordering is then
dened as the maximum of the individual bandwidths. For example, consider the following graph:
H
E
This can be ordered in many ways, two of which are illustrated below:
A-B-C-D-E-H-F-G
A-B-C-D-G-F-H-E
For these orderings, the bandwidths of the nodes (in order) are 6, 6, 1, 4, 1, 1, 6, 6 giving an ordering
bandwidth of 6, and 5, 3, 1, 4, 3, 5, 1, 4 giving an ordering bandwidth of 5.
Write a program that will nd the ordering of a graph that minimises the bandwidth.
Input
Input will consist of a series of graphs. Each graph will appear on a line by itself. The entire le will be
terminated by a line consisting of a single #. For each graph, the input will consist of a series of records
separated by `;'. Each record will consist of a node name (a single upper case character in the the range
`A' to `Z'), followed by a `:' and at least one of its neighbours. The graph will contain no more than 8
nodes.
Output
Output will consist of one line for each graph, listing the ordering of the nodes followed by an arrow (->)
and the bandwidth for that ordering. All items must be separated from their neighbours by exactly one
space. If more than one ordering produces the same bandwidth, then choose the smallest in lexicographic
ordering, that is the one that would appear rst in an alphabetic listing.
Sample input
A:FB;B:GC;D:GC;F:AGH;E:HD
#
Sample output
A B C F G D H E -> 3
If the rst pattern had been produced earlier, then any of the following three patterns (plus one
other not shown) would terminate the game, whereas the last one would not.
Input will consist of a series of games, each consisting of the size of the board, N (2 N 50) followed,
on separate lines, by 2N moves, whether they are all necessary or not. Each move will consist of the
coordinates of a square (integers in the range 1..N) followed by a blank and a character `+' or `-' indicating
the addition or removal of a spot respectively. You may assume that all moves are legal, that is there
will never be an attempt to place a spot on an occupied square, nor to remove a non-existent spot. Input
will be terminated by a zero (0).
Output will consist of one line for each game indicating which player won and on which move, or
that the game ended in a draw.
Sample input
2
1
2
2
1
2
1
2
1
2
0
1
2
2
2
+
+
+
1
2
2
2
+
+
+
-
Sample output
Player 2 wins on move 3
Draw
1 b
C
8
2
4
d
7
3
5
c
6
A mouse click at `a' will select region A. A mouse click at `b' will select icon 1. A mouse click at
`c' will select icons 6 and 7. A mouse click at `d' is ambiguous. The ambiguity is resolved by assuming
that one region is in front of another. In the data les, later regions can be assumed to be in front of
earlier regions. Since regions are labelled in order of appearance (see later) `d' will select C. Note that
regions always overlap icons so that obscured icons need not be considered and that the origin (0,0) is
at the top left corner.
Write a program that will read in a series of region and icon denitions followed by a series of mouse
clicks and return the selected items. Coordinates will be given as pairs of integers in the range 0..499
and you can assume that all icons and regions lie wholly within the screen. Your program must number
all icons (even invisible ones) in the order of arrival starting from 1 and label regions alphabetically in
the order of arrival starting from `A'.
Input
Input will consist of a series of lines. Each line will identify the type of data: I for icon, R for region
and M for mouse click. There will be no separation between the specication part and the event part,
however no icon or region specications will follow the rst mouse click. An I will be followed by the
coordinates of the centre of the icon, R will be followed by the coordinates of the top left and bottom
right corners respectively and M will be followed by the coordinates of the cursor at the time of the click.
There will always be at least one visible icon and never more than 25 regions and 50 icons. The entire
le will be terminated by a line consisting of a single #.
Output
Output will consist of one line for each mouse click, containing the selection(s) for that click. Regions
will be identied by their single character identier, icon numbers will be written out right justied in a
eld of width 3, and where there is more than one icon number they will appear in increasing numerical
order.
Sample input
I
R
I
I
I
R
I
I
R
I
I
M
M
M
M
#
216
22
40
96
36
305
191
387
266
419
170
50
236
403
330
Sample output
A
C
1
6 7
28
19
150
138
193
13
184
200
63
134
102
50
30
167
83
170
102
425
103
370
140
Consider that we now overlay a series of triangles on to this grid. The vertices of the triangle can
have any real coordinates in the range 0.0 to 100.0, thus trees can have coordinates in the range 1 to 99.
Two possible triangles are shown.
Write a program that will determine how many trees are contained within a given triangle. For the
purposes of this problem, you may assume that the trees are of point size, and that any tree (point)
lying exactly on the border of a triangle is considered to be in the triangle.
Input will consist of a series of lines. Each line will contain 6 real numbers in the range 0.00 to 100.00
representing the coordinates of a triangle. The entire le will be terminated by a line containing 6 zeroes
(0 0 0 0 0 0).
Output will consist of one line for each triangle, containing the number of trees for that triangle right
justied in a eld of width 4.
Sample input
1.5 1.5 1.5 6.8 6.8 1.5
10.7 6.9 8.5 1.5 14.5 1.5
0 0 0 0 0 0
Sample output
15
17
Input will consist of a series of lines each containing a value for N and k as integers. The list will be
terminated by two zeroes (0 0).
Output will consist of a line for each line of input and will contain the list of students in the order in
which they leave the queue. Students are ordered according to their position in the queue at the start
of the day. All numbers must be right justied in a eld of width 3.
Sample input
5 3
0 0
Sample output
1 3 5 2 4
Input lines will consist of the charging step (upper case letter 'A'..'E'), the number called (a string of
7 digits and a hyphen in the approved format) and the start and end times of the call, all separated
by exactly one blank. Times are recorded as hours and minutes in the 24 hour clock, separated by one
blank and with two digits for each number. Input will be terminated by a line consisting of a single #.
Output will consist of the called number, the time in minutes the call spent in each of the charge
categories, the charging step and the total cost in the format shown below.
Sample input
A 183-5724 17 58 18 04
#
Sample output
10
183-5724
16
22
28
31
39
0.44
146 ID Codes
It is 2084 and the year of Big Brother has nally arrived, albeit a century late. In order to exercise greater
control over its citizens and thereby to counter a chronic breakdown in law and order, the Government
decides on a radical measure|all citizens are to have a tiny microcomputer surgically implanted in their
left wrists. This computer will contains all sorts of personal information as well as a transmitter which
will allow people's movements to be logged and monitored by a central computer. (A desirable side
eect of this process is that it will shorten the dole queue for plastic surgeons.)
An essential component of each computer will be a unique identication code, consisting of up to
50 characters drawn from the 26 lower case letters. The set of characters for any given code is chosen
somewhat haphazardly. The complicated way in which the code is imprinted into the chip makes it much
easier for the manufacturer to produce codes which are rearrangements of other codes than to produce
new codes with a dierent selection of letters. Thus, once a set of letters has been chosen all possible
codes derivable from it are used before changing the set.
For example, suppose it is decided that a code will contain exactly 3 occurrences of `a', 2 of `b' and
1 of `c', then three of the allowable 60 codes under these conditions are:
abaabc
abaacb
ababac
These three codes are listed from top to bottom in alphabetic order. Among all codes generated with
this set of characters, these codes appear consecutively in this order.
Write a program to assist in the issuing of these identication codes. Your program will accept a
sequence of no more than 50 lower case letters (which may contain repeated characters) and print the
successor code if one exists or the message `No Successor' if the given code is the last in the sequence
for that set of characters.
Input will consist of a series of lines each containing a string representing a code. The entire le will be
terminated by a line consisting of a single #.
Output will consist of one line for each code read containing the successor code or the words `No
Successor'.
Sample input
abaacb
cbbaa
#
Sample output
ababac
No Successor
147 Dollars
New Zealand currency consists of $100, $50, $20, $10, and $5 notes and $2, $1, 50c, 20c, 10c and 5c
coins. Write a program that will determine, for any given amount, in how many ways that amount may
be made up. Changing the order of listing does not increase the count. Thus 20c may be made up in 4
ways: 120c, 210c, 10c+25c, and 45c.
Input
Input will consist of a series of real numbers no greater than $50.00 each on a separate line. Each amount
will be valid, that is will be a multiple of 5c. The le will be terminated by a line containing zero (0.00).
Output
Output will consist of a line for each of the amounts in the input, each line consisting of the amount
of money (with two decimal places and right justied in a eld of width 5), followed by the number of
ways in which that amount may be made up, right justied in a eld of width 12.
Sample input
0.20
2.00
0.00
Sample output
0.20
2.00
4
293
Input
Input will consist of two parts. The rst part is the dictionary, the second part is the set of phrases for
which you need to nd anagrams. Each part of the le will be terminated by a line consisting of a single
#. The dictionary will be in alphabetic order and will contain up to 2000 words, one word per line. The
entire le will be in upper case, and no dictionary word or phrase will contain more than 20 letters. You
cannot assume the language being used is English.
Output
Output will consist of a series of lines. Each line will consist of the original phrase, a space, an equal
sign (=), another space, and the list of words that together make up an anagram of the original phrase,
separated by exactly one space. These words must appear in alphabetic sequence.
Sample input
ABC
AND
DEF
DXZ
K
KX
LJSRT
LT
PT
PTYYWQ
Y
YWJSRQ
ZD
ZZXY
#
ZZXY ABC DEF
SXZYTWQP KLJ YRTD
ZZXY YWJSRQ PTYYWQ ZZXY
#
Sample output
SXZYTWQP
SXZYTWQP
SXZYTWQP
SXZYTWQP
KLJ
KLJ
KLJ
KLJ
YRTD
YRTD
YRTD
YRTD
=
=
=
=
149 Forests
The saying \You can't see the wood for the trees" is not only a cliche, but is also incorrect. The real
problem is that you can't see the trees for the wood. If you stand in the middle of a \wood" (in NZ
terms, a patch of bush), the trees tend to obscure each other and the number of distinct trees you can
actually see is quite small. This is especially true if the trees are planted in rows and columns (as in a
pine plantation), because they tend to line up. The purpose of this problem is to nd how many distinct
trees you can see from an arbitrary point in a pine plantation (assumed to stretch \for ever").
You can only see a distinct tree if no part of its trunk is obscured by a nearer tree|that is if both
sides of the trunk can be seen, with a discernible gap between them and the trunks of all trees closer
to you. Also, you can't see a tree if it is apparently \too small". For deniteness, \not too small" and
\discernible gap" will mean that the angle subtended at your eye is greater than 0.01 degrees (you are
assumed to use one eye for observing). Thus the two trees marked obscure at least the trees marked
from the given view point.
Write a program that will determine the number of trees visible under these assumptions, given the
diameter of the trees, and the coordinates of a viewing position. Because the grid is innite, the origin
is unimportant, and the coordinates will be numbers between 0 and 1.
Input
Input will consist of a series of lines, each line containing three real numbers of the form 0.nn. The rst
number will be the trunk diameter|all trees will be assumed to be cylinders of exactly this diameter,
with their centres placed exactly on the points of a rectangular grid with a spacing of one unit. The
next two numbers will be the x and y coordinates of the observer. To avoid potential problems, say by
being too close to a tree, we will guarantee that diameter x; y (1 ? diameter). To avoid problems
with trees being too small you may assume that diameter 0:1. The le will be terminated by a line
consisting of three zeroes.
Output
Output will consist of a series of lines, one for each line of the input. Each line will consist of the number
of trees of the given size, visible from the given position.
Sample input
0.10 0.46 0.38
0 0 0
Sample output
124
Input
Input will consist of a series of lines, each line containing a day and date (such as Friday 25 December
1992). Dates will be in the range 1 January 1600 to 31 December 2099, although converted dates may
lie outside this range. Note that all names of days and months will be in the style shown, that is the
rst letter will be capitalised with the rest lower case. The le will be terminated by a line containing a
single `#'.
Output
Output will consist of a series of lines, one for each line of the input. Each line will consist of a date
in the other style. Use the format and spacing shown in the example and described above. Note that
there must be exactly one space between each pair of elds. To distinguish between the styles, dates in
the old style must have an asterisk (`*') immediately after the day of the month (with no intervening
space). Note that this will not apply to the input.
Sample input
Saturday 29 August 1992
Saturday 16 August 1992
Wednesday 19 December 1991
Monday 1 January 1900
#
Sample output
Saturday 16* August 1992
Saturday 29 August 1992
Wednesday 1 January 1992
Monday 20* December 1899
Input will consist of a series of lines, each line containing the number of regions (N ) with 13 N < 100.
The le will be terminated by a line consisting of a single 0.
Output will consist of a series of lines, one for each line of the input. Each line will consist of the
number m according to the above scheme.
Sample input
17
0
Sample output
7
Tree's a Crowd
Dr William Larch, noted plant psychologist and inventor of the phrase \Think like a tree|Think Fig"
has invented a new classication system for trees. This is a complicated system involving a series of
measurements which are then combined to produce three numbers (in the range [0, 255]) for any given
tree. Thus each tree can be thought of as occupying a point in a 3-dimensional space. Because of the
nature of the process, measurements for a large sample of trees are likely to be spread fairly uniformly
throughout the whole of the available space. However Dr Larch is convinced that there are relationships
to be found between close neighbours in this space. To test this hypothesis, he needs a histogram of the
numbers of trees that have closest neighbours that lie within certain distance ranges.
Write a program that will read in the parameters of up to 5000 trees and determine how many of
them have closest neighbours that are less than 1 unit away, how many with closest neighbours 1 or more
but less than 2 units away, and so on up to those with closest neighbours 9 or more but less than 10 units
away. Thus if d is the distance between the i'th point and its nearest neighbour(s) and j d < k, with
j and k integers and k = j + 1, then this point (tree) will contribute 1 to the j'th bin in the histogram
(counting from zero). For example, if there were only two points 1.414 units apart, then the histogram
would be 0, 2, 0, 0, 0, 0, 0, 0, 0, 0.
i
Input will consist of a series of lines, each line consisting of 3 numbers in the range [0, 255]. The le will
be terminated by a line consisting of three zeroes.
Output will consist of a single line containing the 10 numbers representing the desired counts, each
number right justied in a eld of width 4.
Sample input
10 10
10 10
10 10
10 10
10 10
10 10
10 10
10 10
10 10
10 10
10 10
0 0 0
0
0
1
3
6
10
15
21
28
36
45
Sample output
2
153 Permalex
Given a string of characters, we can permute the individual characters to make new strings. If we
can impose an ordering on the characters (say alphabetic sequence), then the strings themselves can
be ordered and any given permutation can be given a unique number designating its position in that
ordering. For example the string `acab' gives rise to the following 12 distinct permutations:
aabc
aacb
abac
abca
1
2
3
4
acab
acba
baac
baca
5
6
7
8
bcaa 9
caab 10
caba 11
cbaa 12
Input will consist of a series of lines, each line containing one string. Each string will consist of up to 30
lower case letters, not necessarily distinct. The le will be terminated by a line consisting of a single #.
Output will consist of a series of lines, one for each line of the input. Each line will consist of the
position of the string in its sequence, right justied in a eld of width 10.
Sample input
bacaa
abc
cba
#
Sample output
15
1
6
154 Recycling
Kerbside recycling has come to New Zealand, and every city from Auckland to Invercargill has leapt on
to the band wagon. The bins come in 5 dierent colours|red, orange, yellow, green and blue|and 5
wastes have been identied for recycling|Plastic, Glass, Aluminium, Steel, and Newspaper. Obviously
there has been no coordination between cities, so each city has allocated wastes to bins in an arbitrary
fashion. Now that the government has solved the minor problems of today (such as reorganising Health,
Welfare and Education), they are looking around for further challenges. The Minister for Environmental
Doodads wishes to introduce the \Regularisation of Allocation of Solid Waste to Bin Colour Bill" to
Parliament, but in order to do so needs to determine an allocation of his own. Being a rm believer
in democracy (well some of the time anyway), he surveys all the cities that are using this recycling
method. From these data he wishes to determine the city whose allocation scheme (if imposed on the
rest of the country) would cause the least impact, that is would cause the smallest number of changes
in the allocations of the other cities. Note that the sizes of the cities is not an issue, after all this is a
democracy with the slogan \One City, One Vote".
Write a program that will read in a series of allocations of wastes to bins and determine which city's
allocation scheme should be chosen. Note that there will always be a clear winner.
Input will consist of a series of blocks. Each block will consist of a series of lines and each line will
contain a series of allocations in the form shown in the example. There may be up to 100 cities in a
block. Each block will be terminated by a line starting with `e'. The entire le will be terminated by a
line consisting of a single #.
Output will consist of a series of lines, one for each block in the input. Each line will consist of the
number of the city that should be adopted as a national example.
Sample input
r/P,o/G,y/S,g/A,b/N
r/G,o/P,y/S,g/A,b/N
r/P,y/S,o/G,g/N,b/A
r/P,o/S,y/A,g/G,b/N
e
r/G,o/P,y/S,g/A,b/N
r/P,y/S,o/G,g/N,b/A
r/P,o/S,y/A,g/G,b/N
r/P,o/G,y/S,g/A,b/N
ecclesiastical
#
Sample output
1
4
Write a program that will read in a value of k and the coordinates of a point, and will determine
how many squares surround the point.
Input will consist of a series of lines. Each line will consist of a value of k and the coordinates of a point.
The le will be terminated by a line consisting of three zeroes (0 0 0).
Output will consist of a series of lines, one for each line of the input. Each line will consist of the
number of squares containing the specied point, right justied in a eld of width 3.
Sample input
500 113 941
0 0 0
Sample output
5
156 Ananagrams
Most crossword puzzle fans are used to anagrams|groups of words with the same letters in dierent
orders|for example OPTS, SPOT, STOP, POTS and POST. Some words however do not have this
attribute, no matter how you rearrange their letters, you cannot form another word. Such words are
called ananagrams, an example is QUIZ.
Obviously such denitions depend on the domain within which we are working; you might think
that ATHENE is an ananagram, whereas any chemist would quickly produce ETHANE. One possible
domain would be the entire English language, but this could lead to some problems. One could restrict
the domain to, say, Music, in which case SCALE becomes a relative ananagram (LACES is not in the
same domain) but NOTE is not since it can produce TONE.
Write a program that will read in the dictionary of a restricted domain and determine the relative
ananagrams. Note that single letter words are, ipso facto, relative ananagrams since they cannot be
\rearranged" at all. The dictionary will contain no more than 1000 words.
Input
Input will consist of a series of lines. No line will be more than 80 characters long, but may contain any
number of words. Words consist of up to 20 upper and/or lower case letters, and will not be broken
across lines. Spaces may appear freely around words, and at least one space separates multiple words
on the same line. Note that words that contain the same letters but of diering case are considered to
be anagrams of each other, thus tIeD and EdiT are anagrams. The le will be terminated by a line
consisting of a single #.
Output
Output will consist of a series of lines. Each line will consist of a single word that is a relative ananagram
in the input dictionary. Words must be output in lexicographic (case-sensitive) order. There will always
be at least one relative ananagram.
Sample input
ladder came tape soon leader acme RIDE lone Dreis peat
ScAlE orb eye Rides dealer NotE derail LaCeS drIed
noel dire Disk mace Rob dries
#
Sample output
Disk
NotE
derail
drIed
eye
ladder
soon
c
x
Az/Bd
n
e
p
m
Ad/Db
Dc/Cc f
f
Bg/Cb
C
h
A common problem in such systems is nding a route between two stations. Once this has been done
we wish to nd the \best" route, where \best" means \shortest time".
Write a program that will read in details of such a system and then will nd the fastest routes
between given pairs of stations. You can assume that the trip between stations always takes 1 unit of
time and that changing between routes at a connecting station takes 3 units of time.
Input
Input will consist of two parts. The rst will consist of a description of a system, the second will consist
of pairs of stations. The description will start with a number between 1 and 26 indicating how many
routes there are in the system. This will be followed by that many lines, each describing a single route.
Each line will start with the route identier followed by a `:' followed by the stations along that route, in
order. Connections will be indicated by an `=' sign followed by the complete alternative designation. All
connections will be identied at least once, and if there are more than two lines meeting at a connection,
some or of all the alternative designations may be identied together. That is, there may be sequences
such as `: : : hc=Bg=Cc=Abd: : : '. If the route forms a loop then the last station will be the same as the
rst. This is the only situation in which station letters will be repeated. The next portion of the input
le will consist of a sequence of lines each containing two stations written contiguously. The le will be
terminated by a line consisting of a single #.
Output
Output will consist of a series of lines, one for each pair of stations in the input. Each line will consist
of the time for the fastest route joining the two stations, right justied in a eld of width 3, followed by
a colon and a space and the sequence of stations representing the shortest journey. Follow the example
shown below. Note that there will always be only one fastest route for any given pair of stations and
that the route must start and nish at the named stations (not at any synonyms thereof), hence the
time for the route must include the time for any inter-station transfers.
The example input below refers to the diagram given above.
Sample input
4
A:fgmpnxzabjd=Dbf
D:b=Adac=Ccf
B:acd=Azefg=Cbh
C:bac
AgAa
AbBh
BhDf
#
Sample output
5: Agfdjba
9: Abaz=Bdefgh
10: Bhg=Cbac=Dcf
158 Calendar
Most of us have a calendar on which we scribble details of important events in our lives|visits to the
dentist, the Regent 24 hour book sale, Programming Contests and so on. However there are also the
xed dates: partner's birthdays, wedding anniversaries and the like; and we also need to keep track of
these. Typically we need to be reminded of when these important dates are approaching|the more
important the event, the further in advance we wish to have our memories jogged.
Write a program that will provide such a service. The input will specify the year for which the
calendar is relevant (in the range 1901 to 1999). Bear in mind that, within the range specied, all years
that are divisible by 4 are leap years and hence have an extra day (February 29th) added. The output
will specify \today's" date, a list of forthcoming events and an indication of their relative importance.
Input
The rst line of input will contain an integer representing the year (in the range 1901 to 1999). This
will be followed by a series of lines representing anniversaries or days for which the service is requested.
An anniversary line will consist of the letter `A'; three integer numbers (D; M; P ) representing the
date, the month and the importance of the event; and a string describing the event, all separated by one
or more spaces. P will be a number between 1 and 7 (both inclusive) and represents the number of days
before the event that the reminder service should start. The string describing the event will always be
present and will start at the rst non-blank character after the priority.
A date line will consist of the letter `D' and the date and month as above.
All anniversary lines will precede any date lines. No line will be longer than 255 characters in total.
The le will be terminated by a line consisting of a single #.
Output
Output will consist of a series of blocks of lines, one for each date line in the input. Each block will
consist of the requested date followed by the list of events for that day and as many following days as
necessary.
The output should specify the date of the event (D and M ), right justied in elds of width 3, and
the relative importance of the event. Events that happen today should be
agged as shown below, events
that happen tomorrow should have P stars, events that happen the day after tomorrow should have P-1
stars, and so on. If several events are scheduled for the same day, order them by relative importance
(number of stars).
If there is still a con
ict, order them by their appearance in the input stream. Follow the format
used in the example below. Leave 1 blank line between blocks.
Sample input
1993
A 23
A 25
A 20
D 20
#
12 5 Partner's birthday
12 7
Christmas
12 1 Unspecified Anniversary
12
Sample output
Today is: 20 12
20 12 *TODAY* Unspecified Anniversary
23 12 ***
Partner's birthday
25 12 ***
Christmas
Input
Input will consist of a series of lines, each line containing four words (two pairs). A word consists of 1
to 10 upper case letters, and will be separated from its neighbours by at least one space. The le will
be terminated by a line consisting of a single #.
Output
Output will consist of a series of double leading word crosses as dened above. Leave exactly three spaces
between the horizontal words. If it is not possible to form both crosses, write the message `Unable to
make two crosses'. Leave 1 blank line between output sets.
Sample input
MATCHES CHEESECAKE PICNIC EXCUSES
PEANUT BANANA VACUUM GREEDY
#
Sample output
C
H
E
E
S
E
C
MATCHES
K
E
E
X
PICNIC
U
S
E
S
N ! = N (N ? 1)!
Factorials grow very rapidly|5! = 120, 10! = 3,628,800. One way of specifying such large numbers
is by specifying the number of times each prime number occurs in it, thus 825 could be specied as (0 1
2 0 1) meaning no twos, 1 three, 2 ves, no sevens and 1 eleven.
Write a program that will read in a number N (2 N 100) and write out its factorial in terms of
the numbers of the primes it contains.
Input
Input will consist of a series of lines, each line containing a single integer N . The le will be terminated
by a line consisting of a single 0.
Output
Output will consist of a series of blocks of lines, one block for each line of the input. Each block will
start with the number N, right justied in a eld of width 3, and the chracters `!', space, and `='. This
will be followed by a list of the number of times each prime number occurs in N !.
These should be right justied in elds of width 3 and each line (except the last of a block, which
may be shorter) should contain fteen numbers. Any lines after the rst should be indented. Follow the
layout of the example shown below exactly.
Sample input
5
53
0
Sample output
5! = 3 1 1
53! = 49 23 12 8 4 4 3 2 2 1 1 1 1 1 1
1
Input
Input will consist of a series of scenarios. Data for each scenario will consist of a series of integers
representing the cycle times of the trac lights, possibly spread over many lines, with no line being
longer than 100 characters. Each number represents the cycle time of a single signal. The cycle time is
the time that trac may move in one direction; note that the last 5 seconds of a green cycle is actually
orange. Thus the number 25 means a signal that (for a particular direction) will spend 20 seconds green,
5 seconds orange and 25 seconds red. Cycle times will not be less than 10 seconds, nor more than 90
seconds. There will always be at least two signals in a scenario and never more than 100. Each scenario
will be terminated by a zero (0). The le will be terminated by a line consisting of three zeroes (0 0 0).
Output
Output will consist of a series of lines, one for each scenario in the input. Each line will consist of the
time in hours, minutes and seconds that it takes for all the signals to show green again after at least
one of them changes to orange. Follow the format shown in the examples. Time is measured from the
instant they all turn green simultaneously. If it takes more than ve hours before they all show green
simultaneously, the message \Signals fail to synchronise in 5 hours" should be written instead.
Sample input
19 20
30
25
0 0 0
0
35 0
Sample output
00:00:40
00:05:00
Input
Input will consist of a series of decks of cards. Each deck will give the cards in order as they would be
dealt (that is in the example deck below, the non-dealer would start the game by playing the H2). Decks
will occupy 4 lines with 13 cards on each. The designation of each card will be the suit (S, H, D, C)
followed by the rank (A, 2{9, T, J, Q, K). There will be exactly one space between cards. The le will
be terminated by a line consisting of a single #.
Output
Output will consist of a series of lines, one for each deck in the input. Each line will consist of the
number of the winning player (1 is the dealer, 2 is the rst to play) and the number of cards in the
winner's hand (ignoring any on the stack), right justied in a eld of width 3.
Sample input
HA
D4
S8
H9
#
H3
D7
D8
DA
H4
SJ
C2
SA
CA
DT
S2
CK
SK
H6
S3
CQ
S5
S9
C7
C3
Sample output
1 44
C5
CT
H5
HT
S6
HK
DJ
SQ
C4
C8
S4
H8
D5
C9
DQ
S7
H7
D6
DK
ST
HJ
CJ
D9
H2
HQ
C6
D3
D2
A5W
A4W
A3W
A2W
A1W
S6N
S5N
A6W
North
S4N
S3N
Avenue 0
S2N
S1N
Street 0
The roads marked in grey are considered to be throughways. These are elevated for most of their
length, thus it is possible to cross them easily, however they always intersect each other at a circle, which
is shared by all other roads that meet at that intersection. You may only enter or leave them by turning
left (sharp left in the case of boulevards). You may not stop on them for any reason. There are no
restrictions on turns for other roads.
This system allows a very simple method of determining one's current position and a way of arriving
at one's destination. Position can be specied in terms of the last intersection you passed through
(the numbers of the Avenue and Street that meet there) and your current heading, which can be one of:
north (N), northeast (NE), east (E), southeast (SE), south (S), southwest (SW), west (W) and northwest
(NW). Directions can then be given in terms of how many intersections to pass through and which turns
to make. However, the locals have an infuriating habit of giving incorrect or invalid directions, although
it cannot be determined whether this is deliberate or accidental. Directions should (but don't always)
conform to the following simple grammar:
Input
Output
Output will consist of a series of lines, one for each scenario. Each line will consist of a position and a
heading in the same format as the input. If the nal stopping place is illegal, report `Illegal stopping
place' as the answer.
Sample input
A2W S1N E
TURN SHARP LEFT
GO 1
TURN RIGHT
TURN LEFT
TURN SHARP LEFT
GO 1
TURN LEFT
STOP
A2W S1N W
GO STRAIGHT 2
TURN LEFT
GO ON 2
TURN HALF LEFT
TURN LEFT
GO 2
STOP
END
Sample output
A3W S1N E
Illegal stopping place
abcde
bcde
bcge
bcgfe
bcgfe
Write a program that will read in two strings (the input string and the target string) and will
produce a minimal X9091 program necessary to transform the input string into the target string. Since
there may be multiple solutions, only one should be produced. Any solution that satises these criteria
will be accepted.
Input will consist of a series of lines, each line containing two strings separated by exactly one space.
The strings will consist of no more than 20 lower case characters. The le will be terminated by a line
consisting of a single #.
Output will consist of a series of lines, one for each line of the input. Each will consist of a program
in X9091 language.
Sample input
abcde bcgfe
#
Sample output
Da01Cg03If04E
165 Stamps
The government of Nova Mareterrania requires that various legal documents have stamps attached to
them so that the government can derive revenue from them. In terms of recent legislation, each class
of document is limited in the number of stamps that may be attached to it. The government wishes to
know how many dierent stamps, and of what values, they need to print to allow the widest choice of
values to be made up under these conditions. Stamps are always valued in units of $1.
This has been analysed by government mathematicians who have derived a formula for n(h; k), where
h is the number of stamps that may be attached to a document, k is the number of denominations of
stamps available, and n is the largest attainable value in a continuous sequence starting from $1. For
instance, if h = 3; k = 2 and the denominations are $1 and $4, we can make all the values from $1 to $6
(as well as $8, $9 and $12). However with the same values of h and k, but using $1 and $3 stamps we
can make all the values from $1 to $7 (as well as $9). This is maximal, so n(3; 2) = 7.
Unfortunately the formula relating n(h; k) to h; k and the values of the stamps has been lost|it
was published in one of the government reports but no-one can remember which one, and of the three
researchers who started to search for the formula, two died of boredom and the third took a job as a
lighthouse keeper because it provided more social stimulation.
The task has now been passed on to you. You doubt the existence of a formula in the rst place
so you decide to write a program that, for given values of h and k, will determine an optimum set of
stamps and the value of n(h; k).
Input
Input will consist of several lines, each containing a value for h and k. The le will be terminated by
two zeroes (0 0). For technical reasons the sum of h and k is limited to 9. (The President lost his little
nger in a shooting accident and cannot count past 9).
Output
Output will consist of a line for each value of h and k consisting of the k stamp values in ascending order
right justied in elds 3 characters wide, followed by a space and an arrow (->) and the value of n(h; k)
right justied in a eld 3 characters wide.
Sample input
3 2
0 0
Sample output
1 3 -> 7
Input
Input will consist of a series of lines, each line dening a dierent situation. Each line will consist of 6
integers representing the numbers of coins available to you in the order given above, followed by a real
number representing the value of the transaction, which will always be less than $5.00. The le will be
terminated by six zeroes (0 0 0 0 0 0). The total value of the coins will always be sucient to make up
the amount and the amount will always be achievable, that is it will always be a multiple of 5c.
Output
Output will consist of a series of lines, one for each situation dened in the input. Each line will consist
of the minimum number of coins that change hands right justied in a eld 3 characters wide.
Sample input
2 4 2 2 1 0 0.95
2 4 2 0 1 0 0.55
0 0 0 0 0 0
Sample output
2
3
The Sultan of Nubia has no children, so she has decided that the country will be split into up to k
separate parts on her death and each part will be inherited by whoever performs best at some test. It
is possible for any individual to inherit more than one or indeed all of the portions. To ensure that only
highly intelligent people eventually become her successors, the Sultan has devised an ingenious test.
In a large hall lled with the splash of fountains and the delicate scent of incense have been placed k
chessboards. Each chessboard has numbers in the range 1 to 99 written on each square and is supplied
with 8 jewelled chess queens. The task facing each potential successor is to place the 8 queens on the
chess board in such a way that no queen threatens another one, and so that the numbers on the squares
thus selected sum to a number at least as high as one already chosen by the Sultan. (For those unfamiliar
with the rules of chess, this implies that each row and column of the board contains exactly one queen,
and each diagonal contains no more than one.)
Write a program that will read in the number and details of the chessboards and determine the
highest scores possible for each board under these conditions. (You know that the Sultan is both a good
chess player and a good mathematician and you suspect that her score is the best attainable.)
Input
Input will consist of k (the number of boards), on a line by itself, followed by k sets of 64 numbers,
each set consisting of eight lines of eight numbers. Each number will be a positive integer less than 100.
There will never be more than 20 boards.
Output
Output will consist of k numbers consisting of your k scores, each score on a line by itself and right
justied in a eld 5 characters wide.
Sample input
1
1
9
17
25
33
41
48
57
2
10
18
26
34
42
50
58
3
11
19
27
35
43
51
59
4
12
20
28
36
44
52
60
5
13
21
29
37
45
53
61
6
14
22
30
38
46
54
62
Sample output
260
7
15
23
31
39
47
55
63
8
16
24
32
40
48
56
64
Assume that Theseus is in cavern C when he hears the Minotaur approaching from A, and that for
this scenario, the value of k is 3. He lights a candle and gives chase, pursuing it through A, B, D (leaves
a candle), G, E, F (another candle), H, E, G (another), H, E (trapped).
Write a program that will simulate Theseus's pursuit of the Minotaur. The description of a labyrinth
will identify each cavern by an upper case character and will list the caverns reachable from that cavern
in the order that the Minotaur will attempt them, followed by the identiers for the caverns which the
Minotaur and Theseus were in when contact was rst made, followed by the value of k.
Input
Input will consist of a series of lines. Each line will describe a scenario in the format shown below (which
describes the above example). No line will contain more than 255 characters. The le will be terminated
by a line consisting of a single #.
Output
Output will consist of one line for each Labyrinth. Each line will identify the lit caverns, in the order
in which the candles were left, and the cavern in which the Minotaur was trapped, following the format
Sample input
A:BCD;B:AD;D:BG;F:H;G:DEH;E:FGH;H:EG;C:AD. A C 3
#
Sample output
D F G /E
169 Xenosemantics
Contact with extra-terrestrial intelligence has been made at last!! A stream of messages has been discovered, apparently emanating from Procyon IV. After intensive study by the world's best xenosemanticists,
the following denite conclusions on the format of the messages have been reached. The messages are
streams of bits divided into groups of 8. Somewhat coincidentally the meaningful parts of the message
map onto the lower case alphabet, although other characters sometimes intervene. Letters are organised
into words separated by spacer letters. The spacer letter varies within a message, but a word which
is delimited by a particular spacer pair does not contain that spacer letter within it. In addition the
message is conceptually bounded by a pair of `joker' letters or `wild spacers' that can match any letter.
For example, a message segment xwrxwtx contains 3 words|wr, wt, and rx; wrxwt is not a word in this
segment of the message. If this segment appeared at the start of a message then xw and xwrxw could also
be words. The words wr and rx overlap, while wt does not overlap any words in this message segment.
While a word contains the same letters each time it appears in one message, the order of the letters may
vary in dierent occurrences of the same word. Each message contains many words which are not \true"
words in that they carry no meaning (like err.., umm.., etc in English). Every true word in the message
contains at least two and no more than 250 letters, overlaps with another true word, and is repeated
somewhere in the message (possibly with the letters in a dierent order). In the example above, wr and
rx would both be true words if wr or rw, and rx or xr, occurred as words elsewhere in the message. The
word wt would be a true word if wt or tw occurred elsewhere in the message, overlapping another true
word.
Write a program that will read in messages and print out a list of the dierent true words contained in
each message (using the spelling which occurs rst), in the order the words rst appear in the message. If
the rst appearances of two words overlap, then the word that nishes rst precedes the other. Remember
that both the start and the end of the message count as spacer letters. Your program must be able to
process messages of up to 1000 letters.
Input
Input will consist of one or more messages. Each message will consist of one or more lines. Each line will
be no more than 60 characters long and will contain a mixture of lower case letters and other characters.
If the last character of a line is a dash (-) then the message continues on the next line. All characters
other than lower case `a' to `z' form no part of the message. The le will be terminated by a line
consisting of a single #.
Output
Output will consist of the true words for each message, in the correct order as specied above, one word
per line. Terminate the list for each message by a line consisting of a single *.
Sample input
dyj@ttdi%sdort^jdyt*rFnn trlnsvkGHoalexotrjxzasvsozgpsi<>:pkelaovo,.;'slnxt'][-prsjlntrjo
aaaaaaa
#
Sample output
dyj
ortj
lnsvkoalexot
*
*
J QA
2
T
9 K 3
8
4
7 6 5
The game then starts. The top card of the `king' pile (the last card dealt) is exposed to become
the current card. Each move thereafter consists of placing the current card face up beneath the pile
corresponding to its value and exposing the top card of that pile as the new current card. Thus if the
current card is an Ace it is placed under the `one' pile and the top card of that pile becomes the current
card. The game ends when the pile indicated by the current card has no face down cards in it. You win
if the entire deck is played out, i.e. exposed."
Write a program that will read in a number of shued decks, and play the game.
The input will consist of decks of cards arranged in four lines of 13 cards, cards separated by a single
blank. Each card is represented by two characters, the rst is the rank (A, 2, 3, 4, 5, 6, 7, 8, 9, T, J,
Q, K) followed by the suit (H, D, C, S). The input will be terminated by a line consisting of a single #.
The deck is listed from bottom to top, so the rst card dealt is the last card listed.
The output will consist of one line per deck. Each line will contain the number of cards exposed
during the game (2 digits, with a leading zero if necessary), a comma, and the last card exposed (in the
format used in the input).
Sample input
TS
9D
6D
AS
#
QC
JH
4S
7C
8S
7H
9S
AH
8D
JD
5S
6H
QH
2S
7S
KD
2D
QS
JS
JC
Sample output
44,KD
3H
TD
8H
7D
KH
2C
3D
AC
9H
4H
8C
5C
2H
5H
3S
TC
TH
AD
4C
QD
KS
4D
6S
6C
KC
5D
9C
3C
Input
Each input line will consist of not more than 75 characters. The input will be terminated by a line
consisting of a single #.
Output
The output will consist of a series of sequentially numbered lines, either containing the valid instruction,
or the text Trap! if the line did not obey the rules. The line number will be right justied in a eld of 3
characters, followed by a full-stop, a single space, and the instruction, with sequences of more than one
space reduced to single spaces.
Sample input
KEEP LEFT AND THEN GO RIGHT
CAS TO 20 KMH
GO FIRST
RIGHT AT "SMITH ST." AND
GO 2nd RIGHT
GO LEFT AT "SMITH STREET AND RECORD TIME
KEEP RIGHT AND THEN RECORD TIME
#
CAS TO 20 KMH
Sample output
1.
2.
3.
4.
5.
6.
Input
Input will consist of a series of lines, each line containing a correct CL expression. No line will be longer
than 100 characters. The le will be terminated by a line consisting of a single #.
Output
Output will consist of a series of lines, one for each line of the input. Each line will consist of a list of
the nal values of all variables whose value changes as a result of the evaluation of that expression. If
more than one variable changes value, they should be listed in alphabetical order, separated by commas.
If a variable changes value more than once in an expression, only the nal value is output. A variable is
said to change value if its value after the expression has been evaluated is dierent from its value before
the expression was evaluated. If no variables change value, then print the message `No Change'. Follow
the format shown below exactly.
Sample input
A
C
C
F
E
Z
#
=
=
=
=
=
=
B = 4
(D = 2)*_2
D = 2 * _2
C - D
D * _10
10 / 3
Sample output
A = 4, B = 4
C = -4, D = 2
D = -4
No Change
E = 40
Z = 3
Input
Input will consist of a series of lines. Each line will describe a network and indicate the starting nodes
for the two programs. A network is described as a series of nodes separated by `;' and terminated by a
period (`.'). Each node is described by its identier, a `:' and one or more of the nodes connected to it.
Each link will be mentioned at least once, as will each node, although not all nodes will be `described'.
After the period will appear the labels of the starting nodes|rst Paskill and then Lisper. No line will
contain more than 255 characters. The le will be terminated by a line consisting of a single #.
Output
Output will consist of one line for each network. Each line will specify the terminating event and the
node where it occurs. The terminating event is one or two of the following:
trapped in node ?
Both annihilated in node ?
Sample input
A:BD;C:BD;F:E;G:DEH;H:EG. A H
E:AB. A B
B:ACD. B D
A:B;B:C;D:E. A D
#
Sample output
Paskill trapped in node D Lisper trapped in node F
Both annihilated in node E
Lisper destroyed in node B
Lisper trapped in node E
174 Strategy
A well known psychology experiment involves people playing a game in which they can either trade with
each other or attempt to cheat the other player. If both players TRADE then each gains one point. If
one TRADEs and the other CHEATs then the TRADEr loses 2 points and the CHEATer wins 2. If
both CHEAT then each loses 1 point.
There are a variety of dierent strategies for playing this game, although most people are either
unable to nd a winning strategy, or, having decided on a strategy, do not stick to it. Thus it is fairer
to attempt to evaluate these strategies by simulation on a computer. Each strategy is simulated by
an automaton. An automaton is characterised by a program incorporating the strategy, a memory for
previous encounters and a count re
ecting the score of that automaton. The count starts at zero and
is altered according to the above rules after each encounter. The memory is able to determine what
happened on up to the last two encounters with each other contender.
Write a program that will read in details of up to 10 dierent strategies, play each strategy against
each other strategy 10 times and then print out the nal scores. Strategies will be in the form of simple
programs obeying the following grammar:
Input
Input will consist of a series of programs. Each program will be no longer than 255 characters and may
be split over several lines for convenience. There will be no more than 10 programs. The le will be
terminated by a line containing only a single `#'.
Output
Output will consist of one line for each line of input. Each line will consist of the nal score of the
relevant program right justied in a eld of width 3.
Sample input
CHEAT.
IF MY LAST1 = CHEAT THEN TRADE ELSE CHEAT.
IFYOURLAST2=NULLTHENTRADEELSEIFYOURLAST1=TRADETHENTRADE
ELSECHEAT.
#
Sample output
1
-12
-13
175 Keywords
Many researchers are faced with an ever increasing number of journal articles to read and nd it dicult
to locate papers of relevance to their particular lines of research. However, it is possible to subscribe
to various services which claim that they will nd articles that t an `interest prole' that you supply,
and pass them on to you. One simple way of performing such a search is to determine whether a pair of
keywords occurs `suciently' close to each other in the title of an article. The threshold is determined
by the researchers themselves, and refers to the number of words that may occur between the pair of
keywords. Thus an archeologist interested in cave paintings could specify her prole as \0 rock art",
meaning that she wants all titles in which the words \rock" and \art" appear with 0 words in between,
that is next to each other. This would select not only \Rock Art of the Maori" but also \Pop Art,
Rock, and the Art of Hang-glider Maintenance".
Write a program that will read in a series of proles followed by a series of titles and determine which
of the titles (if any) are selected by each of the proles. A title is selected by a prole if at least one
pair of keywords from the prole is found in the title, separated by no more than the given threshold.
For the purposes of this program, a word is a sequence of letters, preceded by one or more blanks and
terminated by a blank or the end of line marker.
Input
Input will consist of no more than 50 proles followed by no more than 250 titles. Each prole and
title will be numbered in the order of their appearance, starting from 1, although the numbers will not
appear in the le.
Each prole will start with the characters \P:", and will consist of a number representing a threshold, followed by two or more keywords in lower case.
Each title will start with the characters \T:", and will consist of a string of characters terminated
by \|". The character \|" will not occur anywhere in a title except at the end. No title will be
longer than 255 characters, and if necessary it will
ow on to more than one line. No line will
be longer than eighty characters and each continuation line of a title will start with at least one
blank. Line breaks will only occur between words.
All non-alphabetic characters are to be ignored, thus the title \Don't Rock --- the Boat as
Metaphor in 1984" would be treated as \Dont Rock the Boat as Metaphor in" and \HP2100X"
will be treated as \HPX". The le will be terminated by a line consisting of a single #.
Output
Output will consist of a series of lines, one for each prole in the input. Each line will consist of the
prole number (the number of its appearance in the input) followed by \:" and the numbers of the
selected titles in numerical order, separated by commas and with no spaces.
Sample input
P:
P:
P:
T:
T:
T:
0 rock art
3 concepts conceptions
1
art rock
metaphor concepts
Rock Art of the Maori|
Jazz and Rock - Art Brubeck and Elvis Presley|
Don't Rock --- the Boat as Metaphor in 1984, Concepts
and (Mis)-Conceptions of an Art Historian.|
T: Carved in Rock, The Art and Craft of making promises
believable when your `phone bills have gone
through the roof|
#
Sample output
1: 1,2
2:
3: 1,2,3,4
15th Street
12th
11th
10th
Avenues
E
S
16th Street
17th Street
99
01
18th Street
00
01
96
Avenue
97
98
99
Street
90
00
Quiet suburbs are formed by the simple expedient of making some Avenues and Streets discontinuous
as shown above. Note that Avenues and Streets keep the same name, even when there are places where
they simply don't exist. It is dicult to get lost in such a city, as the address tells you exactly where to
go. However, if you don't know the pattern of missing portions, you can spend a lot of time going into
dead-end roads.
Write a program that will rstly read in a description of the `missing' areas in a city and then a
series of pairs of addresses, where an address is assumed to specify a driveway not necessarily a residence.
For each pair of addresses the program must calculate the distance between them, by the shortest legal
route. The distance is the number of driveways you pass (on your side of the road) excluding the source
and destination. You may make the following assumptions:
Input
Input will be divided into two portions: a \missing road" portion and an address portion, each terminated
by a line consisting of a single `#'. The \missing road" portion consists of a series of lines with each line
containing a road identier and a pair of house numbers. A road identier is an `A' or an `S' (specifying
an Avenue or a Street) followed by a number in the range 00 to 49. A house number is an even number
in the range 0000 to 4898. The area between and including the specied numbers on the identied road
is inaccessible. Note that the line goes directly across the street, thus if number 1612 is inaccessible,
then so is 1613. Inaccessible portions run from the borders of sections not from driveways. There will
be exactly one space separating parts of the input.
The address portion consists of a series of lines each line containing two addresses. An address is a
road identier (as above) followed by a number in the range 0000 to 4899. There will be exactly one
space separating parts of the input.
Output
Output consists of a series of lines, one for each line in the address portion of the input le. Each line
contains the distance between the two houses specied in the input (the number of driveways passed)
written as an integer, left justied.
Note: The following sample data matches the diagram on previous page. (Note the intersection of A13
and S17).
Sample input
A11
A12
S16
S17
S17
#
S16
#
1612
1508
1152
1048
1272
1720
1636
1250
1134
1326
Sample output
213
Write a program to draw the curve which appears after N folds. The exact specication of the curve
is as follows:
The paper starts
at, with the \start edge" on the left, looking at it from above.
The right half is folded over so it lies on top of the left half, then the right half of the new double
sheet is folded on top of the left, to form a 4-thick sheet, and so on, for N folds.
Then every fold is opened from a 180 degree bend to a 90 degree bend.
Finally the bottom edge of the paper is viewed end-on to see the dragon curve.
From this view, the only unchanged part of the original paper is the piece containing the \start edge",
and this piece will be horizontal, with the \start edge" on the left. This uniquely denes the curve. In
the above picture, the \start edge" is the left end of the rightmost bottom horizontal piece (marked `s').
Horizontal pieces are to be displayed with the underscore character \ ", and vertical pieces with the \|"
character.
Input
Input will consist of a series of lines, each with a single number N (1 N 13). The end of the input
will be marked by a line containing a zero.
Output
Output will consist of a series of dragon curves, one for each value of N in the input. Your picture must
be shifted as far left, and as high as possible. Note that for large N , the picture will be greater than 80
characters wide, so it will look messy on the screen. The pattern for each dierent number of folds is
terminated by a line containing a single `^'.
Sample input
2
4
1
0
Sample output
|_
_|
^
_ _
|_|_| |_
_|
_|
|_|
^
_|
^
Input
Input will consist of a series of decks of cards, each deck specied as 4 lines each containing 13 cards.
Each card will be specied by two characters, a rank (A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K)
followed by a suit (S, H, C, D). Cards will be in the order in which they will be played. The le will
be terminated by a line consisting of a single #.
Output
Output will consist of a series of lines, one line for each deck in the input. Each line shall start with
the deck number, followed by a colon. If it is not possible to play a deck within the specied 4 4 grid,
then write a space followed by the message `Overflowed on card no' followed by the number of the
card about to be dealt. If it is possible to play the entire deck, then write out the non-zero numbers
that represent the numbers of cards in each pile when the deck is fully dealt.
All numbers are to be right justied in a eld 3 characters wide.
Sample input
TS
9D
6D
AS
#
QC
JH
4S
7C
8S
7H
9S
AH
8D
JD
5S
6H
QH
2S
7S
KD
2D
QS
JS
JC
3H
TD
8H
7D
KH
2C
3D
AC
9H
4H
8C
5C
2H
5H
3S
TC
TH
AD
4C
QD
KS
4D
6S
6C
KC
5D
9C
3C
Sample output
1: 8 6 7 4 3 5 4 4 2 5 4
Input
Input will consist of a series of (plaintext, cyphertext1, cyphertext2) triples. Lines will be no more than
80 characters long. The rst two strings (of length n) represent the rst n characters of the plaintext
and cyphertext. There is no implication that n is a multiple of k. The le will be terminated by a line
consisting of a single #.
Output
Output will consist of a series of lines, one for each triple in the input. If a permutation cycle has been
found, apply the inverse permutation to cyphertext2, padding it if necessary with `?'. If no periodic
permutation can be found (with period less than or equal to the length of the plain and cyphertext1
strings) that transforms the plaintext into the cyphertext, then print cyphertext2 unchanged. If more
than one periodic permutation could have mapped the plain text to the cyphertext1, then apply the
periodic permutation that has the smallest value for k. There will never be more than one shortest
permutation function that matches the data.
Sample input
Mary had a little lamb!!
aMyrh daa l tilt ealbm!!
hTsii s aetts
Foobar
blargg
No cycle
abc
bca
abcd
#
Sample output
This is a test
No cycle
cab?d?
Input
Input will consist of a series of lines, each line containing the upper and lower estimates of the number
of eligible people (both numbers inclusive). The le will be terminated by a line containing two zeroes
(0 0).
Output
Output will consist of a series of lines, one for each line of the input. Each line will consist of a single
number giving the number of the position closest to Mxgobgwq that will not be chosen as chief for
any number in the given range and for either direction of elimination. If no position is safe then print
"Better estimate needed".
Sample input
80 150
40 150
0 0
Sample output
1
Better estimate needed
181 Hearts
There are 52 playing cards in a pack, divided into suits, and, within suits, into denominations. The
suits are (in order, lowest to highest) Clubs, Diamonds, Hearts and Spades, abbreviated C, D, H and S.
The 13 denominations (or face values) are (from lowest to highest): 2, 3, 4, 5, 6, 7, 8, 9, 10 (T), Jack
(J), Queen (Q), King (K) and Ace(A). A higher card will beat a lower card in the same suit, but will
not usually beat any other card in a dierent suit. An exception to this is the `trump' suit|if a suit is
designated to be a trump suit (by whatever means the rules of the game allow), then any card of that
suit will beat any card of any other suit.
A simplied version of an old card game called Hearts is played as follows. The dealer deals cards
clockwise, one by one, face downward, to four other players and himself, starting with the player on
his left, who thus gets the rst card, followed by the sixth, and so on, while the dealer gets the fth
card, followed by the tenth, and so on. When each player has 10 cards there will be two left|these are
exposed and the suit of the one of higher denomination determines the trump suit. If there is a tie, then
the highest ranking suit becomes the trump suit.
A `game' consists of 10 `tricks', each containing 5 cards, one from each player. For each trick, one
player `leads', i.e. plays a card face up on the table, the rest of the players then `follow', in clockwise
order. The player to the dealer's left leads to the rst trick, thereafter the winner of each trick leads to
the next trick. A player must follow suit if possible, i.e. play a card of the same suit as the one lead.
If he cannot, then he must trump it (play a card of the designated trump suit). If he cannot trump it
(because he has no cards in the trump suit), he discards a card. If a trick is trumped, then the person
playing the highest trump wins the trick, otherwise the person playing the highest card of the correct
suit wins it.
Strategies are as follows:
1. Leader: The leader always plays the highest card in his hand. If there is a tie and one of the cards
is a trump card, then he leads the trump, otherwise he plays the highest ranking suit.
2. Follower: If possible he must play the highest card in his hand of the correct suit. If he has no
cards in that suit then he plays the highest trump he has. If he cannot trump it he plays the
highest card in his hand, breaking ties as previously specied.
When all the tricks have been played, each player examines the tricks he has taken and scores the
face value of any Heart he has (Jack counts 11, Queen counts 12, King counts 13 and Ace counts 14).
This score is recorded.
Write a program to simulate the playing of this game.
Input
Input will consist of a series of decks of cards, each deck spread over four lines as shown below. The le
will be terminated by a line consisting of a single #.
Output
Output will consist of a series of lines, one for each deck in the input. Each line will consist of 5 numbers
re
ecting the scores of the individual players, starting with the dealer and proceeding clockwise through
the rest of the players. Each score will consist of a number right justied in a eld of width 3.
Sample input
TS
9D
6D
AS
#
QC
JH
4S
7C
8S
7H
9S
AH
8D
JD
5S
6H
QH
2S
7S
KD
2D
QS
JS
JC
Sample output
22 0 68 0 14
3H
TD
8H
7D
KH
2C
3D
AC
9H
4H
8C
5C
2H
5H
3S
TC
TH
AD
4C
QD
KS
4D
6S
6C
KC
5D
9C
3C
Input
Input will consist of a series of lines, each line consisting of a ten digit number representing the next
bond number to be sold in a particular region and an integer in the range 1 to 10 representing the desired
character position. It is possible that some regions will appear more than once in the input stream, and
that others will not appear at all. The le will be terminated by a line consisting of 0000000000 0.
Output
Output will consist of a series of tables, one for each line of the input. Each table will consist of ten
rows, one for each digit in the range 0 to 9. Each row will consist of a single number giving the numbers
of times that digit appears in the sequence numbers at the desired position. Each number will be right
justied in a eld of width 11. Separate tables by one blank line.
Sample input
4810000000 1
0000000000 0
Sample output
100000000
100000000
100000000
100000000
80000000
0
0
0
0
0
Input
Input will consist of a series of bit maps. Each bit map begins with a line giving its format (\B" or \D")
and its dimensions (rows and columns). Neither dimension will be greater than 200. There will be at
least one space between each of the items of information. Following this line will be one or more lines
containing the sequence of \1", \0" and \D" characters that represent the bit map, with no intervening
spaces. Each line (except the last, which may be shorter) will contain 50 characters. A \B" type bitmap
will be written left to right, top to bottom. The le will be terminated by a line consisting of a single #.
Output
Output will consist of a series of bitmaps, one for each bit map of the input. Output of each bit map
begins on a new line and will be in the same format as the input. The width and height are to be output
right justied in elds of width four.
Sample input
B 3 4
001000011011
D 2 3
DD10111
#
Sample output
D 3 4
D0D1001D101
B 2 3
101111
Input
Input will consist of a series of data sets, each set containing the coordinates of between 3 and 300 points
(both inclusive). Each set will start on a new line.
The coordinates will be pairs of integers in the range 0 to 9999 and each set will be terminated by a
pair of zeroes (0 0). Successive numbers will be separated by one or more spaces; in addition a data set
may be split into several lines, such splits will only occur between coordinate pairs and never between
the elements of a coordinate pair. The entire le will also be terminated by a pair of zeroes (0 0).
Note that there will be several test cases, but only one will contain more than 100 points.
Output
Output, for each set, is either the message "No lines were found", or the message "The following
lines were found:", followed by the sets of points lying on straight lines, each set ordered rst by x,
and if the x's are equal, then by y .
All coordinates are in a eld of width 4, and are separated by a comma; the points are delimited
by brackets, with no spaces between successive points. The lines themselves are ordered in a similar
manner to the points on each line; i.e. by considering the rst point on each line, and if more than one
line starts at that point, by considering the second point on the line.
Sample input
5 5 8 7 14 11 4 8 20 15
12 6 18 21 0 0
5 5 8 8 14 13 0 0
5 5 25 17 20 23 10 11 20 14 15 11 0 0
0 0
Sample output
The following
( 4, 8)(
( 5, 5)(
( 12, 6)(
No lines were
The following
( 5, 5)(
( 5, 5)(
lines were
8, 7)(
8, 7)(
14, 11)(
found
lines were
10, 11)(
15, 11)(
found:
12, 6)
14, 11)( 20, 15)
18, 21)
found:
20, 23)
20, 14)( 25, 17)
Input
Input will consist of a series of lines, each line consisting of an apparent Roman sum, i.e. a valid Roman
number, a plus sign (+), another valid Roman number, an equal sign (=) and another valid Roman
number. No Roman number will contain more than 9 letters. The le will be terminated by a line
consisting of a single #.
Output
Output will consist of a series of lines, one for each line of the input, and each containing two words.
The rst word will be one of (Correct, Incorrect) depending on whether the Roman sum is or is not
correct. The second word will be separated from the rst by exactly one space and will be one of the
set (impossible, ambiguous, valid) depending on the Arabic sum.
Sample input
V+V=X
X+X=XX
XX+XX=MXC
#
Sample output
Correct ambiguous
Correct impossible
Incorrect valid
Input
Output
The output should be a series of reports, one for each departure point-destination point pair in the input.
Each report should be in exactly the same form as those in the example below. There should be two
blank lines before each report.
Sample input
San Luis Obispo,Bakersfield,CA-58,117
Bakersfield,Mojave,CA-58,65
Mojave,Barstow,CA-58,70
Barstow,Baker,I-15,62
Baker,Las Vegas,I-15,92
San Luis Obispo,Santa Barbara,US-101,106
San Luis Obispo,Santa Barbara,CA-1,113
Santa Barbara,Los Angeles,US-101,95
Bakersfield,Wheeler Ridge,CA-99,24
Wheeler Ridge,Los Angeles,I-5,88
Mojave,Los Angeles,CA-14,94
Los Angeles,San Bernardino,I-10,65
San Bernardino,Barstow,I-15,73
Los Angeles,San Diego,I-5,121
San Bernardino,San Diego,I-15,103
Santa Barbara,Las Vegas
San Diego,Los Angeles
San Luis Obispo,Los Angeles
Sample output
From
-------------------Santa Barbara
Los Angeles
San Bernardino
Barstow
Baker
To
-------------------Los Angeles
San Bernardino
Barstow
Baker
Las Vegas
Route
Miles
---------- ----US-101
95
I-10
65
I-15
73
I-15
62
I-15
92
----Total
387
From
To
Route
Miles
-------------------- -------------------- ---------- ----San Diego
Los Angeles
I-5
121
----Total
121
From
-------------------San Luis Obispo
Santa Barbara
To
-------------------Santa Barbara
Los Angeles
Route
Miles
---------- ----US-101
106
US-101
95
----Total
201
Note: There will be no extraneous blanks in the input. There will be no more than 100 cities in the
map and no more than 200 highway segments. The total distance in each best route is guaranteed to t
within a 16-bit integer.
Input
where sss is a three-digit sequence number, nnn is a three-digit account number, and xxxxxxxxx is a
nine-digit amount in dollars and cents (without the decimal point). Each of these records is one entry of
a transaction. A transaction consists of between two and ten entries with identical sequence numbers.
Each transaction will be contiguous within the input data. This section of input data is terminated by
a record which has a sequence number of 000.
Output
Nothing is to be printed for transactions which balance. For transactions which do not balance, an
exception report is to be printed in the form:
***
nnn
nnn
.
.
.
999
Out of Balance
vvvvvvv.vv
Sample input
111Cash
121Accounts Receivable
211Accounts Payable
241Sales Tax Payable
401Sales
555Office Supplies
000No such account
100111
11795
100121 -11795
101121
105
101241
-7
101401
-100
102211 -70000
102555
40000
103111 -40000
103555
40000
000000
0
Sample output
***
121
241
401
999
***
211
555
999
for all i 6= j ,
then the next largest C that could resolve the con
ict is at least
$ % ! !
C
C
+
1
wi ;
+ 1 wj
min
w
w
i
Since all such con
icts must be resolved, it is advantageous to choose the largest candidate from
among the con
icts as the next C to test.
You are to convert each word to a number by processing each letter from left to right. Consider `a'
to be 1, `b' to be 2, : : :, `z' to be 26. Use 5 bits for each letter (shift left by 5 or multiply by 32). Thus
`a' = 1, `bz' = (2 32) + 26 = 90.
Input to your program will be a series of word lists, one per line, terminated by the end-of-le. Each
line consists of between two and thirteen words of at most ve lower case letters each, separated from
each other by at least one blank. There will always be at least one one-letter word.
For each list, you are to print the input line. On the next line, print the C for the hash function
determined by the list. Print a blank line after each C .
C will always t in a 32-bit integer.
Sample input
this is a test of some words to try out
a bee see dee
the of and to a in that is i it with for as
Sample output
this is a test of some words to try out
17247663
a bee see dee
4427
the of and to a in that is i it with for as
667241
Input to your program will be a series of Turbo Pascal programs. Each program will be terminated by a
line containing tilde characters in the rst two columns, followed by the name of the submitting member.
Each of these programs will be syntactically correct and use the standard symbols for comments (braces)
and subscripts (square brackets).
For each program, you are print a separate line containing the name of the submitting member and
the unit count of the program. Use a format identical to that of the sample below.
Sample input
PROGRAM SAMPLEINPUT;
VAR
TEMP : RECORD
FIRST, SECOND : REAL;
END;
BEGIN {Ignore this }
TEMP.FIRST := 5.0E-2;
READLN (TEMP.SECOND);
WRITELN ('THE ANSWER IS', TEMP.FIRST * TEMP.SECOND : 7 : 3)
END.
~~A. N. Onymous
Sample output
Program by A. N. Onymous contains 29 units.
Here are some additional notes on Turbo Pascal for those not familiar with the language:
Identiers start with an underscore ( ) or a letter (upper or lower case) which is followed by zero
or more characters that are underscores, letters or digits.
Note:
The delimiter for the beginning and ending of a string constant is the single forward quote (').
Each string is entirely on a single source line (that is a string constant cannot begin on one line
and continue on the next). If '' appears within a string then it represents a single ' character that
is part of the string. A string constant consisting of a single ' character is, therefore, represented
by '''' in a Turbo Pascal program. The empty string is allowed.
The most general form of a numeric constant is illustrated by the constant 10.56E-15. The 10
is the integral part (1 or more digits) and is always present. The .56 is the decimal part and is
optional. The E-15 is the exponent and it is also optional. It begins with an upper or lower case
E, which is followed by a sign (+ or -). The sign is optional.
Turbo Pascal supports hexadecimal integer constants which consist of a $ followed by one or more
hex digits (`0' to `9', `a' to `f', `A' to `F'). For example, $a9F is a legal integer constant in Turbo
Pascal.
The only comment delimiters that you should recognise are fg, and not (**). Comments do not
nest.
`+' and `?' should be considered as operators wherever possible. For example in
x := -3 the `?' and the `3' are separate tokens.
Subranges of ordinal types can be expressed as lower..upper. For example, 1..10 is a subrange
involving the integers from 1 to 10.
All tokens not mentioned anywhere above consist of a single character.
(x ? h)2 + (y ? k)2 = r2
(1)
x2 + y2 + cx + dy ? e = 0
(2)
Each line of input to your program will contain the x and y coordinates of three points, in the order
Ax, Ay , Bx , By , Cx, Cy . These coordinates will be real numbers separated from each other by one or
more spaces.
Your program must print the required equations on two lines using the format given in the sample
below. Your computed values for h, k, r, c, d, and e in Equations 1 and 2 above are to be printed
with three digits after the decimal point. Plus and minus signs in the equations should be changed as
needed to avoid multiple signs before a number. Plus, minus, and equal signs must be separated from
the adjacent characters by a single space on each side. No other spaces are to appear in the equations.
Print a single blank line after each equation pair.
Sample input
7.0 -5.0 -1.0 1.0 0.0 -6.0
1.0 7.0 8.0 6.0 7.0 -2.0
Sample output
(x - 3.000)^2 + (y + 2.000)^2 = 5.000^2
x^2 + y^2 - 6.000x + 4.000y - 12.000 = 0
(x - 3.921)^2 + (y - 2.447)^2 = 5.409^2
x^2 + y^2 - 7.842x - 4.895y - 7.895 = 0
191 Intersection
You are to write a program that has to decide whether a given line segment intersects a given rectangle.
An example:
line:
rectangle:
start point:
end point:
left-top:
right-bottom:
(4,9)
(11,2)
(1,5)
(7,1)
Input
The input consists of n test cases. The rst line of the input le contains the number n. Each following
line contains one test case of the format:
Output
For each test case in the input le, the output le should contain a line consisting either of the letter
"T" if the line segment intersects the rectangle or the letter "F" if the line segment does not intersect
Sample Input
1
4 9 11 2 1 5 7 1
Sample Output
F
The signal delay introduced between two synchronous nodes must be smaller or equal than the
clock period so there is enough time for nodes to become stable. In gure 1, the round-ended boxes
are asynchronous nodes whereas the square boxes are synchronous nodes. The delay introduced
on the dashed path is 43ns and exceeds the given clock period of 30ns.
There may be n o cycles composed exclusively of asynchronous nodes. In the real circuit such
cycles could oscillate. In gure 2, the dashed path constitutes a cycle of asynchronous nodes.
Figure 3 shows a circuit with a synchronous design. It does not contain cycles composed of asynchronous nodes and the longest path between two synchronous nodes is shorter than the clock period of
30ns.
the delays introduced between any input and any output of the same node are equal, i.e. equal to
the delay given for that node,
synchronous nodes have no delay at all,
all connections between two nodes connect an output to an input.
Input
The input le contains several circuits. The rst line gives the number of circuits in the le.
For each circuit in the le, the rst line contains the clock period for the circuit, given as an integer
number in nanoseconds. The next line gives the number of nodes. The following lines each contain a
node, described by a letter and a integer number. The letter is 'i' for an input, 'o' for an output, 'a'
for an asynchronous node and 's' for a synchronous node. The number gives the delay introduced by
the node as an integer number in nanoseconds (only meaningful for an asynchronous node). Nodes are
implicitly numbered, starting at zero.
After the nodes, the number of connections for the circuit follows. Each following line contains a
pair of integer numbers denoting a connection between the output and the input of two nodes. The
connection links an output of the node given by the rst number and an input of the node given by the
second number.
The clock signal is not given in the input le. We assume that all synchronous nodes are properly
connected to the clock signal.
Output
For each circuit in the input le, your output le should contain a line with one of the following messages:
"Synchronous design. Maximum delay: <ss>." if
Sample Input
1
30
10
i 0
i 0
i 0
i 0
o 0
o 0
a 9
a 11
a 8
s 0
9
0 8
1 7
2 6
2 6
6 7
7 8
8 4
7 9
9 5
Sample Output
Synchronous design. Maximum delay: 28
The graph is given as a set of nodes denoted by numbers 1 : : :n, n 100, and a set of undirected edges
denoted by pairs of node numbers (n1 ; n2), n1 6= n2 . The input le contains m graphs. The number m
is given on the rst line. The rst line of each graph contains n and k, the number of nodes and the
number of edges, respectively. The following k lines contain the edges given by a pair of node numbers,
which are separated by a space.
The output should consists of 2m lines, two lines for each graph found in the input le. The rst line
of should contain the maximum number of nodes that can be colored black in the graph. The second
line should contain one possible optimal coloring. It is given by the list of black nodes, separated by a
blank.
Sample Input
1
6
1
1
2
2
3
3
4
5
8
2
3
4
5
4
6
6
6
Sample Output
3
1 4 5
194 Triangle
A triangle is a basic shape of planar geometry. It consists of three straight lines and three angles in
between. Figure 1 shows how the sides and angles are usually labeled.
Figure 1: Triangle
A look into a book about geometry shows that many formulas for triangles exist:
++
=
a
b
c
sin = sin = sin
a = b cos
+ c cos
a2 = b2 + c2 ? 2bc cos
?
+
a?b
=
tan
tan
a+b
2
2
The values of a, b, c, , , and
form a set of six parameters that fully dene a triangle. If a large
enough subset of these parameters is given, the missing ones can be calculated by using the formulas
above.
You are to write a program that calculates the missing parameters for a given subset of the six
parameters of a triangle. For some sets of parameters, it is not possible to calculate the triangle because
either too few is known about the triangle or the parameters would lead to an invalid triangle. The sides
of a valid triangle are greater than 0 and the angles are greater than 0 and less than . Your program
should detect this case and output: "Invalid input." The same phrase should be output if more than
the minimal set needed to compute the triangle is given but the parameters con
ict with each other, e.g.
all three angles are given but their sum is greater than .
Other sets of parameters can lead to more than one but still a nite number of valid solutions for
the triangle. In such a case, your program should output: "More than one solution."
In all other cases, your program should compute the missing parameters and output all six parameters.
Input
The rst line of the input le contains a number indicating the number of parameter sets to follow.
Each following line consists of six numbers, separated by a single blank character. The numbers are the
values for the parameters a, , b, , c, and
respectively. The parameters are labeled as shown in gure
1. A value of -1 indicates that the corresponding parameter is undened and has to be calculated. All
oating-point numbers include at least eight signicant digits.
Output
Your program should output a line for each set of parameters found in the input le. If a unique solution
for a valid triangle can be found for the given parameters, your program should output the six parameters
a, , b, , c,
, separated by a blank character. Otherwise the line should contain the phrase
"More than one solution." or
"Invalid input."
as explained above.
The numbers in the output les should include at least eight signicant digits. Your calculations
should be precise enough to get the six most signicant digits correct.
Sample Input
3
62.72048064 2.26853639 -1.00000000 0.56794657 -1.00000000 -1.00000000
15.69326944 0.24714213 -1.00000000 1.80433105 66.04067877 -1.00000000
72.83685175 1.04409241 -1.00000000 -1.00000000 -1.00000000 -1.00000000
Sample Output
62.72048064 2.26853639 44.02668698 0.56794657 24.58722491 0.30510970
Invalid input.
Invalid input.
195 Anagram
You are to write a program that has to generate all possible words from a given set of letters.
Example: Given the word "abc", your program should - by exploring all dierent combination of the
three letters - output the words "abc", "acb", "bac", "bca", "cab" and "cba".
In the word taken from the input le, some letters may appear more than once. For a given word,
your program should not produce the same word more than once, and the words should be output in
alphabetically ascending order.
Input
The input le consists of several words. The rst line contains a number giving the number of words to
follow. Each following line contains one word. A word consists of uppercase or lowercase letters from A
to Z. Uppercase and lowercase letters are to be considered dierent.
Output
For each word in the input le, the output le should contain all dierent words that can be generated
with the letters of the given word. The words generated from the same input word should be output in
alphabetically ascending order.
Sample Input
2
abc
acba
Sample Output
abc
acb
bac
bca
cab
cba
aabc
aacb
abac
abca
acab
acba
baac
baca
bcaa
caab
caba
cbaa
196 Spreadsheet
In 1979, Dan Bricklin and Bob Frankston wrote VisiCalc, the rst spreadsheet application. It became a
huge success and, at that time, was the killer application for the Apple II computers. Today, spreadsheets
are found on most desktop computers.
The idea behind spreadsheets is very simple, though powerful. A spreadsheet consists of a table
where each cell contains either a number or a formula. A formula can compute an expression that
depends on the values of other cells. Text and graphics can be added for presentation purposes.
You are to write a very simple spreadsheet application. Your program should accept several spreadsheets. Each cell of the spreadsheet contains either a numeric value (integers only) or a formula, which
only support sums. After having computed the values of all formulas, your program should output the
resulting spreadsheet where all formulas have been replaced by their value.
A1
A2
A3
A4
A5
A6
B1
B2
B3
B4
B5
B6
C1
C2
C3
C4
C5
C6
D1
D2
D3
D4
D5
D6
E1
E2
E3
E4
E5
E6
F1
F2
F3
F4
F5
F6
:::
:::
:::
:::
:::
:::
:::
:::
:::
:::
:::
:::
:::
Input
The rst line of the input le contains the number of spreadsheets to follow. A spreadsheet starts with
a line consisting of two integer numbers, separated by a space, giving the number of columns and rows.
The following lines of the spreadsheet each contain a row. A row consists of the cells of that row,
separated by a single space.
A cell consists either of a numeric integer value or of a formula. A formula starts with an equal sign
(=). After that, one or more cell names follow, separated by plus signs (+). The value of such a formula
is the sum of all values found in the referenced cells. These cells may again contain a formula. There
are no spaces within a formula.
You may safely assume that there are no cyclic dependencies between cells. So each spreadsheet can
be fully computed.
The name of a cell consists of one to three letters for the column followed by a number between 1
and 999 (including) for the row. The letters for the column form the following series: A, B, C, ..., Z, AA,
AB, AC, ..., AZ, BA, ..., BZ, CA, ..., ZZ, AAA, AAB, ..., AAZ, ABA, ..., ABZ, ACA, ..., ZZZ. These
letters correspond to the number from 1 to 18278. The top left cell has the name A1. See gure 1.
Output
The output of your program should have the same format as the input, except that the number of
spreadsheets and the number of columns and rows are not repeated. Furthermore, all formulas should
be replaced by their value.
Sample Input
1
4 3
10 34 37 =A1+B1+C1
40 17 34 =A2+B2+C2
=A1+A2 =B1+B2 =C1+C2 =D1+D2
Sample Output
10 34 37 81
40 17 34 91
50 51 71 172
197
Cube
There was on e a 3 by 3 by 3 ube built of 27 smaller ubes. It has fallen apart into seven pie es:
d d g
b f g
f f e
d g g
b f e
b e e
a a b
a b b
a d
f f e
g f
d d
f e e
g g e
d g
Input
The input le has several test
ases. Ea
h test
ase indi
ates the initial position of pie
e `a'. You
an
translate it, but you mustn't rotate it.
Output
For ea
h solution found, your program should output a line
ontaining the solution as a string. The
string is a linearized form of the
ube. Ea
h letter stands for the pie
e lling out the
orresponding
spa
e in the
ube. It is linearized as follows:
The string
onsists of substrings representing the front, middle and ba
k plane.
Ea
h substring
onsists of substrings representing the top, middle and bottom row.
Ea
h row substring
onsists of letters representing the left, middle and right
ell.
It is very important that your program uses the naming
onvention given in gure 1 and linearizes
the
ube as explained above.
Print a blank line after ea
h test
ase.
aa.a..a....................
.........a..a..aa..........
Sample output
Peter's Calculator
Unfortunately, Peter's Calculator broke down last week. Now Peter is left with his computer, which has
no calculator application, and paper and pencil, which is too tiresome for an engineer. As one of Peter's
friends, you are asked to write him a calculator application. After talking to him, you gure out the
following:
Peter does only integer arithmetic. The operations he needs are addition, subtraction and multiplication.
He would like to use an arbitrary number of variables whose names are not longer than 50 characters.
His main way of doing calculations are to type in a few formulas and to assign them to variables.
Some formulas are complicated expressions, which can refer to yet undened variables, while other
formulas consist of a single number. Then Peter asks for the value of some variables, i.e. he
evaluates the formulas.
Peters wants to redene some variables and then to reevaluate formulas that depend on these
variables.
The input strictly adheres to the following syntax (given in EBNF):
file = line { line } <EOF>.
line = [ assignment | print | reset ] <CR>.
assignment = var ":=" expression.
print = "PRINT" var.
reset = "RESET".
expression = term { addop term }.
term = factor { mulop factor }.
factor = "(" expression ")" | var | number.
addop = "+" | "-".
mulop = "*".
In the Extended Backus-Naur Formalism (EBNF), A = B C declares that the grammatical construct
A consists of a B followed by a C . A = B | C means that A consists of a B or, alternatively, of a C
. A = [ B ] denes construct A to be either a B or nothing and A = B tells you that A consists
of the concatenation of any number of B's (including none).
The production var stands for the name of a variable, which starts with a letter followed by up to
49 letters or digits. Letters may be uppercase or lowercase. The production number stands for a integer
number. The precise syntax for these productions are given below. The case of letters is important for
both variables and statements.
var = letter { letter | digit }.
number = [ "-" ] digit { digit }.
letter = "A" | "B" | ... | "Z" | "a" | "b" | ... | "z".
digit = "0" | "1" | ... | "8" | "9".
Between the parts of a grammatical construct but not within the names of variables or integer
numbers, any number of spaces may appear. <EOF> stands for the end of the input le and <CR> stands
for the new-line character. All lines in the input le are shorter than 200 characters.
The value of a variable is said to be undened:
if it has not yet been dened or it refers to a variable, which has not yet been dened;
if the denition of the variable contains a cycle.
Your are to write a program that implements Peter's calculator. It should store all variable denitions
and for each "PRINT" statement evaluate the specied variable based on the latest variable denitions. If
your program encounters a "RESET" statement, it should delete all stored variables so that all variables
become undened.
Input
The input le contains calculations adhering to the syntax given above. Each line contains either an
assignment to a variable, a "PRINT" statement, a "RESET" statement or nothing.
Output
For each "PRINT" statement found in the input le, your program should output a line containing the
numerical value of the specied variable or the word "UNDEF" if the variable is undened.
Sample Input
a := b + c
b := 3
c := 5
PRINT d
PRINT a
b := 8
PRINT a
RESET
PRINT a
Sample Output
UNDEF
8
13
UNDEF
(1)
@ 2 u = 1 (u ? 2u + u )
(2)
+1
@x2 h2 ?1
This approximation works with 2-dimensional functions u(x; y ) as well. For simplicity we only work
on square problems, i.e. (x; y ) is element of [0; 1] [0; 1]. Again, the area of the function is discretized
in a similar way: x +1 ? x = y +1 ? y = h = 1 , for some integer n 2. We only look at the values of
u(x; y) at the discrete points P = (x ; y ) : u = u(P ). With this discretization, we have a function
u as shown in gure 2:
i
i;j
i;j
u(x ; 0)
u(x ; 1)
u(0; y )
u(1; y )
= b1(x )
= b2(x )
(3)
= b3(y )
= b4(y )
The points P cover the inner points of the discretization area, i.e. the area without the boundary.
They are numbered from left to right and from top to bottom like English text.
What we now want to do is to solve the poisson-equation in the area [0; 1] [0; 1]:
i
@ 2 u + @ 2 u = f (x; y)
(4)
@x2 @y 2
with the above boundary conditions. f (x; y ) is a given 2-dimensional function. With equation (2) and
the above discretization, the poisson-equation can be approximated at
1
h2 (u ?1 + u ?1 + u +1 + u +1 ? 4u = f ;
where f is the function f (x; y ), evaluated at the discrete points (x ; y ).
i
;j
i;j
;j
i;j
i;j
i;j
(5)
i;j
Formula (5) can be written in a more readable form, depending on the position of the discrete points:
1
1
0
0
0
0
0
0
1
0
1B
C
C
B
h2 @ 1 ?4 1 A 3u = @ 0 1 0 A 3f
(6a)
0 0 0
0 1 0
A similar equation, which we will use as an example below, is:
1
0
1
0
0
5
0
1
0
2
1B
C
B
C
h2 @ 0 ?4 0 A 3u = @ 6 0 7 A 3f
(6b)
0 8 0
3 0 4
We call the 3 3 matrix on the left hand side v and the 3 3 matrix on the right hand side g .
Now, equation (6b) can be formulated in every point of the discrete area of gure 2:
P1 :
P2 :
P3 :
P4 :
1 (b2(0) + 2b2(2h) ? 4P1 + 3b3(h) + 4P4) = 5f (h; 1) + 6f (0; 2h) + 7f (2h; 2h) + 8f (h; h)
12 (b2(h) + 2b2(1) ? 4P2 + 3P3 + 4b4(h)) = 5f (2h; 1) + 6f (h; 2h) + 7f (1; 2h) + 8f (2h; h)
12 (b3(2h) + 2P2 ? 4P3 + 3b1(0) + 4b1(2h)) = 5f (h; 2h) + 6f (0; h) + 7f (2h; h) + 8f (h; 0)
12 (P1 + 2b4(2h) ? 4P4 + 3b1(h) + 4b1(1)) = 5f (2h; 2h) + 6f (h; h) + 7f (1; h) + 8f (2h; 0)
h2
h
h
h
9
>
>
=
(7)
>
>
;
and (7) is a linear equation system for the values of u(x; y ) at the points P1 ; P2; P3 and P4 .
By rearranging and adding the terms on each line, the linear equation system can be formulated as:
az = b
(8)
where a is a 4 4 matrix and b is a vector with 4 elements. Vector z represents the unknown values of
u(x; y) at the points P1 ; P2; P3 and P4 .
You are to write a program that creates the linear equation system (7) in the form (8) for any two
matrices v and g (6). As input, the two matrices v and g and the functions b1; b2; b3; b4 , and f are given.
Also, a parameter n is given as the number of discretization intervals. Thus, h = 1 . As the result, your
program should calculate the matrix a and the vector b. For this more general case, there are (n ? 1)2
inner points and a and b must be sized accordingly.
n
Input
The input le consists of m tests. The number m is given in the rst line of the le. The rst line of
each test contains the number n which gives the number of discretizations intervals as dened above.
You may assume that 2 n 30. Then the 3 3 matrices v and g follow. The following four lines
contain the functions b1; b2; b3 and b4, each given as a vector of order n + 1, containing the values for
0, h, 2h, ..., 1. Finally, the function f is given as a n + 1 by n + 1 matrix. Like the vectors before, it
contains the values for x; y = 0; h; 2h; : : :; 1. Each row contains from left to right the function values for
increasing x values while each column contains from top to bottom the function values for increasing y
values.
A vector occupies one line. Its values are given in ascending order, separated by a space. A n by n
matrix occupies n lines. Its rows are given in ascending order as vectors, which occupy one line each.
All values found in the input le are integer values.
Output
For each test found in the input le, your program should output the matrices a and b. Matrix a is a
(n ? 1)2 (n ? 1)2 matrix (the discretization area (cf. gure 2) contains (n ? 1)2 inner points, which are
unknown). The vector b is of order (n ? 1)2. They should be output in the same format as the vectors
and matrices in the input le. Your output should only contain integer values. Note that the expression
12 yields an integer number and that all other calculations can also be done using integer numbers.
h
Sample Input
1
3
1
0
3
0
6
0
3
0
3
6
1
2
3
4
0 2
-4 0
0 4
5 0
0 7
8 0
4 5 6
1 2 3
2 1 0
5 4 3
1 1 1
2 2 2
3 3 3
4 4 4
Sample Output
-36 0 0 36
0 -36 27 0
0 18 -36 0
9 0 0 -36
-8 -152 -198 -333