Vous êtes sur la page 1sur 169

# ACM Contest Problems Archive

## 100 The 3n + 1 problem

Background

Problems in Computer Science are often classi ed 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
classi cation is not known for all possible inputs.

The Problem

## Consider the following algorithm:

1. input n
2. print n
3. if n = 1 then STOP
4.
if n is odd then n ? 3n + 1
5.
else n ? n=2
6. GOTO 2
Given the input 22, the following sequence of numbers will be printed
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input
value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been
veri ed, however, for all integers n such that 0 < n < 1; 000; 000 (and, in fact, for many more numbers
than this.)
Given an input n, it is possible to determine the number of numbers printed before and including
the 1 is printed. For a given n this is called the cycle-length of n. In the example above, the cycle length
of 22 is 16.
For any two numbers i and j you are to determine the maximum cycle length over all numbers
between and including both i and j .

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

## The Blo ks Problem

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 i ed 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

## Figure 1: Initial Blo ks World

The valid ommands for the robot arm that manipulates blo ks are:

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 a e t on the on guration of
blo ks.

## ACM Contest Problems Ar hive

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 i ed 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

## 102 Ecological Bin Packing

Background

Bin packing, or the placement of objects of certain weights into di erent 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
speci ed 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 in nite 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 con guration should be printed.

## ACM Contest Problems Archive

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

## 103 Stacking Boxes

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 di erential 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
suces, 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 satis es 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 de ne 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.

## ACM Contest Problems Archive

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

## ACM Contest Problems Archive

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 di er-

ences in conversion rates among several currencies in order to achieve a pro t. 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 pro t of 6.4 percent. You will write a program that determines whether a sequence of currency exchanges can yield a pro t 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 pro t of more than 1 percent (0.01). If a sequence exists you must print the sequence of exchanges that results in a pro t. If there is more than one sequence that results in a pro t 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 pro t. Because the IRS (United States Internal Revenue Service) notices lengthy transaction sequences, all pro ting 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 pro ting sequence exists you must print the sequence of exchanges that results in a pro t. 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 pro ting sequence starts. This integer also ends the sequence. n ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## If no pro ting sequence of or fewer transactions exists, then the line n ## no arbitrage sequence exists 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 ## The Skyline Problem 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 ## Universidad de Valladolid OJ: 105 The Skyline Problem 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 106 Fermat vs. Pythagoras Background Computer generated and assisted proofs and veri cation 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 e orts in veri cation 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 107 The Cat in the Hat Background ## (An homage to Theodore Seuss Geisel) The Cat in the Hat is a nasty creature, But the striped hat he is wearing has a rather nifty feature. With one ick of his wrist he pops his top o . Do you know what's inside that Cat's hat? A bunch of small cats, each with its own striped hat. Each little cat does the same as line three, All except the littlest ones, who just say \Why me?" Because the littlest cats have to clean all the grime, And they're tired of doing it time after time! 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 speci cations. Each speci cation 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 speci cation), 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. ## ACM Contest Problems Archive Sample Input 216 125 5764801 1679616 0 0 Sample Output 31 671 335923 30275911 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 108 Maximum Sum Background A problem that is simple to solve in one dimension is often much more dicult 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 eciently, 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: ## is in the lower-left-hand corner: and has the sum of 15. ## Input and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 109 SCUD Busters Background Some problems are dicult to solve but have a simpli cation that is easy to solve. Rather than deal with the diculties 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 speci cations followed by a sequence of missile landing locations. A kingdom is speci ed 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 speci cation 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 speci ed in kilometers using coordinates on a 500 km by 500 km grid. All coordinates will be integers between 0 and 500 inclusive. Coordinates are speci ed 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. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 ## You may or may not nd the following formula useful. Given a polygon described by the vertices v0 ; v1; : : : ; v such that v0 = v , the signed area of the polygon is given by 1 (x y ) ? (x y ) a = ?1 ?1 2 =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 ## ACM Contest Problems Archive 110 ## University of Valladolid (SPAIN) 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 signi cant 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:        ## It must begin with program sort(input,output); It must declare storage for exactly n integer variables. The names of the variables must come from the rst n letters of the alphabet (a,b,c,d,e,f). A single readln statement must read in values for all the integer variables. Other than writeln statements, the only statements in the program are if then else statements. The boolean conditional for each if statement must consist of one strict inequality (either < or >) of two integer variables. Exactly n! writeln statements must appear in the program. Exactly three semi-colons must appear in the program 1. after the program header: program sort(input,output); 2. after the variable declaration: : : : : integer; 3. after the readln statement: readln(: : : ); No redundant comparisons of integer variables should be made. For example, during program execution, once it is determined that a < b, variables a and b should not be compared again. Every writeln statement must appear on a line by itself. The program must compile. Executing the program with input consisting of any arrangement of any n distinct integer values should result in the input values being printed in sorted order. For those unfamiliar with Pascal syntax, the example at the end of this problem completely de nes the small subset of Pascal needed. The Input ## The input is a single integer n on a line by itself with 1  n  6. The Output The output is a compilable standard Pascal program meeting the criteria speci ed above. ## ACM Contest Problems Archive 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. ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 111 History Grading 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 ## Given the correct chronological order of n events 1; 2; : : : ; n as c1 ; c2; : : : c where 1  c  n denotes the ranking of event i in the correct chronological order and a sequence of student responses r1; r2; : : : r where 1  r  n denotes the chronological rank given by the student to event i; determine the length of the longest (not necessarily contiguous) sequence of events in the student responses that are in the correct chronological order relative to each other. n 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 ## ACM Contest Problems Archive 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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 112 Tree Summing Background 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 speci ed 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 speci ed 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. ## ACM Contest Problems Archive The Output ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 113 Power of Cryptography 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 ecient 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 ## n p should be printed, i.e., the number k such that kn = p. For each integer pair n and p the value p Sample Input 2 16 3 27 7 4357186184021382204544 Sample Output 4 3 1234 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 114 Simulation Wizardry 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 de nition 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. ## ACM Contest Problems Archive The Output ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 115 Climbing Trees Background Expression trees, B and B* trees, red-black trees, quad trees, PQ trees; trees play a signi cant 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 Arti cial 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 Hu man 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 de nitions:  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 de nition 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 ## if and only if p is an (n + 1)-descendent of q . 2. parent | grand parent, great grand parent, great great grand parent, etc. By de nition p is the \parent" of q if and only if the pair q p appears in the input sequence of child-parent pairs (i.e., p is a 0-ancestor of q ); p is the \grand parent" of q if and only if p is a 1-ancestor of q ; and p is the \ great great : : : great} grand parent" of q {z | n times ## if and only if p is an (n + 1)-ancestor of q . ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 3. cousin | 0th cousin, 1st cousin, 2nd cousin, etc.; cousins may be once removed, twice removed, three times removed, etc. By de nition 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 de nition, cousins p and q are \kth cousins" if and only if k = min(n; m), and, also by de nition, 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 di erent 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. ## ACM Contest Problems Archive 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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive 116 ## University of Valladolid (SPAIN) Unidirectional TSP Background Problems that require minimum paths through some domain appear in many di erent 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 speci ed 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 di erent 5 6 matrices are shown below (the only di erence 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 speci cations. Each matrix speci cation 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  ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) are not restricted to being positive. There will be one or more matrix speci cations in an input le. Input is terminated by end-of- le. For each speci cation 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 speci cation 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 117 The Postal Worker Rings Once 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 Konigsberg problem. Many optimization problems involve determining ecient 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 speci ed, 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. ## ACM Contest Problems Archive 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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 118 Mutant Flatworld Explorers Background Robotics, robot motion planning, and machine learning are areas that cross the boundaries of many of the subdisciplines that comprise Computer Science: arti cial 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 speci ed grid. The maximum value for any coordinate is 50. All instruction strings will be less than 100 characters in length. ## ACM Contest Problems Archive The Output ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 119 Greedy Gift Givers 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 input is a sequence of gift-giving groups. A group consists of several lines:  the number of people in the group,  a list of the names of each person in the group,  a line for each person in the group consisting of the name of the person, the amount of money spent on gifts, the number of people to whom gifts are given, and the names of those to whom gifts are given. All names are lower-case letters, there are no more than 10 people in a group, and no name is more than 12 characters in length. Money is a non-negative integer less than 2000. The input consists of one or more groups and is terminated by end-of- le. 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. ## ACM Contest Problems Archive 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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 120 Stacks of Flapjacks 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 di erent 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 speci ed 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 speci ed 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. ## ACM Contest Problems Archive 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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 121 Pipe Fitters 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 di erent 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. ## ACM Contest Problems Archive Sample Input 3 3 2.9 10 2.9 10.5 11 11 Sample Output 9 grid 29 skew 30 skew 126 skew ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 122 Trees on the level 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 ## is: 5, 4, 8, 11, 13, 4, 7, 2, 1. In this problem a binary tree is speci ed by a sequence of pairs (n,s) where n is the value at the node whose path from the root is given by the string s. A path is given be a sequence of L's and R's where L indicates a left branch and R indicates a right branch. In the tree diagrammed above, the node containing 13 is speci ed by (13,RL), and the node containing 2 is speci ed by (2,LLR). The root node is speci ed by (5,) where the empty string indicates the path from the root to itself. A binary tree is considered to be completely speci ed if every node on all root-to-node paths in the tree is given a value exactly once. The Input The input is a sequence of binary trees speci ed 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 ## Pun de nitely intended. ## ACM Contest Problems Archive The Output ## University of Valladolid (SPAIN) For each completely speci ed binary tree in the input le, the level order traversal of that tree should be printed. If a tree is not completely speci ed, 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 123 Searching Quickly 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 ecient O(n log n) [average case] comparison based sort. KWIC-indexing is an indexing method that permits ecient \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 ## A KWIC-index of these titles might be given by: a portrait of the ARTIST as a young man the ASCENT of man DESCENT of man descent of MAN the ascent of MAN the old MAN and the sea a portrait of the artist as a young MAN the OLD man and the sea a PORTRAIT of the artist as a young 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. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 justi ed or aligned by keyword, all titles may be listed left-justi ed. 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 124 Following Orders 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 speci cations. A speci cation 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 speci cation. There will be at least one constraint, and no more than 50 constraints in a speci cation. There will be at least one, and no more than 300 orderings consistent with the contraints in a speci cation. Input is terminated by end-of- le. The Output For each constraint speci cation, 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 di erent constraint speci cations 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 ## ACM Contest Problems Archive Sample Output abfg abgf agbf gabf wxzvy wzxvy xwzvy xzwvy zwxvy zxwvy ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 125 Numbering Paths 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 ecient solutions. Other problems may be simple as decision problems, but enumerating all possible \yes" answers may be very dicult (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 di erent routes between each intersection. A route is a sequence of one-way streets connecting two intersections. Intersections are identi ed by non-negative integers. A one-way street is speci ed 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 in nite number of di erent 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 in nitely many di erent routes from 0 to 2. This is because the street from 2 to 3 and back to 2 can be repeated yielding a di erent sequence of streets and hence a di erent route. Thus the route 0 ! 2 ! 3 ! 2 ! 3 ! 2 is a di erent route than 0 ! 2 ! 3 ! 2. The Input The input is a sequence of city speci cations. Each speci cation 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 speci cation, a square matrix of the number of di erent routes from intersection j to intersection k is printed. If the matrix is denoted M , then M [j ][k] is the number of di erent routes from intersection j to intersection k. The matrix M should be printed in row-major order, one row per line. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) Each matrix should be preceded by the string \matrix for city k" (with k appropriately instantiated, beginning with 0). If there are an in nite number of di erent 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 126 The Errant Physicist The well-known physicist Alfred E Neuman is working on problems that involve multiplying polynomials of x and y. For example, he may need to calculate (?x8 y + 9x3 ? 1 + y ):(x5y + 1 + x3 ) getting the answer 13 2 y 11 ## + 8x8y + 9x6 ? x5 y + x5 y 2 + 8x3 + x3 y ? 1 + y 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. Coecients are also integers, but may be negative. Both exponents and coecients 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 coecient must not be displayed. 4. Coecients 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 coecient of the rst term is negative, it is preceded by a unary minus in the rst column, with no intervening blank column. Otherwise, the coecient itself begins in the rst output column. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 127 \Accordian" Patience You are to simulate the playing of games of \Accordian" patience, the rules for which are as follows: Deal cards one by one in a row from left to right, not overlapping. Whenever the card matches its immediate neighbour on the left, or matches the third card to the left, it may be moved onto that card. Cards match if they are of the same suit or same rank. After making a move, look to see if it has made additional moves possible. Only the top card of each pile may be moved at any given time. Gaps between piles should be closed up as soon as they appear by moving all piles on the right of the gap one position to the left. Deal out the whole pack, combining cards towards the left whenever possible. The game is won if the pack is reduced to a single pile. Situations can arise where more than one play is possible. Where two cards may be moved, you should adopt the strategy of always moving the leftmost card possible. Where a card may be moved either one position to the left or three positions to the left, move it three positions. Input Input data to the program speci es 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 128 Software CRC You work for a company which uses lots of personal computers. Your boss, Dr Penny Pincher, has wanted to link the computers together for some time but has been unwilling to spend any money on the Ethernet boards you have recommended. You, unwittingly, have pointed out that each of the PCs has come from the vendor with an asynchronous serial port at no extra cost. Dr Pincher, of course, recognizes her opportunity and assigns you the task of writing the software necessary to allow communication between PCs. You've read a bit about communications and know that every transmission is subject to error and that the typical solution to this problem is to append some error checking information to the end of each message. This information allows the receiving program to detect when a transmission error has occurred (in most cases). So, o you go to the library, borrow the biggest book on communications you can nd and spend your weekend (unpaid overtime) reading about error checking. Finally you decide that CRC (cyclic redundancy check) is the best error checking for your situation and write a note to Dr Pincher detailing the proposed error checking mechanism noted below. 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 signi cant byte of the binary number. The second byte is the next most signi cant, 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). ## Input and Output 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 # ## ACM Contest Problems Archive Sample Output 77 FD 0C 86 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive 129 ## University of Valladolid (SPAIN) 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 diculty 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 ## Some examples of hard sequences are:     D DC ABDAB CBABCBA ## Input and Output 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 ## Alphabetical ordering here corresponds to the normal ordering encountered in a dictionary. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 130 Roman Roulette The historian Flavius Josephus relates how, in the Romano-Jewish con ict of 67 A.D., the Romans took the town of Jotapata which he was commanding. Escaping, Jospehus found himself trapped in a cave with 40 companions. The Romans discovered his whereabouts and invited him to surrender, but his companions refused to allow him to do so. He therefore suggested that they kill each other, one by one, the order to be decided by lot. Tradition has it that the means for e ecting the lot was to stand in a circle, and, beginning at some point, count round, every third person being killed in turn. The sole survivor of this process was Josephus, who then surrendered to the Romans. Which begs the question: had Josephus previously practised quietly with 41 stones in a dark corner, or had he calculated mathematically that he should adopt the 31st position in order to survive? Having read an account of this gruesome event you become obsessed with the fear that you will nd yourself in a similar situation at some time in the future. In order to prepare yourself for such an eventuality you decide to write a program to run on your hand-held PC which will determine the position that the counting process should start in order to ensure that you will be the sole survivor. In particular, your program should be able to handle the following variation of the processes described by Josephus. n > 0 people are initially arranged in a circle, facing inwards, and numbered from 1 to n. The numbering from 1 to n proceeds consecutively in a clockwise direction. Your allocated number is 1. Starting with person number i, counting starts in a clockwise direction, until we get to person number k (k > 0), who is promptly killed. We then proceed to count a further k people in a clockwise direction, starting with the person immediately to the left of the victim. The person number k so selected has the job of burying the victim, and then returning to the position in the circle that the victim had previously occupied. Counting then proceeeds from the person to his immediate left, with the kth person being killed, and so on, until only one person remains. For example, when n = 5, and k = 2, and i = 1, the order of execution is 2, 5, 3, and 1. The survivor is 4. ## Input and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 131 The Psychic Poker Player In 5-card draw poker, a player is dealt a hand of ve cards (which may be looked at). The player may then discard between zero and ve of his or her cards and have them replaced by the same number of cards from the top of the deck (which is face down). The object is to maximize the value of the nal hand. The di erent values of hands in poker are given at the end of this problem. Normally the player cannot see the cards in the deck and so must use probability to decide which cards to discard. In this problem, we imagine that the poker player is psychic and knows which cards are on top of the deck. Write a program which advises the player which cards to discard so as to maximize the value of the resulting hand. ## Input and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 132 Bumpy Objects 6 7 8 1 2 3 4 1 5 6 Object 1 3 Object 2 4 Square Consider objects such as these. They are polygons, speci ed 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 de ned by one of these lines known as its base line. A base line, and its associated stable position, is identi ed 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 de ned by the string '#'. Output will consist of the identi cation string followed by the number of the relevant base line. ## ACM Contest Problems Archive 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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 133 The Dole Queue In a serious attempt to downsize (reduce) the dole queue, The New National Green Labour Rhinoceros Party has decided on the following strategy. Every day all dole applicants will be placed in a large circle, facing inwards. Someone is arbitrarily chosen as number 1, and the rest are numbered counter-clockwise up to N (who will be standing on 1's left). Starting from 1 and moving counter-clockwise, one labour ocial counts o k applicants, while another ocial starts from N and moves clockwise, counting m applicants. The two who are chosen are then sent o for retraining; if both ocials pick the same person she (he) is sent o to become a politician. Each ocial then starts counting again at the next available person and the process continues until no-one is left. Note that the two victims (sorry, trainees) leave the ring simultaneously, so it is possible for one ocial to count a person already selected by the other ocial. 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 ocial 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. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 134 Loglan|A Logical Language Loglan is a synthetic speakable language designed to test some of the fundamental problems of linguistics, such as the Sapir Whorf hypothesis. It is syntactically unambiguous, culturally neutral and metaphysically parsimonious. What follows is a gross over-simpli cation of an already very small grammar of some 200 rules. Loglan sentences consist of a series of words and names, separated by spaces, and are terminated by a period (.). Loglan words all end with a vowel; names, which are derived extra-linguistically, end with a consonant. Loglan words are divided into two classes|little words which specify the structure of a sentence, and predicates which have the form CCVCV or CVCCV where C represents a consonant and V represents a vowel (see examples later). The subset of Loglan that we are considering uses the following grammar: A MOD BA DA LA NAM PREDA <sentence> <predclaim> <preds> <predname> <predstring> <statement> <verbpred> ) 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. ## Input and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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. ## Input and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 136 Ugly Numbers Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, : : : shows the rst 11 ugly numbers. By convention, 1 is included. Write a program to nd and print the 1500'th ugly number. ## Input and Output 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>. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 137 Polygons Given two convex polygons, they may or may not overlap. If they do overlap, they will do so to di ering degrees and in di erent 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. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 138 Street Numbers A computer programmer lives in a street with houses numbered consecutively (from 1) down one side of the street. Every evening she walks her dog by leaving her house and randomly turning left or right and walking to the end of the street and back. One night she adds up the street numbers of the houses she passes (excluding her own). The next time she walks the other way she repeats this and nds, to her astonishment, that the two sums are the same. Although this is determined in part by her house number and in part by the number of houses in the street, she nevertheless feels that this is a desirable property for her house to have and decides that all her subsequent houses should exhibit it. Write a program to nd pairs of numbers that satisfy this condition. To start your list the rst two pairs are: (house number, last number): 6 35 8 49 ## Input and Output There is no input for this program. Output will consist of 10 lines each containing a pair of numbers, each printed right justi ed in a eld of width 10 (as shown above). ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 139 Telephone Tangles A large company wishes to monitor the cost of phone calls made by its personnel. To achieve this the PABX logs, for each call, the number called (a string of up to 15 digits) and the duration in minutes. Write a program to process this data and produce a report specifying each call and its cost, based on standard Telecom charges. International (IDD) numbers start with two zeroes (00) followed by a country code (1{3 digits) followed by a subscriber's number (4{10 digits). National (STD) calls start with one zero (0) followed by an area code (1{5 digits) followed by the subscriber's number (4{7 digits). The price of a call is determined by its destination and its duration. Local calls start with any digit other than 0 and are free. 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 nameprice 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 # ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 de ned 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 de ned 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 141 The Spot Game The game of Spot is played on an NxN board as shown below for N = 4. During the game, alternate players may either place a black counter (spot) in an empty square or remove one from the board, thus producing a variety of patterns. If a board pattern (or its rotation by 90 degrees or 180 degrees) is repeated during a game, the player producing that pattern loses and the other player wins. The game terminates in a draw after 2N moves if no duplicate pattern is produced before then. Consider the following patterns: 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 and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 142 Mouse Clicks A typical windowing system on a computer will provide a number of icons on the screen as well as some de ned regions. When the mouse button is clicked, the system has to determine where the cursor is and what is being selected. For this problem we assume that a mouse click in (or on the border of) a region selects that region, otherwise it selects the closest visible icon (or icons in the case of a tie). Consider the following screen: 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 de nitions 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 speci cation part and the event part, however no icon or region speci cations 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. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 identi ed by their single character identi er, icon numbers will be written out right justi ed 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 143 Orchard Trees An Orchardist has planted an orchard in a rectangle with trees uniformly spaced in both directions. Thus the trees form a rectangular grid and we can consider the trees to have integer coordinates. The origin of the coordinate system is at the bottom left of the following diagram: 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 and Output 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 justi ed 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 144 Student Grants The Government of Impecunia has decided to discourage tertiary students by making the payments of tertiary grants a long and time-consuming process. Each student is issued a student ID card which has a magnetically encoded strip on the back which records the payment of the student grant. This is initially set to zero. The grant has been set at$40 per year and is paid to the student on the working day nearest
to his birthday. (Impecunian society is still somewhat medieval and only males continue with tertiary
education.) Thus on any given working day up to 25 students will appear at the nearest oce of the
Department of Student Subsidies to collect their grant.
The grant is paid by an Automatic Teller Machine which is driven by a reprogrammed 8085 21 chip
originally designed to run the state slot machine. The ATM was built in the State Workshops and is
designed to be dicult to rob. It consists of an interior vault where it holds a large stock of $1 coins and an output store from which these coins are dispensed. To limit possible losses it will only move coins from the vault to the output store when that is empty. When the machine is switched on in the morning, with an empty output store, it immediately moves 1 coin into the output store. When that has been dispensed it will then move 2 coins, then 3, and so on until it reaches some preset limit k. It then recycles back to 1, then 2 and so on. The students form a queue at this machine and, in turn, each student inserts his card. The machine dispenses what it has in its output store and updates the amount paid to that student by writing the new total on the card. If the student has not received his full grant, he removes his card and rejoins the queue at the end. If the amount in the store plus what the student has already received comes to more than$40, the machine only pays out enough to make the total up to $40. Since this fact is recorded on the card, it is pointless for the student to continue queuing and he leaves. The amount remaining in the store is then available for the next student. Write a program that will read in values of N (the number of students, 1  N  25) and k (the limit for that machine, 1  k  40) and calculate the order in which the students leave the queue. ## Input and Output 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 justi ed in a eld of width 3. Sample input 5 3 0 0 Sample output 1 3 5 2 4 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 145 Gondwanaland Telecom Gondwanaland Telecom makes charges for calls according to distance and time of day. The basis of the charging is contained in the following schedule, where the charging step is related to the distance: Charging Step Day Rate Evening Rate Night Rate (distance) 8am to 6pm 6pm to 10pm 10pm to 8am A 0.10 0.06 0.02 B 0.25 0.15 0.05 C 0.53 0.33 0.13 D 0.87 0.47 0.17 E 1.44 0.80 0.30 All charges are in dollars per minute of the call. Calls which straddle a rate boundary are charged according to the time spent in each section. Thus a call starting at 5:58 pm and terminating at 6:04 pm will be charged for 2 minutes at the day rate and for 4 minutes at the evening rate. Calls less than a minute are not recorded and no call may last more than 24 hours. Write a program that reads call details and calculates the corresponding charges. ## Input and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 e ect of this process is that it will shorten the dole queue for plastic surgeons.) An essential component of each computer will be a unique identi cation 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 di erent 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 identi cation 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 and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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: 120c, 210c, 10c+25c, and 45c.

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 justi ed in a eld of width 5), followed by the number of ways in which that amount may be made up, right justi ed in a eld of width 12. Sample input 0.20 2.00 0.00 Sample output 0.20 2.00 4 293 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 148 Anagram checker It is often fun to see if rearranging the letters of a name gives an amusing anagram. For example, the letters of WILLIAM SHAKESPEARE' rearrange to form SPEAK REALISM AWHILE'. Write a program that will read in a dictionary and a list of phrases and determine which words from the dictionary, if any, form anagrams of the given phrases. Your program must nd all sets of words in the dictionary which can be formed from the letters in each phrase. Do not include the set consisting of the original words. If no anagram is present, do not write anything, not even a blank line. 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 # ## ACM Contest Problems Archive Sample output SXZYTWQP SXZYTWQP SXZYTWQP SXZYTWQP KLJ KLJ KLJ KLJ YRTD YRTD YRTD YRTD = = = = ## DXZ K LJSRT PTYYWQ DXZ K LT PT Y YWJSRQ KX LJSRT PTYYWQ ZD KX LT PT Y YWJSRQ ZD ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 de niteness, \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 in nite, 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. ## ACM Contest Problems Archive Output ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 150 Double Time In 45 BC a standard calendar was adopted by Julius Caesar|each year would have 365 days, and every fourth year have an extra day|the 29th of February. However this calendar was not quite accurate enough to track the true solar year, and it became noticeable that the onset of the seasons was shifting steadily through the year. In 1582 Pope Gregory XIII ruled that a new style calendar should take e ect. From then on, century years would only be leap years if they were divisible by 400. Furthermore the current year needed an adjustment to realign the calendar with the seasons. This new calendar, and the correction required, were adopted immediately by Roman Catholic countries, where the day following Thursday 4 October 1582 was Friday 15 October 1582. The British and Americans (among others) did not follow suit until 1752, when Wednesday 2 September was followed by Thursday 14 September. (Russia did not change until 1918, and Greece waited until 1923.) Thus there was a long period of time when history was recorded in two di erent styles. Write a program that will read in a date, determine which style it is in, and then convert it to the other style. 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 151 Power Crisis During the power crisis in New Zealand this winter (caused by a shortage of rain and hence low levels in the hydro dams), a contingency scheme was developed to turn o the power to areas of the country in a systematic, totally fair, manner. The country was divided up into N regions (Auckland was region number 1, and Wellington number 13). A number, m, would be picked at random', and the power would rst be turned o in region 1 (clearly the fairest starting point) and then in every m'th region after that, wrapping around to 1 after N , and ignoring regions already turned o . For example, if N = 17 and m = 5, power would be turned o to the regions in the order:1,6,11,16,5,12,2,9,17,10,4,15,14,3,8,13,7. The problem is that it is clearly fairest to turn o Wellington last (after all, that is where the Electricity headquarters are), so for a given N , the random' number m needs to be carefully chosen so that region 13 is the last region selected. Write a program that will read in the number of regions and then determine the smallest number m that will ensure that Wellington (region 13) can function while the rest of the country is blacked out. ## Input and Output 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 ## ACM Contest Problems Archive 152 ## University of Valladolid (SPAIN) 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 classi cation 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 and Output 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 justi ed 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 ## Thus the string acab' can be characterised in this sequence as 5. Write a program that will read in a string and determine its position in the ordered sequence of permutations of its constituent characters. Note that numbers of permutations can get very large; however we guarantee that no string will be given whose position is more than 231 ? 1 = 2; 147; 483; 647. ## Input and Output 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 justi ed in a eld of width 10. Sample input bacaa abc cba # Sample output 15 1 6 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 di erent colours|red, orange, yellow, green and blue|and 5 wastes have been identi ed 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 and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 155 All Squares Geometrically, any square has a unique, well-de ned centre point. On a grid this is only true if the sides of the square are an odd number of points long. Since any odd number can be written in the form 2k+1, we can characterise any such square by specifying k, that is we can say that a square whose sides are of length 2k+1 has size k. Now de ne a pattern of squares as follows. 1. The largest square is of size k (that is sides are of length 2k+1) and is centred in a grid of size 1024 (that is the grid sides are of length 2049). 2. The smallest permissible square is of size 1 and the largest is of size 512, thus 1  k  512. 3. All squares of size k > 1 have a square of size k div 2 centred on each of their 4 corners. (Div implies integer division, thus 9 div 2 = 4). 4. The top left corner of the screen has coordinates (0,0), the bottom right has coordinates (2048, 2048). Hence, given a value of k, we can draw a unique pattern of squares according to the above rules. Furthermore any point on the screen will be surrounded by zero or more squares. (If the point is on the border of a square, it is considered to be surrounded by that square). Thus if the size of the largest square is given as 15, then the following pattern would be produced. 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. ## ACM Contest Problems Archive ## Input and Output ## University of Valladolid (SPAIN) 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 speci ed point, right justi ed in a eld of width 3. Sample input 500 113 941 0 0 0 Sample output 5 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 156 Ananagrams Most crossword puzzle fans are used to anagrams|groups of words with the same letters in di erent 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 de nitions 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 di ering 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 157 Route Finding Many cities provide a comprehensive public transport system, often integrating bus routes, suburban commuter train services and underground railways. Routes on such systems can be categorised according to the stations or stops along them. We conventionally think of them as forming lines (where the vehicle shuttles from one end of the route to the other and returns), loops (where the two ends of the \branch" are the same and vehicles circle the system in both directions) and connections, where each end of the route connects with another route. Obviously all of these can be thought of as very similar, and can connect with each other at various points along their routes. Note that vehicles can travel in both directions along all routes, and that it is only possible to change between routes at connecting stations. To simplify matters, each route is given a designation letter from the set A' to Z', and each station along a route will be designated by another letter from the set a' to z'. Connecting stations will have more than one designation. Thus an example could be: a 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 identi er 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 identi ed at least once, and if there are more than two lines meeting at a connection, some or of all the alternative designations may be identi ed together. That is, there may be sequences ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 justi ed 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 speci ed, 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 justi ed 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 ## ACM Contest Problems Archive Sample output Today is: 20 12 20 12 *TODAY* Unspecified Anniversary 23 12 *** Partner's birthday 25 12 *** Christmas ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 159 Word Crosses A word cross is formed by printing a pair of words, the rst horizontally and the second vertically, so that they share a common letter. A leading word cross is one where the common letter is as near as possible to the beginning of the horizontal word, and, for this letter, as close as possible to the beginning of the vertical word. Thus DEFER and PREFECT would cross on the rst 'E' in each word, PREFECT and DEFER would cross on the 'R'. Double leading word crosses use two pairs of words arranged so that the two horizontal words are on the same line and each pair forms a leading word cross. Write a program that will read in sets of four words and form them (if possible) into double leading word crosses. 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 de ned 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 ## Unable to make two crosses ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 160 Factors and Factorials The factorial of a number N (written N !) is de ned as the product of all the integers from 1 to N . It is often de ned recursively as follows: 1! = 1 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 speci ed 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 justi ed 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 justi ed 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 161 Trac Lights One way of achieving a smooth and economical drive to work is to catch' every trac light, that is have every signal change to green as you approach it. One day you notice as you come over the brow of a hill that every trac light you can see has just changed to green and that therefore your chances of catching every signal is slight. As you wait at a red light you begin to wonder how long it will be before all the lights again show green, not necessarily all turn green, merely all show green simultaneously, even if it is only for a second. Write a program that will determine whether this event occurs within a reasonable time. Time is measured from the instant when they all turned green simultaneously, although the initial portion while they are all still green is excluded from the reckoning. 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 trac 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 trac 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 162 Beggar My Neighbour \Beggar My Neighbour" (sometimes known as \Strip Jack Naked") is a traditional card game, designed to help teach beginners something about cards and their values. A standard deck is shued and dealt face down to the two players, the rst card to the non-dealer, the second to the dealer, and so on until each player has 26 cards. The dealer receives the last card. The non-dealer starts the game by playing the top card of her deck (the second last card dealt) face up on the table. The dealer then covers it by playing her top card face up. Play continues in this fashion until a \face" card (Ace, King, Queen or Jack) is played. The next player must then \cover" that card, by playing one card for a Jack, two for a Queen, three for a King and four for an Ace. If a face card is played at any stage during this sequence, play switches and the other player must cover that card. When this sequence has ended, the player who exposed the last face card takes the entire heap, placing it face down under her existing deck. She then starts the next round by playing one card face up as before, and play continues until one player cannot play when called upon to do so, because they have no more cards. Write a program that will simulate playing this game. Remember that a standard deck (or pack) of cards contains 52 cards. These are divided into 4 suits|Spades (), Hearts (~), Diamonds (}) and Clubs (|). Within each suit there are 13 cards|Ace (A), 2{9, Ten (T), Jack (J), Queen (Q) and King (K). 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 justi ed 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 163 City Directions When driving through a city, an intersection usually o ers one the choice of going straight on or turning left or right through 90 degrees. However some cities have diagonal roads, thus at intersections involving these one may be able to turn through 45 degrees (\half") or through 135 degrees (\sharp"). Consider such a city with Avenues running north-south, Streets running east-west and Boulevards running diagonally. The central Avenue and Street are labelled Zero (A0 and S0). Other roads are labelled relative to these, thus A3W is the third avenue to the west of A0. There are 6 Boulevards|two passing through the centre of the city, and 4 others, one in each quadrant. The diagram below shows the northwest quadrant of a small version of such a city. 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 speci ed 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: ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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: ## <command> ::= <turn command> j <straight command> <turn command> ::= TURN [HALF j SHARP] fLEFT j RIGHTg <straight command> ::= GO [STRAIGHT] n 1  n  99 Write a program that will simulate driving through such a city, by tracking your position and heading as you follow a set of directions (commands). Each quadrant of the city will be 50 blocks by 50 blocks, thus the entire city will be 100 blocks by 100 blocks, the outer throughways will be labelled Fifty and the major and minor boulevards will cross at roads labelled Twenty ve. You will be told your starting position and heading and then given a series of directions. If a direction does not follow the above grammar, or would involve an illegal or impossible turn then ignore it. At no stage will directions take you out of the con nes of the city. Input ## Input will consist of a series of scenarios. Each scenario will consist of a position and a heading and will be followed by a series of directions (commands), each on a separate line. If either of the roads involved is one of the central roads (A0, S0), they will be labelled N or E as appropriate. Note that you may assume that you have just left the intersection speci ed. The GO <n> command means that you pass through <n> intersections. Each scenario will be terminated by a line consisting of the word STOP. The le will be terminated by a line consisting of the word END only. Input data will follow the format shown below, except that more than one space may occur where only one is shown. No line will be longer than 80 characters. 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. ## ACM Contest Problems Archive 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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 164 String Computer Extel have just brought out their newest computer, a string processing computer dubbed the X9091. It is hoped that it will have some value in cryptography and related elds. (It is rumoured that the Taiwanese are working on a clone that will correct Stage 1 essays, but we will ignore such vapourware). This computer will accept input strings and produce output strings from them, depending on the programs loaded into them at the time. The chip is the ultimate in RISC technology|it has only three transformation instructions:  Delete a character at a particular position.  Insert a character at a particular position.  Change the character at a particular position to a di erent character. Programs for this machine are written in a form of machine code where each instruction has the format ZXdd---Z represents the code for the instruction (D, I or C), X is a character and dd represents a two digit number. A program is terminated by a special halt instruction consisting of the letter E'. Note that each instruction works on the string in memory at the time the instruction is executed. To see how this all works consider the following example. It is desired to transform the string abcde' to the string bcgfe'. This could be achieved by a series of Change commands, but is not minimal. The following program is better. Da01 Cg03 If04 E abcde bcde bcge bcgfe bcgfe ## % note the a' is necessary because it is checked by the hardware % Terminates the program 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 satis es these criteria will be accepted. ## Input and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 di erent 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 of1.
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 justi ed in elds 3 characters wide, followed by a space and an arrow (->) and the value of n(h; k) right justi ed in a eld 3 characters wide. Sample input 3 2 0 0 Sample output 1 3 -> 7 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 166 Making Change Given an amount of money and unlimited (almost) numbers of coins we know that an amount of money may be made up in a variety of ways. A more interesting problem arises when goods are bought and need to be paid for, with the possibility that change may need to be given. Given the nite resources of most wallets nowadays, we are constrained in the number of ways in which we can make up an amount to pay for our purchases|assuming that we can make up the amount in the rst place, but that is another story. The problem we will be concerned with will be to minimise the number of coins that change hands at such a transaction, given that the shopkeeper has an adequate supply of all coins. (The set of New Zealand coins comprises 5c, 10c, 20c, 50c,$1 and $2.) Thus if we need to pay 55c, and we do not hold a 50c coin, we could pay this as 2*20c + 10c + 5c to make a total of 4 coins. If we tender$1 we will
receive 45c in change which also involves 4 coins, but if we tender $1.05 ($1 + 5c), we get 50c change
and the total number of coins that changes hands is only 3.
Write a program that will read in the resources available to you and the amount of the purchase and
will determine the minimum number of coins that change hands.

Input

Input will consist of a series of lines, each line de ning a di erent 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 sucient 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 de ned in the input. Each line will consist of the minimum number of coins that change hands right justi ed 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 ## ACM Contest Problems Archive 167 ## University of Valladolid (SPAIN) ## The Sultan's Successors 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 justi ed 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 168 Theseus and the Minotaur Those of you with a classical education may remember the legend of Theseus and the Minotaur. This is an unlikely tale involving a bull headed monster, an underground maze full of twisty little passages all alike, love-lorn damsels and balls of silk. In line with the educational nature of this contest, we will now reveal the true story. The maze was actually a series of caverns connected by reasonably straight passages, some of which could only be traversed in one direction. In order to trap the Minotaur, Theseus smuggled a large supply of candles into the Labyrinth, as he had discovered that the Minotaur was afraid of light. Theseus wandered around somewhat aimlessly until he heard the Minotaur approaching along a tunnel. At this point he lit a candle and set o in pursuit. The Minotaur retreated into the cavern it had just left and ed by another passage. Theseus followed, slowly gaining, until he reached the k'th cavern since lighting the candle. Here he had enough time to place the lighted candle in the middle of the cavern, light another one from it, and continue the chase. As the chase progressed, a candle was left in each k'th cavern passed through, thereby limiting the movement of the Minotaur. Whenever the Minotaur entered a cavern, it would check the exits in a particular order, eeing down the rst that did not lead directly to a lit cavern. (Remember that as Theseus was carrying a lit candle, the Minotaur never exited a cavern by the tunnel used to enter it.) Eventually the Minotaur became trapped, enabling Theseus to defeat it. Consider the following Labyrinth as an example, where in this case the Minotaur checks the exits from a cavern in alphabetical order: 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 identi ers 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 ## ACM Contest Problems Archive shown in the example below. 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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 de nite 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 di erent 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 di erent 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 di erent 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 speci ed 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 # ## ACM Contest Problems Archive Sample output dyj ortj lnsvkoalexot * * ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 170 Clock Patience Card sharp Albert (Foxy) Smith is writing a book on patience games. To double check the examples in the book, he is writing programs to nd the optimal play of a given deal. The description of Clock Patience reads as follows: \The cards are dealt out (face down) in a circle, representing a clock, with a pile in each hour position and an extra pile in the centre of the clock. The rst card goes face down on one o'clock, the next on two, and so on clockwise from there, with each thirteenth card going to the center of the clock. This results in thirteen piles, with four cards face down in each pile. 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 shued decks, and play the game. ## Input and Output 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 171 Car Trialling Car trialling requires the following of carefully worded instructions. When setting a trial, the organiser places traps in the instructions to catch out the unwary. Write a program to determine whether an instruction obeys the following rules, which are loosely based on real car trialling instructions. BOLD-TEXT indicates text as it appears in the instruction (case sensitive), j separates options of which exactly one must be chosen, and .. expands, so A..D is equivalent to AjBjCjD . instruction = navigational j time-keeping j navigational AND time-keeping navigational = directional j navigational AND THEN directional directional = how direction j how direction where how = GO j GO when j KEEP direction = RIGHT j LEFT when = FIRST j SECOND j THIRD where = AT sign sign = "signwords" signwords = s-word j signwords s-word s-word = letter j s-word letter letter = A..Z j . time-keeping = record j change record = RECORD TIME change = cas TO nnn KMH cas = CHANGE AVERAGE SPEED j CAS nnn = digit j nnn digit digit = 0..9 Note that s-word and nnn are sequences of letters and digits respectively, with no intervening spaces. There will be one or more spaces between items except before a period (.), after the opening speech marks or before the closing speech marks. 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 justi ed 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. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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. ## KEEP LEFT AND THEN GO RIGHT CAS TO 20 KMH GO FIRST RIGHT AT "SMITH ST." AND CAS TO 20 KMH Trap! Trap! Trap! ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 172 Calculator Language Calculator Language (CL) supports assignment, positive and negative integers and simple arithmetic. The allowable characters in a CL statement are thus: A..Z variable names 0..9 digits + addition operator subtraction operator * multiplication operator / integer division operator = assignment operator () brackets negative sign All operators have the same precedence and are right associative, thus 15 ? 8 ? 3 = 15 ? (8 ? 3) = 10. As one would expect, brackets will force the expression within them to be evaluated rst. Brackets may be nested arbitrarily deeply. An expression never has two operators next to each other (even if separated by a bracket), an assignment operator is always immediately preceded by a variable and the leftmost operator on a line is always an assignment. For readability, spaces may be freely inserted into an expression, except between a negative sign and a number. A negative sign will not appear before a variable. All variables are initialised to zero (0) and retain their values until changed explicitly. Write a program that will accept and evaluate expressions written in this language. Each expression occupies one line and contains at least one assignment operator, and maybe more. 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 di erent 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 ## ACM Contest Problems Archive Sample output A = 4, B = 4 C = -4, D = 2 D = -4 No Change E = 40 Z = 3 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 173 Network Wars It is the year 2126 and comet Swift-Tuttle has struck the earth as predicted. The resultant explosion emits a large cloud of high energy neutrons that eliminates all human life. The accompanying electromagnetic storm causes two unusual events: many of the links between various parts of the electronic network are severed, and some postgraduate AI projects begin to merge and mutate, in much the same way as animal life did several million years ago. In a very short time two programs emerge, Paskill and Lisper, which move through the network marking each node they visit: Paskill activates a modi ed Prolog interpreter and Lisper activates the Hello World' program. However Hello World' has mutated into an endless loop that so ties up the node that no other program, not even Lisper, can re-enter that node and the Prolog interpreter immediately reverse compiles (and destroys) any program that enters. However, Paskill knows which nodes it has visited and never tries to re-enter them. Thus if Lisper attempts to enter a node already visited by Paskill it will be annihilated; neither can enter a node already visited by Lisper, if either (or both) cannot move both will halt and if they ever arrive at a node simultaneously they annihilate each other. Both programs move through the network at the same speed. Write a program to simulate these events. All nodes in the the network are labelled with a single uppercase letter as shown below. When moving to the next node, Paskill searches alphabetically forwards from the current node, whereas Lisper searches alphabetically backwards from the current node, both wrapping round if necessary. Thus, (in the absence of the other) if Paskill enters the network below at A, it would visit the nodes in the order A, B, C, D, G, H, E, F; if Lisper enters the network at H it would visit them in the order H, G, E, F. Simulation stops when one or more of the above events occurs. If more than one event occurs, mention Paskill rst. 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 identi er, 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:  ## Lisper destroyed in node ? ## ACM Contest Problems Archive  fPaskill/Lisperg  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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 di erent 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 di erent 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: ## <program> ::= <statement>. <statement> ::= <command> j <ifstat> <ifstat> ::= IF <condition> THEN <statement> ELSE <statement> <condition> ::= <cond> j <cond> <op> <condition> <op> ::= AND j OR <cond> ::= <memory> f= j #g f<command> j NULLg <memory> ::= fMY j YOURg LAST f1 j 2g <command> ::= TRADE j CHEAT Note that LAST1 refers to the previous encounter between these two automata, LAST2 to the encounter before that and that MY' and YOUR' have the obvious meanings. Spaces and line breaks may appear anywhere in the program and are for legibility only. The symbol #' means is not equal to'. NULL indicates that an encounter has not ocurred. The following are valid programs: CHEAT. IF MY LAST1 = CHEAT THEN TRADE ELSE CHEAT. IFYOURLAST2=NULLTHENTRADEELSEIFYOURLAST1=TRADETHENTRADE ELSECHEAT. 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 justi ed in a eld of width 3. ## ACM Contest Problems Archive Sample input CHEAT. IF MY LAST1 = CHEAT THEN TRADE ELSE CHEAT. IFYOURLAST2=NULLTHENTRADEELSEIFYOURLAST1=TRADETHENTRADE ELSECHEAT. # Sample output 1 -12 -13 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 175 Keywords Many researchers are faced with an ever increasing number of journal articles to read and nd it dicult 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 pro le' 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 suciently' 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 pro le 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 pro les followed by a series of titles and determine which of the titles (if any) are selected by each of the pro les. A title is selected by a pro le if at least one pair of keywords from the pro le 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 pro les followed by no more than 250 titles. Each pro le and title will be numbered in the order of their appearance, starting from 1, although the numbers will not appear in the le.   Each pro le 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 pro le in the input. Each line will consist of the pro le 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. ## ACM Contest Problems Archive 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 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 176 City Navigation Most US cities are constructed according to a very simple plan|they have Avenues running north and south, and Streets running east and west, enclosing square blocks. Avenues and Streets are numbered, with numbers increasing westward and southward. There are 50 driveways on each side of a block, numbered 00 to 98 on one side and 01 to 99 on the other. House numbers increase in the same directions as Street and Avenue numbers. If you are travelling in the direction of increasing numbers then odd numbers are on your right. Thus the house at 1288 16th Street (S16 1288) is located on 16th Street, west of 12th Avenue and east of 13th Avenue, and is on the right-hand side going east. The residence described as A11 1543 lies on 11th Avenue, south of 15th Street and north of 16th Street, and is on the right-hand side going south. Both of these are marked on the following typical street map: 13th 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 dicult 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:   ## You drive on the right hand side of the road. You may not cross a lane of trac except at an intersection, that is you must turn right when entering or leaving a driveway. ## ACM Contest Problems Archive      ## University of Valladolid (SPAIN) ## Driveways are located in the centres of their sections. U-turns are illegal except at the end of cul de sacs. Streets and Avenues are numbered from 00 to 49 and there are no roads beyond these bounds; however there are driveways on both sides of the bounding roads. Sections on corners have two driveways. A route exists between any pair of driveways. 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 identi er and a pair of house numbers. A road identi er 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 speci ed numbers on the identi ed 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 identi er (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 speci ed in the input (the number of driveways passed) written as an integer, left justi ed. 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 ## 1288 A11 1543 Sample output 213 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 177 Paper Folding If a large sheet of paper is folded in half, then in half again, etc, with all the folds parallel, then opened up at, there are a series of parallel creases, some pointing up and some down, dividing the paper into fractions of the original length. If the paper is only opened \half-way" up, so every crease forms a 90 degree angle, then (viewed end-on) it forms a \dragon curve". For example, if four successive folds are made, then the following curve is seen (note that it does not cross itself, but two corners touch): Write a program to draw the curve which appears after N folds. The exact speci cation 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 de nes 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 di erent number of folds is terminated by a line containing a single ^'. Sample input 2 4 1 0 ## ACM Contest Problems Archive Sample output |_ _| ^ _ _ |_|_| |_ _| _| |_| ^ _| ^ ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 178 Shuing Patience Many children enjoy playing cards, especially some of the simpler forms of patience or solitaire, yet many of them nd it dicult to shue the cards adequately. The following patience' game assists this as well as aiding card recognition and boosting simple arithmetic skills. The essence is to cover' exposed pairs or triples of cards that have a speci c relationship to each other. A deck of cards consists of 52 cards, in four suits of 13 ranks. The suits are spades, hearts, clubs, diamonds and the ranks run from ace (face value one), 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen and king. During play up to 16 piles in a 4 by 4 grid may be created if necessary, although usually fewer are needed. Deal cards, face up, in this 4  4 grid. Before playing each card check whether a pair or triple of cards already played can be covered. A pair of cards can be covered if they are of rank ace to ten and their face values add to 11. A triple of cards can be covered if they form the set fjack, queen, kingg. If no pairs or triples exist, a new pile is started. Where more than one pair and/or triple exists, only one is covered before reassessing. Cards are always covered in the same order they were dealt, that is left to right, top to bottom. The rst card covered shall be the eligible card nearest the start of play. The second card covered (and also the third for a triple) is its partner nearest the start of play. Thus if the rst part of a deck consists of: TS QC 8S 8D QH 2D 3H KH 9H..., then the rst seven cards will be played as follows: TS QC 8S 8D QH 2D 3H The next two cards (KH 9H) will then cover the pair 8S and 3H respectively. Note that covering pairs or triples is considered an indivisible operation, and thus further covering operations are not considered until it is complete. Write a program to simulate the playing of this game. Your program must read in one or more decks of cards, simulate the play and determine how many cards are on each pile at the end. If it is not possible to remain within the stipulated 16 piles, terminate that deal with a message as described below. Input Input will consist of a series of decks of cards, each deck speci ed as 4 lines each containing 13 cards. Each card will be speci ed 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 speci ed 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 justi ed in a eld 3 characters wide. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 179 Code Breaking Periodic permutation is a simple encryption technique which involves choosing a period, k, and a permutation of the rst k numbers. To encrypt a message, split the message into groups of k characters (padding if necessary) and apply the given permutation. Decryption involves taking groups of k characters and performing the inverse permutation. Thus for k = 4, a permutation could be 2431. This would encrypt Mary' to yMra' and Maryan' to yMra?a?n'. Once one knows the permutation, one can apply its inverse to other encrypted messages (cyphertext) to recover the original text (plaintext). Write a program that will read (plaintext, cyphertext1, cyphertext2) triples, and for each (plaintext, cyphertext1) pair determine whether or not a periodic permutation encryption method has been used. If it has, determine the value of k and the permutation function and apply the reverse permutation to cyphertext2 to recover the corresponding plaintext. 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? ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 180 Eeny Meeny In darkest <name of continent/island deleted to prevent o ence> lived a tribe called the \Eeny Meenys". They got this name from their way of choosing a chief for a year. It appears that a newspaper reporter visited the tribe and managed to get across a few ideas of civilisation, but apparently came to an unfortunate end before nishing the job. Thus the tribe no longer had a permanent chief; the chief's term was exactly one year. At the end of that time, they ate the current chief, and chose another chief. Their method of choosing a chief was the \Eeny meeny miny mo" method. All eligible tribal members (women were also eligible|one of the blessings of civilisation the tribe had adopted) stood in a circle, a starting place was chosen, and the chief medicine man (who was ineligible for chieftainship) went around counting out E', e', n', y', M', e', e', n', y', M',i', n', y', M', o!', E', e', n', y', M', e', e', n', y', M', i', n', y', M', o!', : : : . At every o!', the person indicated was pushed out of the circle which then closed up and the count restarted with his neighbour (the one who would have been E' anyway). This process continued until only one was left|the new chief. While the chance of glory for a year makes the job of chief highly attractive to tribal members, you (possessing a computer decades before they were invented) nd the brevity of the glory unappealing. You have managed to nd out that the count this year will start with Mxgobgwq (a very large person), so you would like to know where not to stand. You don't know the direction, nor how many eligible people there are, but you can estimate the number (it is certainly less than 500). Write a program that will determine the  rst' (i.e. closest to Mxgobgwq) safe position to stand, regardless of the actual number of people and the direction of count (clockwise or anti-clockwise). 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 di erent 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 simpli ed 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 speci ed. 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 justi ed in a eld of width 3. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 182 Bonus Bonds The government of Impecunia does not levy any taxes, instead it raises money by the (sometimes forced) sale of Bonus Bonds. Originally the Bonds were numbered using a 7 digit number pre xed by a one digit code in the range 1 to 9 representing the region of Impecunia in which the bond was sold. However the scheme has proved so popular that the numbering scheme has been extended by a further two digits. To retain compatibility with the previous scheme, the 8th digit from the right (the third from the left) still designates the region of sale. At the same time, a central' region was created and has been given the designation 0. For security reasons no bond may be numbered with a number consisting entirely of zeroes, thus, although the original bonds all started from zero (since the region code was non-zero), the bonds from the central region start from 0000000001. Each month, the winning numbers are drawn for each region independently. The equipment generates a stream of single digits and it would appear to be simple enough to collect these together in groups of ten and compare the results with the list of Bond-holders. However, the equipment is a little antiquated and is liable to various breakdowns, thus it is desirable to only generate numbers that lie within the allocated range and with the same distributions of digits at each position as would be found by examining all the bonds sold for that region. Thus if we wish to draw N numbers for a given region, the equipment is set to generate 10 streams of N digits, one for each position. The rst winning number is then made up by taking the rst digit from each stream, the second winning number is composed of the second digit in each stream, and so on. For each stream, the equipment is adjusted so that the distribution of digits it generates closely matches the actual distributions of digits in that position on the allocated Bonds. The state auditors generate a table of these distributions so that the two may be compared. Write a program that will generate the table for the state auditors for any given draw. For each region, the program will read the serial number of the next bond to be sold in that region so that it can calculate the distributions. Since the output is voluminous, your program will only need to print the digit distribution for a particular digit position. 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 justi ed in a eld of width 11. Separate tables by one blank line. Sample input 4810000000 1 0000000000 0 ## ACM Contest Problems Archive Sample output 100000000 100000000 100000000 100000000 80000000 0 0 0 0 0 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 183 Bit Maps The bitmap is a data structure that arises in many areas of computing. In the area of graphics, for example, a bitmap can represent an image by having a 1 represent a black pixel and a 0 represent a white pixel. Consider the following two ways of representing a rectangular bit map. In the rst, it is simply represented as a two dimensional array of 1s and 0s. The second is based on a decomposition technique. First, the entire bit map is considered. If all bits within it are 1, a 1 is output. If all bits within it are 0, a 0 is output. Otherwise, a D is output, the bit map is divided into quarters (as described below), and each of those is processed in the same way as the original bit map. The quarters are processed in top left, top right, bottom left, bottom right order. Where a bit map being divided has an even number of rows and an even number of columns, all quarters have the same dimensions. Where the number of columns is odd, the left quarters have one more column than the right. Where the number of rows is odd the top quarters have one more row than the bottom. Note that if a region having only one row or one column is divided then two halves result, with the top half processed before the bottom where a single column is divided, and the left half before the right if a single row is divided. Write a program that will read in bitmaps of either form and transform them to the other form. 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 justi ed 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 184 Laser Lines A computer chip manufacturer has discovered a new way to combine opto-electronics and ordinary electronics by forming light-emitting and receiving nodes on the surface of the chip. These can be used to send messages to each other in a direct line-of-sight manner, thereby speeding up operation considerably by allowing a much greater density of information transfer. One diculty is that the nodes must all be able to send messages to each other; no node should block the line-of-sight between two other nodes. The manufacturing method ensures that the nodes will be positioned exactly on the points of a lattice covering the chip, so their coordinates are given by integers between 0 and 9999 (inclusive) except that for technical reasons no node can appear at point (0, 0). Write a program that will read in sets of coordinates of these nodes and determine whether any of them lie on lines containing three or more nodes. Because of the layout method used, it is envisaged that there may well be several lines containing three nodes, but that longer' lines will be increasingly rare. However, no line will contain more than 10 points. 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 ## ACM Contest Problems Archive 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) ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 185 Roman Numerals The original system of writing numbers used by the early Romans was simple but cumbersome. Various letters were used to represent important numbers, and these were then strung together to represent other numbers with the values decreasing monotonically from left to right. The letters they used and the numbers that were represented are given in the following table. I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Thus 1993 was written as MDCCCCLXXXXIII. This system was then superseded by a partially placeoriented system, whereby if the above rule of decreasing values was broken, it meant that the immediately preceding (lower) value was deemed to be negative' and was subtracted from the higher (out of place) value. In this system 1993 was usually written as MCMXCIII. There is still some controversy as to which letters could precede which other letters, but for the purposes of this problem we will assume the following restrictions: 1. A letter from the left column can never appear more than three times in a row, and there can never be more than one other occurrence of that letter. 2. A letter from the right column can never appear more than once. 3. Once a letter has been used in a negative' position, all subsequent characters (apart from the one immediately following) may not be greater than that character. Thus we could write MXMIII for 1993 or CCXCIV for 294, however we could not write ILV for 54, nor could we write LIL for 99. Note that 299 could be written as CCXCIX or CCIC Given a Roman sum, we can either interpret it as such or as an encoding of an Arabic sum. Thus V+V=X could be interpreted as an ambiguous encoding of an Arabic sum with V 2 f1, 2, 3, 4g and X = 2 * V. Similarly, X+X=XX could be interpreted as a correct Roman sum but an impossible Arabic encoding (apart from the trivial encoding X = 0) and XX+XX=MXC as an incorrect Roman sum, but a valid encoding with M = 1, X = 9, and C = 8. Write a program that will read in sums in Roman numerals and determine whether or not they are correct as Roman sums and also whether they are impossible, ambiguous or valid as Arabic encodings. Assume that zero will never appear on its own or as a leading digit, and that no two Roman numerals map onto the same Arabic digit. 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 #. ## ACM Contest Problems Archive Output ## University of Valladolid (SPAIN) 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 186 Trip Routing Your employer, the California Car Club (CCC), has decided to provide a trip routing service to its members. Your job is to write a program which reads a list of departure point-destination point pairs and calculates the shortest routes between them. For each trip, your program will print a report which itemises the names of each city passed through, with route names and leg distances. Input ## Input to your program will be in two parts. The rst part is a map in the form of a list of highway segments. Each segment is designated by a line containing four elds which are separated by commas. The rst two elds are 1{20 characters each, and are the names of the cities which are at each end of the highway segment. The third eld is the 1{10 character name of the route. The fourth eld is the number of miles between the two endpoints, expressed as a positive integer. The highway segment list will be terminated by an empty line. The second part of the input is a list of departure point-destination point pairs, one per line. The departure point is given rst, followed by a comma and the destination point. Each of the cities is guaranteed to have appeared in the rst part of the input data, and there will be a path that connects them. The list is terminated by the end of le. 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 ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) 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. ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 187 Transaction Processing You have been called upon to write a program which performs one of the initial steps in posting transactions to a general ledger. The central principle of double-entry bookkeeping is that the sum of all debits must equal the sum of all credits. This is true for each transaction. For the purposes of your program, positive numbers represent debits and negative numbers represent credits. That is, 2:00 is a two dollar debit, and ?2:00 is a two dollar credit. The purpose of your program is to check that each transaction balances, and to report it if it doesn't. Input ## Input data to your program will come in two sections. The rst section is a list of up to 100 accounts in the general ledger. It consists of lines in the format: nnnxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ## where nnn is a three-digit account number and xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx is a 1{30 character account name string. This section is terminated by a record starting with 000, which is not used as an account number. The second section of the input data consists of 15-character records, one per line in the format sssnnnxxxxxxxxx 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 ## Transaction sss is out of balance *** xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx vvvvvvv.vv xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx vvvvvvv.vv Out of Balance vvvvvvv.vv ## where nnn is an account number, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx is the corresponding account name, and vvvvvvv.vv is the amount. Print a space between the above elds. The entries should be listed in the order that they were received in the input. The last entry in the report is one you will create to make the transaction balance, using the special account number 999 (the suspense account). Print a blank line after each exception report. ## ACM Contest Problems Archive 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 ## Transaction 101 is out of balance *** Accounts Receivable 1.05 Sales Tax Payable -0.07 Sales -1.00 Out of Balance 0.02 *** 211 555 999 ## Transaction 102 is out of balance *** Accounts Payable -700.00 Office Supplies 400.00 Out of Balance 300.00 ## University of Valladolid (SPAIN) ## ACM Contest Problems Archive ## University of Valladolid (SPAIN) ## 188 Perfect Hash Perfect Software, Inc. has obtained a government contract to examine text owing through a high-speed network for the occurrence of certain words. Your boss, Wally Perfect, has designed a parallel processing system which checks each word against a group of small perfect hash tables. A perfect hash function maps its input directly to a fully occupied table. Your job is to construct the perfect hash functions from the lists of words in each table. The hash function is of the form bC=wc mod n, where C is a positive integer you are to discover, w is an integer representation of an input word, and n is the length of the table. C must be as small as possible. Note that bc is the oor function and that bRc for some real number R is the largest integer that is  R. Here are Wally's notes on the subject: Let W = fw1; w2; : : : ; wng consist of positive integers w1 < w2 < : : : < wn . The problem is to nd the smallest positive integer C such that jCk jCk mod n 6= w w mod n for all 1  i < j  n. i ## must be a multiple of at least one element of W . If some jCk jCk mod n = w w mod n i 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 and Output

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

## ACM Contest Problems Archive

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

## 189 Pascal Program Lengths

Your local computer user's group publishes a quarterly newsletter, and in each issue there is a small
Turbo Pascal programming problem to be solved by the membership. Members submit their solutions
to the problem to the newsletter editor, and the member submitting the shortest solution to the problem
The length of a program is measured in units. The unit count is determined by counting all occurrences of reserved words, identi ers, constants, left parentheses, left brackets, and the following operators:
+, -, *, /, =, <, >, <=, >=, <>, @, ^, and :=. Comments are ignored, as are all other symbols
not falling into one of the categories mentioned above. The program with the lowest unit count is
declared the winner. Two or more programs with equal unit counts split the prize for the quarter.
In an e ort to speed the judging of the contest, your team has been asked to write a program that
will determine the length of a series of Pascal programs and print the number of units in each.

## Input and Output

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;
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:
 Identi ers 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:

## ACM Contest Problems Archive

 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.

## 190 Circle Through Three Points

Your team is to write a program that, given the Cartesian coordinates of three points on a plane, will
nd the equation of the circle through them all. The three points will not be on a straight line.
The solution is to be printed as an equation of the form
and an equation of the form

(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

## ACM Contest Problems Archive

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

## ACM Contest Problems Archive

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)

## Figure 1: Line segment does not intersect rectangle

The line is said to intersect the rectangle if the line and the rectangle have at least one point in
common. The rectangle consists of four straight lines and the area in between. Although all input values
are integer numbers, valid intersection points do not have to lay on the integer grid.

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:

## xstart ystart xend yend xleft ytop xright ybottom

where (xstart; ystart) is the start and (xend; yend) the end point of the line and (xleft; ytop) the top
left and (xright; ybottom) the bottom right corner of the rectangle. The eight numbers are separated
by a blank. The terms top left and bottom right do not imply any ordering of coordinates.

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

the rectangle.

Sample Input
1
4 9 11 2 1 5 7 1

Sample Output
F

## 192 Synchronous Design

The designers of digital integrated circuits (IC) are very concerned about the correctness of their designs
because, unlike software, ICs cannot be easily tested. Real tests are not possible until the design has
been nalized and the IC has been produced.
To simulate the behavior of a digital IC and to more or less guarantee that the nal chip will work,
all of today's digital ICs are based on a synchronous design.

## Figure 1: The critical path (dashed line) takes 43ns to settle

In a synchronous design, an external clock signal triggers the IC to go from a well de ned and stable
state to the next one. On the active edge of the clock, all input and output signals and all internal
nodes are stable in either the high or low state. Between two consecutive edges of the clock, the signals
and nodes are allowed to change and may take any intermediate state. The behavior of a synchronous
network is predictable and will not fail due to hazards or glitches introduced by irregularities of the real
circuit.
To analyze whether an IC has a synchronous design, we distinguish between synchronous and
asynchronous nodes. Flip ops are synchronous nodes. On the active edge of the clock, the output
of the ip op changes to the state of the input and holds that state throughout the next clock cycle.
Synchronous nodes are connected to the clock signal.
Simple gates like ANDs or ORs are asynchronous nodes. Their output changes - with a short delay
- whenever one of their inputs changes. During that transition phase, the output can even go into some
unde ned or intermediate state.
For simplicity, we assume that all inputs of the circuits are directly connected to the output of a
synchronous node outside the circuit and that all outputs of the circuit are directly connected to the
input of a synchronous node outside the circuit.

## For an IC to have a synchronous design, mainly two requirements must be met:



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.

## Figure 2: The design contains a cycle (dashed line)

Your are to write a program that decides for a given IC whether it has a synchronous design or not.
You are given a network of synchronous and asynchronous nodes, a delay for each node, some inputs
and outputs and the clock period.
You may safely assume that




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.

## Figure 3: A synchronous design

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



## the circuit has a synchronous design.

< ss > should be replaced by the longest delay found on any path between two synchronous nodes.
"Circuit contains cycle." if the circuit contains a cycle composed exclusively of asynchronous
nodes.
Clock period exceeded." if there is a path between two synchronous nodes that is longer than
the given clock period and there are no cycles composed of asynchronous nodes.

## ACM Contest Problems Archive

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

## 193 Graph Coloring

You are to write a program that tries to nd an optimal coloring for a given graph. Colors are applied
to the nodes of the graph and the only available colors are black and white. The coloring of the graph
is called optimal if a maximum of nodes is black. The coloring is restricted by the rule that no two
connected nodes may be black.

## Input and Output

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

## ACM Contest Problems Archive

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 de ne 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  .

## ACM Contest Problems Archive

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 unde ned and has to be calculated. All
oating-point numbers include at least eight signi cant 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 signi cant digits. Your calculations
should be precise enough to get the six most signi cant 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.

## ACM Contest Problems Archive

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 di erent 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 di erent.

Output

For each word in the input le, the output le should contain all di erent 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

## ACM Contest Problems Archive

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

:::

:::

:::

:::

:::

:::

:::
:::
:::
:::
:::
:::
:::

## Figure 1: Naming of the top left cells

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.

## ACM Contest Problems Archive

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

## ACM Contest Problems Ar hive

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:

## Figure 1: The seven pie es that on e formed a ube

The seven pie es an be assembled in many ways to again form the ube. Figure 2 shows one of
these possibilities. The rst square stands for the front plane, the next one for the middle plane and
the last one for the ba k plane of the ube. The letters in the ells stand for the name of pie e lling
out the orresponding spa e in the ube. The name of the seven pie es an be found in gure 1.
a d
a
a a

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

## Figure 2: Two possibilities of assembling the ube

You are to write a program that outputs all possibilities of assembling the ube but suppress solutions
that are mere rotations of another solution.
Hint: Pie e a is the only part that, by rotation and translation, annot be transformed into itself.
In order to avoid solutions that are mere rotations of an already found solution, you may restri t
transformations of pie e a to translations.

## ACM Contest Problems Ar hive

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.

## The solutions in gure 2 would be represented like this:

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.

## Figure 3: Positions of the ells in the string

Figure 3 again shows how the ells of the ube are linearized.
Sample input

aa.a..a....................
.........a..a..aa..........

Sample output

...
...

## ACM Contest Problems Archive

198

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 unde ned 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 rede ne 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.
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 ] de nes 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".

## ACM Contest Problems Archive

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 unde ned:
 if it has not yet been de ned or it refers to a variable, which has not yet been de ned;
 if the de nition of the variable contains a cycle.
Your are to write a program that implements Peter's calculator. It should store all variable de nitions
and for each "PRINT" statement evaluate the speci ed variable based on the latest variable de nitions. If
your program encounters a "RESET" statement, it should delete all stored variables so that all variables
become unde ned.

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 speci ed variable or the word "UNDEF" if the variable is unde ned.

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

## 199 Partial di erential equations

In engineering sciences, partial di erential equations play an important and central role. For example,
the temperature of a metal plate can be expressed as a partial di erential equation if the temperature
on the boundaries is known. This is called a boundary value problem.
Usually, it is not easy to solve these problems. Analytical solutions exist only in very special cases.
But there are some more or less "good" numerical ways to solve boundary value problems.
We now will look at one method which works with nite di erence approximations for the derivatives
of a function. For this approach, we do not look at an analytical function u(x) but we are only interested
in the values of u at a nite set of discrete points x : u = u(x ). The distance between two adjacent
points, x and x +1 , is constant: h = x +1 ? x (cf. gure 1).
i

## The nite di erence approximation of a rst derivative of the function u(x) is

@ u = 1 (?u + u )
@x 2h ?1 +1
The second derivative is approximated by
i

(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

i;j

## On the boundary, u(x ; y ) is given by 4 known functions:

i

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

## ACM Contest Problems Archive

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 de ned 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.

## ACM Contest Problems Archive

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