ProblemasACM 2007II
ProblemasACM 2007II
ProblemasACM 2007II
Problem: Quicksum
A checksum is an algorithm that scans a packet of data and returns a single number. The idea is that if the
packet is changed, the checksum will also change, so checksums are often used for detecting transmission
errors, validating document contents, and in many other situations where it is necessary to detect
undesirable changes in data.
For this problem, you will implement a checksum algorithm called Quicksum. A Quicksum packet allows only
uppercase letters and spaces. It always begins and ends with an uppercase letter. Otherwise, spaces and
letters can occur in any combination, including consecutive spaces.
A Quicksum is the sum of the products of each character's position in the packet times the character's value.
A space has a value of zero, while letters have a value equal to their position in the alphabet. So, A=1, B=2,
etc., through Z=26. Here are example Quicksum calculations for the packets "ACM" and "MID CENTRAL":
ACM: 1*1 + 2*3 + 3*13 = 46
MID CENTRAL: 1*13 + 2*9 + 3*4 + 4*0 + 5*3 + 6*5 + 7*14 + 8*20 + 9*18 + 10*1 + 11*12 = 650
Input
The input consists of one or more packets followed by a line containing only # that signals the end of the
input. Each packet is on a line by itself, does not begin or end with a space, and contains from 1 to 255
characters.
Output
For each packet, output its Quicksum on a separate line in the output.
Example Input:
Example Output:
ACM
MID CENTRAL
REGIONAL PROGRAMMING CONTEST
ACN
ACM
ABC
BBC
#
46
650
4690
49
75
14
15
2.
This problem is inspired by Pachinko, a popular game in Japan. A traditional Pachinko machine is a cross
between a vertical pinball machine and a slot machine. The player launches small steel balls to the top of the
machine using a plunger as in pinball. A ball drops through a maze of pins that deflect the ball, and
eventually the ball either exits at a hole in the bottom and is lost, or lands in one of many gates scattered
throughout the machine which reward the player with more balls in varying amounts. Players who collect
enough balls can trade them in for prizes.
For the purposes of this problem, a linear Pachinko machine is a sequence of one or more of the following:
holes ("."), floor tiles ("_"), walls ("|"), and mountains ("/\"). A wall or mountain will never be adjacent to
another wall or mountain. To play the game, a ball is dropped at random over some character within a
machine. A ball dropped into a hole falls through. A ball dropped onto a floor tile stops immediately. A ball
dropped onto the left side of a mountain rolls to the left across any number of consecutive floor tiles until it
falls into a hole, falls off the left end of the machine, or stops by hitting a wall or mountain. A ball dropped
onto the right side of a mountain behaves similarly. A ball dropped onto a wall behaves as if it were dropped
onto the left or right side of a mountain, with a 50% chance for each. If a ball is dropped at random over the
machine, with all starting positions being equally likely, what is the probability that the ball will fall either
through a hole or off an end?
For example, consider the following machine, where the numbers just indicate character positions and are
not part of the machine itself:
123456789
/\.|__/\.
The probabilities that a ball will fall through a hole or off the end of the machine are as follows, by position:
1=100%, 2=100%, 3=100%, 4=50%, 5=0%, 6=0%, 7=0%, 8=100%, 9=100%. The combined probability for
the whole machine is just the average, which is approximately 61.111%.
Input: The input consists of one or more linear Pachinko machines, each 179 characters long and on a line
by itself, followed by a line containing only "#" that signals the end of the input.
Output: For each machine, compute as accurately as possible the probability that a ball will fall through a
hole or off the end when dropped at random, then output a single line containing that percentage truncated to
an integer by dropping any fractional part.
Example input:
Example output:
/\.|__/\.
_._/\_|.__/\./\_
...
___
./\.
_/\_
_|.|_|.|_|.|_
____|_____
#
61
53
100
0
100
50
53
10
3.
The D-pairs of a string of letters are the ordered pairs of letters that are distance D from each other. A string
is D-unique if all of its D-pairs are different. A string is surprising if it is D-unique for every possible distance D.
Consider the string ZGBG. Its 0-pairs are ZG, GB, and BG. Since these three pairs are all different, ZGBG is
0-unique. Similarly, the 1-pairs of ZGBG are ZB and GG, and since these two pairs are different, ZGBG is 1unique. Finally, the only 2-pair of ZGBG is ZG, so ZGBG is 2-unique. Thus ZGBG is surprising. (Note that
the fact that ZG is both a 0-pair and a 2-pair of ZGBG is irrelevant, because 0 and 2 are different distances.)
Input
The input consists of one or more nonempty strings of at most 79 uppercase letters, each string on a line by
itself, followed by a line containing only an asterisk that signals the end of the input.
Output
For each string of letters, output whether or not it is surprising using the exact output format shown below.
Acknowledgement: This problem is inspired by the "Puzzling Adventures" column in the December 2003
issue of Scientific American.
Example input:
Example output:
ZGBG
X
EE
AAB
AABA
AABB
BCBABCC
*
ZGBG is surprising.
X is surprising.
EE is surprising.
AAB is surprising.
AABA is surprising.
AABB is NOT surprising.
BCBABCC is NOT surprising.
4.
Imagine disks of ice falling, one at a time, into a box, each ending up at the lowest point it can reach without
overlapping or moving previous disks. Each disk then freezes into place, so it cannot be moved by later
disks. Your job is to find the overall height of the final combination of disks.
So that the answer is unique, assume that any disk reaching the bottom of the box rolls as far to the left as
possible. Also the data is chosen so there will be a unique lowest position for any disk that does not reach
the bottom. The data is also such that there are no "perfect fits": each disk that lands will be in contact with
only two other points, on previous circles or the sides of the box. The illustrations above show white filled
disks labeled with the order in which they fall into their boxes. The gray circle in the fourth illustration is not
intended to be a disk that fell in. The gray disk is included to demonstrate a point: the gray disk is the same
size as disk 2, so there is space for disk 2 on the very bottom of its box, but disk 2 cannot reach that position
by falling from the top. It gets caught on disk 1 and the side of the box.
One way to find the top intersection point of two intersecting circles is as follows. Suppose circle 1 has center
(x1, y1) and radius r1, and suppose circle 2 has center (x2, y2), and radius r2. Also assume that circle 1 is to
the left of circle 2, i.e., x1 < x2. Let
dx = x2 - x1,
dy = y2 - y1,
D = sqrt(dx*dx + dy*dy),
E = (r1*r1 - r2*r2 + D*D)/(2*D),
F = sqrt(r1*r1 - E*E);
then the upper intersection point is (x1 + (E*dx - F*dy)/D, y1 + (F*dx + E*dy)/D).
Input
The input consists of one or more data sets, followed by a line containing only 0 that signals the end of the
input. Each data set is on a line by itself and contains a sequence of three or more blank-separated positive
integers, in the format w, n, d1, d2, d3, ..., dn, where w is the width of the box, n is the number of disks, and
the remaining numbers are the diameters of the disks, in the order in which they fall into the box. You can
assume that w < 100, that n < 10, and that each diameter is less than w.
Output
For each data set, output a single line containing the height of the pile of disks, rounded to two places
beyond the decimal point.
The example data matches the illustrations above.
Example input:
10 3 5 2 3
8255
11 3 10 2 4
93446
Example output:
5.00
9.00
12.99
9.58
Example input:
10 6 5 4 6 3 5 2
0
Example output:
14.19
5.
For this problem you will write a search engine that takes a query, searches a collection of words, and finds
the lexicographically smallest word that matches the query (i.e., the matching word that would appear first in
an English dictionary). A query is a sequence of one or more terms separated by single vertical bars ("|"). A
term is one or more letters followed by zero or more signed letters. A signed letter is either +s ("positive" s)
or -s ("negative" s), where s is a single letter. All letters are lowercase, and no letter will appear more than
once within a term. A query will not contain spaces. A term matches a word if the word contains at least one
of the unsigned letters, all of the positive letters, and none of the negative letters; a query matches a word if
at least one of its terms matches the word.
Input
The input consists of one or more test cases followed by a line containing only "#" that signals the end of the
input. Each test case consists of 1100 words, each on a line by itself, followed by a line containing only "*"
that marks the end of the word list, followed by one or more queries, each on a line by itself, followed by a
line containing only "**" that marks the end of the test case. Each word will consist of 120 lowercase letters.
All words within a test case will be unique. Each query will be as defined above and will be 179 characters
long.
Output
For each query, output a single line containing the lexicographically smallest word within that test case that
matches the query, or the word NONE if there is no matching word. At the end of each test case, output a
dollar sign on a line by itself.
Example input:
Example output:
Elk
cow
bat
*
ea
acm+e
nm+o|jk+l
**
debian
slackware
gentoo
ubuntu
suse
fedora
mepis
*
yts
cab-e+n
r-e|zjq|i+t|vs-p+e-u-c
**
#
bat
NONE
elk
$
gentoo
ubuntu
NONE
$
6.
Problem: Go Go Gorelians
The Gorelians travel through space using warp links. Travel through a warp link is instantaneous, but for
safety reasons, an individual can only warp once every 10 hours. Also, the cost of creating a warp link
increases directly with the linear distance between the link endpoints.
The Gorelians, being the dominant force in the known universe, are often bored, so they frequently conquer
new regions of space in the following manner.
1) The initial invasion force finds a suitable planet and conquers it, establishing a Regional Gorelian Galactic
Government, hereafter referred to as the RGGG, that will govern all Gorelian matters in this region of space.
2) When the next planet is conquered, a single warp link is constructed between the new planet and the
RGGG planet. Planets connected via warp links in this manner are said to be part of the Regional Gorelian
Planetary Network, that is, the RGPN.
3) As additional planets are conquered, each new planet is connected with a single warp link to the nearest
planet already in the RGPN, thus keeping the cost of connecting new planets to the network to a minimum. If
two or more planets are equidistant from the new planet, the new planet is connected to whichever of them
was conquered first.
This causes a problem however. Since planets are conquered in a more-or-less random fashion, after a
while, the RGGG will probably not be in an ideal location. Some Gorelians needing to consult with the RGGG
might only have to make one or two warps, but others might require dozens---very inconvenient when one
considers the 10-hour waiting period between warps.
So, once each Gorelian year, the RGGG analyzes the RGPN and relocates itself to an optimal location. The
optimal location is defined as a planet that minimizes the maximum number of warps required to reach the
RGGG from any planet in the RGPN. As it turns out, there is always exactly one or two such planets. When
there are two, they are always directly adjacent via a warp link, and the RGGG divides itself evenly between
the two planets.
Your job is to write a program that finds the optimal planets for the RGGG. For the purposes of this problem,
the region of space conquered by the Gorelians is defined as a cube that ranges from (0,0,0) to
(1000,1000,1000).
Input
The input consists of a set of scenarios where the Gorelians conquer a region of space. Each scenario is
independent. The first line of the scenario is an integer N that specifies the total number of planets
conquered by the Gorelians. The next N lines of the input specify, in the order conquered, the IDs and
coordinates of the conquered planets to be added to the RGPN, in the format ID X Y Z. An ID is an integer
from 1 to 1000. X, Y, and Z are integers from 0 to 1000. A single space separates the numbers. A value of N
= 0 marks the end of the input.
Output
For each input scenario, output the IDs of the optimal planet or planets where the RGGG should relocate.
For a single planet, simply output the planet ID. For two planets, output the planet IDs, smallest ID first,
separated by a single space.
Example Input:
Example Output:
5
1000
2001
3002
4003
5004
5
1000
2110
3320
4210
3
24
31 97
Example Input:
Example Output:
5300
10
21 71 76 4
97 32 5 69
70 33 19 35
3 79 81 8
31 91 17 67
52 31 48 75
48 90 14 4
41 73 2 21
83 74 41 69
26 32 30 24
0
7.
Problem: Dice
The people of AC Mamia have a tradition of rolling a six sided die to determine who will choose where to dine
that evening.
One person rolls the die, the other calls odd or even. If the caller guesses correctly, then he or she gets
to choose the restaurant; otherwise, the person throwing does. Hopefully, it is obvious that odd wins
when 1, 3 or 5 is rolled, and even with 2, 4 or 6! ACMamians also have a tradition of repeating the same
call (either odd or even) several times in succession. Your task is to check the recorded rolls and
determine how many times each person wins.
Input
Input for this problem consists of a sequence of one or more scenarios. Each scenario contains 3 lines.
The first line contains, in order, the names of two people, and one of the words odd or even
(in lowercase), separated by a space. The first named person will always throw, and the second
named person will always call either odd or even, as indicated. In AC Mamia, a name is a nonempty sequence of up to 20 (inclusive) letters (any of which may be uppercase or lowercase).
The second line will be an integer, N, 1 N 255, representing the number of die throws.
The third line contains N integers, each between 1 and 6 (inclusive), separated by single spaces,
representing die throws.
The input will be terminated by a line consisting of three hash signs (#), separated by single spaces. This
line should not be processed.
Output
Output will be a sequence of lines, one for each input scenario. Each line will contain in order the following
items, separated by single spaces: the name of the first person (exactly as it appears in the input), the
number of times the first person won, the name of the second person (exactly as it appears in the input),
and the number of times the second person won.
SAMPLE INPUT:
Bill Susan even
8
16534255
Sarah Tony odd
15
245436125431256
###
SAMPLE OUTPUT:
Bill 5 Susan 3
Sarah 8 Tony 7
8.
Problem: CD Titles
I found my hard disk quickly filling up with snapshots and videos. I decided to offload a lot of the files to CD.
Each CD is in its own plastic case, and the contents are clearly described on the front of the case. As the
number of CDs increased, I built myself a shelf on which the CDs stand vertically. I need your help! I have
written a title for each CD into a text file, but I need the titles to appear vertically so that I can put them in
the spine of the CD cases and be able to read them easily from the shelf. I want you to write a program that
will output my titles vertically. I need lines between each title so that, when I print them, I can easily cut
along the lines.
I have worked out that I can fit 36 characters into the available space, so all output titles must be 36
characters long, padded with spaces at the end where necessary. If I accidentally make a title too long,
only output the first 36 characters.
Input
Input will be at most 50 titles, one to a line. Each title consists of 1 to 100 arbitrary characters. A single #
on a line by itself indicates the end of input.
Output
Output will be the same titles presented vertically, where the left to right order will be the same as the order
of the input. There will be a column of bar (|) characters at each end, and separating each title, and a row
of minus (-) characters (1 per column) at the beginning and end.
SAMPLE INPUT:
012345678901234567890123456789012345
David and Janes wedding, March 2002, Alexandria
Bahamas Holiday August 2001
#
SAMPLE
OUTPUT:
------|0|D|B|
|1|a|a|
|2|v|h|
|3|i|a|
|4|d|m|
|5| |a|
|6|a|s|
|7|n| |
|8|d|H|
|9| |o|
|0|J|l|
|1|a|i|
|2|n|d|
|3|e|a|
|4||y|
|5|s| |
|6| |A|
|7|w|u|
|8|e|g|
|9|d|u|
|0|d|s|
|1|i|t|
|2|n| |
|3|g|2|
|4|,|0|
|5| |0|
|6|M|1|
|7|a| |
|8|r| |
|9|c| |
|0|h| |
|1| | |
1
|2|2| |
|3|0| |
|4|0| |
|5|2| |
-------
9.
The government of Acmonia has decided that henceforth all house numbers should be given in binary
instead of decimal notation. Householders will now have to purchase 0 and 1 binary digits to display on their
houses. For reasons much too complicated to discuss here it seems that the cost to a householder of a 0
binary digit and of a 1 binary digit may well differ. Your task is to write a program which will report to
householders the cost of their new numbers.
Input
The input text consists of a number of sets of problems. The first line of a set is of the form COST a b. For
that set:
10. a and b are both integers, 0 a, b 1000,
11. a 0 binary digit costs a dollars,
12. a 1 binary digit costs b dollars.
The first line is followed by one or more lines each consisting of a single integer n.
1 0 n 2 000 000,
2 n indicates a house number, expressed as a standard decimal number.
A single # on a line indicates the end of input.
Output
Each set of output data must begin with a single output line showing consisting of the word Set, followed
by a space ( ), and the current set number (counted from 1). This is followed by the cost of the binary
digits for each house number, each cost being displayed as a decimal number on a separate line.
SAMPLE INPUT:
COST 1 1
1
34
15
COST 1 10
1
34
15
COST 10 1
1
34
15
COST 0 5
1
16
#
SAMPLE OUTPUT:
Set 1
1
6
4
Set 2
10
24
40
Set 3
1
42
4
Set 4
5
5
SAMPLE OUTPUT:
e:5 i:5 a:3 o:2 u:1.
a:2 o:2 e:1 i:1 u:0.
Sample Output
450
2100
Once students grow up and enter intermediate-level schools, we can give them the opposite. Give them an
N N table, and let them decide how to add labels for it to be a valid addition table (if it is indeed an addition
table.) Given an N N table, which does not include any labels, your job is to decide whether it is possible
to properly label it or not. Were not interested in the labels themselves, just decide if it is an addition table
or not. For example, the 2 2 table on the left is not an addition table, while the one on the right is not an
addition table, while the one on the right is.
Input
Your program will be tested on one or more test cases. The first line in the input is an integer D representing
the number of cases. The first line of each test case is an integer N, where N 10, representing the size of
the table. Following that, there will be N lines, each with N integers representing the N N table in a rowmajor format. Each number in the table is between -10, 000 and 10, 000 (inclusive).
Output
For each test case, output the result on a single line using the following format: k._result Where k is the
test case number (starting at 1,) and result is "YES" if the test case is an addition table, or "NO" if its not.
Sample Input
add.in
3
3
4 -1 6
729
1 -4 3
2
14
35
2
36
25
Sample Output
1. YES
2. NO
3. YES
16.Problem:
Tag Checker
Markup languages such as HTML use tags to highlight sections with special significance. In this way, a
sentence in boldface can be indicated thus:
<B>This is a sentence in boldface</B>
Typically every tag has an opening tag of the form <TAG> and a closing tag of the form </TAG>, so that
portions of text can be bracketed as above. Tags can then be combined to achieve more than one effect on
a particular piece of text simply by nesting them properly, for instance: <CENTER><B>This text is centred
and in boldface</B></CENTER>
Two of the most common mistakes when tagging text are:
1. getting the nesting wrong: <B><CENTER>This should be centred boldface, but the tags are
wrongly nested</B></CENTER>
2. forgetting a tag: <B><CENTER>This should be centred boldface, but there is a missing
tag</CENTER>
Write a program to check that all the tags in a given piece of text (a paragraph) are correctly nested, and
that there are no missing or extra tags. An opening tag for this problem is enclosed by angle brackets, and
contains exactly one upper case letter, for example <T>, <X>, <S>. The corresponding closing tag will be
the same letter preceded by the symbol /; for the examples above these would be </T>, </X>, </S>.
Input and Output
The input will consist of any number of paragraphs. Each paragraph will consist of a sequence of tagged
sentences, over as many lines as necessary, and terminating with a # which will not occur elsewhere in
the text. The input will never break a tag between two lines and no line will be longer than 80 characters. The
input will be terminated by an empty paragraph, i.e. a line containing only a single #.
If the paragraph is correctly tagged then output the line Correctly tagged paragraph, otherwise output a
line of the form Expected <expected> found <unexpected> where <expected> is the closing tag matching
the most recent unmatched tag and <unexpected> is the closing tag encountered. If either of these is the
end of paragraph, i.e. there is either an unmatched opening tag or no matching closing tag at the end of the
paragraph, then replace the tag or closing tag with #. These points are illustrated in the examples below
which should be followed exactly as far as spacing is concerned.
Sample Input
The following text<C><B>is centred and in boldface</B></C>#
<B>This <\g>is <B>boldface</B> in <<*> a</B> <\6>
<<d>sentence#
<B><C> This should be centred and in boldface, but the tags
are wrongly nested </B></C>#
<B>This should be in boldface, but there is an extra closing
tag</B></C>#
<B><C>This should be centred and in boldface, but there is a
missing closing tag</C>#
#
Sample Output
Correctly tagged paragraph
Correctly tagged paragraph
Expected </C> found </B>
Expected # found </C>
Expected </B> found #
SAMPLE OUTPUT:
10
11
34
Impossible!
234567900
18.Problem: Heliport
In these fast-paced times, companies are investing in heliports to reduce travel time for their busy
executives. The heliports are typically circular landing pads, constructed on the roofs of the companies
headquarters.
You must write a program that finds the largest radius for a circular heliport that can be constructed on the
flat roof of a building that is in the form of a simple polygon. Since this is merely the design phase of the
construction effort, your program must find only the radius of the heliport. The maximum radius for a heliport
in the diagram shown is 10.
Input
The input file contains several test cases. Each test case consists of two lines. The first line consists of an
even integer n (4 n 20), which is the number of the sides of the building. The second line consists of n
pairs of the form (m, d), where m is an integer (1 m 50) and d is a letter (U, R, D, L). Assuming the roof is
drawn on the Cartesian plane, m is the length of a roof boundary segment and d is the direction of that
segment as you travel counterclockwise around the roof. U, R, D, and L mean Up, Right, Down, and
Left respectively. The boundary segments of the roof, which are parallel to the x and y axes, are given in
counterclockwise order. The starting position is the origin (0, 0).
Input for the last test case is followed by a line consisting of the number 0.
Output
For each test case, the output consists of a separate line containing the case number (starting with 1) and a
real number (rounded to two digits after the decimal point) representing the radius of the heliport. Print a
blank line between cases as shown in the sample output.
Sample Input
4
2R2U2L2D
10
10 R 10 U 10 L 10 U 10 R 5 U 30 L 20 D 20 R 5 D
0
Sample Output
Case Number 1 radius is: 1.00
Case Number 2 radius is: 10.00
19.Problem: Q
You've got a queue. And you just got to mess with it.
Given a queue of items and a series of queue operations, return the resulting queue.
Queue operations are defined as follows:
starting-position to requested-position
meaning one wants the item at the starting position to be moved to the requested position. So if the queue
of items were:
Item1 Item2 Item3 Item4 Item5
(Item1 being in position 1, Item2 in position 2, etc.)
after applying the queue operation:
5 to 2 the resulting queue would be:
Item1 Item5 Item2 Item3 Item4
as Item5 (the item in position 5) was moved to position 2. Multiple queue operations are applied at the same
time, however; e.g., given the queue of items:
Item1 Item2 Item3 Item4 Item5 Item6 Item7 Item8
If the following queue operations were applied:
2 to 6; 6 to 3; 4 to 5; 5 to 2; 7 to 4; 8 to 1 then the resulting queue would be:
Item8 Item5 Item6 Item7 Item4 Item2 Item1 Item3
As you can see, the queue operations are strictly enforced, with other items (not involved in queue
operations) maintaining their order and moving to vacant positions in the queue. Note that no two queue
operations will have the same starting-position or same requested-position defined.
Input
Input to this problem will begin with a line containing a single integer x indicating the number of datasets.
Each data set consists of three components:
1Start line A single line, "m n" (1 <= m, n <= 20) where m indicates the number of items in the queue and n
indicates the number of queue operations.
2Queue items A line of short (between 1 and 8 characters) alphanumeric names for the items in the queue.
Names are unique for a given data set and contain no whitespace.
3Queue operations n lines of queue operations in the format "starting-position requested position".
Output
For each dataset, output the queue after the queue operations have been applied. Print the elements of the
queue on a single line, starting from the first and ending with the last, with a single space separating each
item.
Sample Input
Sample Output
35
1
alpha beta gamma delta epsilon
52
86
abcdefgh
26
63
45
52
74
81
32
foo bar baz
31
13
Your job is to automate Mr. Ramanujans brain to see all possible such patterns, given any n (Maximum
value of n is 16). Captain has jersey #1 and hence obviously the point of beginning. Print all possible
formations in ascending numeric ordering e.g. 1 2 5 comes before 1 2 6. Every formation must begin with
captains jersey number. Give priority to clockwise formations i.e. print patterns in clockwise direction and
then all patterns of anticlockwise direction. There are no missing numbers on the jerseys. E.g. if the number
of players is 6, the jerseys are numbered 1, 26.
Input
The first line of the input represents the number of test cases k (at most 5).
The next k lines represent the number of players n (0 < n <= 16).
Output
The output format is shown as sample below. Each row represents a possible formation satisfying the above
adjacency constraint. For each test case, the first line should be the test case number followed by the
arranged patterns, one pattern per row. There should be an empty line separating each test case.
Example Input:
2
6
8
Example Output:
1
143256
165234
2
12385674
12583476
14765832
16743852
Sample Input
Sample Output
7 PlayerM S
15 PlayerP G
1 PlayerD D
3 PlayerU D
6 PlayerI D
10 PlayerC D
2 PlayerB M
4 PlayerV M
8 PlayerF M
9 PlayerA M
5 PlayerR S
4-4-2
0
Sample Output
100
0
4
Sample Output
3
00:59:58 01:01:24
22:47:03 01:03:24
00:00:09 00:03:37
29
2727
70
24.Problem: Rounders
For a given number, if greater than ten, round it to the nearest ten, then (if that result is greater than 100)
take the result and round it to the nearest hundred, then (if that result is greater than 1000) take that number
and round it to the nearest thousand, and so on ...
Input
Input to this problem will begin with a line containing a single integer n indicating the number of integers to
round. The next n lines each contain a single integer x (0 <= x <= 99999999).
Output
For each integer in the input, display the rounded integer on its own line.
Note: Round up on fives.
Sample Input:
Sample Output
91
5
14
459
9
12345678
44444445
1445
446
20
10
451
00
10000000
50000000
2000
500
25.Problem: Caterpillar
An undirected graph is called a caterpillar if it is connected, has no cycles, and there is a path in the
graph where every node is either on this path or a neighbor of a node on the path. This path is called
the spine of the caterpillar and the spine may not be unique. You are simply going to check graphs to
see if they are caterpillars.
For example, the left graph below is not a caterpillar, but the right graph is. One possible spine is
shown by dots.
Input
There will be multiple test cases. Each test case starts with a line containing n indicating the number of
nodes, numbered 1 through n (a value of n = 0 indicates end-of-input). The next line will contain an integer e
indicating the number of edges. Starting on the following line will be e pairs n1 n2 indicating an undirected
edge between nodes n1 and n2. This information may span multiple lines. You may assume that n <= 100
and e <= 300. Do not assume that the graphs in the test cases are connected or acyclic.
Output
For each test case generate one line of output. This line should either be
Graph g is a caterpillar.
or
Graph g is not a caterpillar.
as appropriate, where g is the number of the graph, starting at 1.
Sample Input
Sample Output
22
21
1 2 2 3 2 4 2 5 2 6 6 7 6 10 10 8 9 10 10 12 11 12 12
13 12 17
18 17 15 17 15 14 16 15 17 20 20 21 20 22 20 19
16
15
1 2 2 3 5 2 4 2 2 6 6 7 6 8 6 9 9 10 10 12 10 11 10 14
10 13 13 16 13 15
0
Sample Output
3
0 1 10 10
1012
10 1 0 10
10 2 10 0
0
Sample Output
33
MAHERSHALALHASHBAZ
AL
BILL
63
MAHERSHALALHASHBAZ
AL
NEBUCHADNEZZAR
BILL
BILLYBOBBENJAMIN
JILL
00
Case 1: no
Case 2: yes
Sample Output
ABCD 4
AEEE 3
IBM 0
3 20 4
ABE 1 0
ROM 1 0
INK 1 0
MOB 0 2
Ben Fitt is one of several workers in the shipping department (part of the Knick Knack Plaque Shack
Pack, as they like to call themselves). Each day he is assigned the task of shipping all the plaques of
a certain width to the various department stores which sell them. He has at his disposal boxes with a
depth of 1 and a width equal to the plaques width. As the plaques come off the assembly line, he fits
them into the boxes one at a time. When placed in a box, each plaque will slide down until some part
of it touches the topmost plaque already in the box (or the bottom of the box if it is the first plaque).
For example, if the leftmost plaque above came off the assembly line first, followed by the middle and
then the rightmost, they would stack up one on top of the other as shown on the left. If they came off
the assembly line in reverse order, they would stack up as shown on the right.
When a plaque comes off the assembly line which will not fit into the box (i.e., it sticks up over the top), Ben
closes that box, ships it off, and starts a new box. In the above examples, the height of the boxes is only 12,
so it would take two boxes for the first ordering of plaques, but only one for the second.
During his free moments between packing plaques, Ben wonders what it would be like if hundreds of
computer programmers tried to write code to simulate this monotonous drudgery.
Input
Input will consist of multiple test cases. Each test case will start with a line containing three integers n w b,
where n indicates the number of plaques to ship, w indicates the width of each plaque, and b indicates the
height of each shipping box. These values will lie in the ranges 1 . . . 100, 1 . . . 10 and 1 . . . 100,
respectively. Following this line will be n specifications of plaque shapes. Each shape specification starts with
a single line containing the integer height h of the plaque (1 <= h <= 10 and h <= b). Following this will be h
lines containing w characters each, where each character is either X (indicating a part of the plaque ) or .,
indicating empty space. The order in which the plaques appear in the input is the order in which they must be
packed in the boxes, and rotating or inverting the plaques is not allowed. The input file will end with the line 0
0 0.
Output
For each test case, output a single line containing the maximum height of the plaques in each box, in the
order in which they are filled.
Sample Input
Sample Output
3 5 12
5
XXXXX
.XXXX
..XXX
96
10
...XX
....X
4
XXX..
..X..
..XXX
..X..
6
X....
X....
X....
X....
X....
XXXXX
3 5 12
6
X....
X....
X....
X....
X....
XXXXX
4
XXX..
..X..
..XXX
..X..
5
XXXXX
.XXXX
..XXX
...XX
....X
000
30.Problem: Roofing It
Bill Eaves owns the Shingle Minded roofing company which is a sub-contracting firm specializing in putting
roofs on buildings. Often, Bill will receive a design for a roof from some young hot-shot architect which,
though it may have some aesthetic appeal, is totally impractical. In these cases, Bill will begin negotiations
with the architect and the client to find a simpler design. Bills only concern is that the roof be convex, to
allow rain, snow and frisbees to roll off easily. The architects main concern is that the maximum height
between his original roof and the compromise roof be as small as possible.
The clients main concern is to get out of this meeting as soon as possible and get back to watching TV.
The architects plans for the roof come in the form of a series of n points (xi, yi) specifying the outline of the
roof as seen from the side of the house. The roofs are always symmetrical, so the architect only shows the
front side of the roof (from its start at the front of the house to its peak). Once Bill gets these plans and a
decision is made on how many sections the convex roof should have, he must decide how to place the
sections so as to 1) make sure that all the original (xi, yi) points lie on or below the new roof, and 2) to
minimize the maximum vertical distance between any of the original (xi, yi) points and the new roof. All
sections must lie on at least two of the initial points specified by the architect.
An example is shown below. On the left are the initial points from the architect. The next two pictures show
an approximation of the roof using only two sections. While both of these are convex, the second of the two
is the one which minimizes the maximum distance.
Input
Input will consist of multiple test cases. Each case will begin with two positive integers n and k
(2 <= n <= 100, 1 <= k < n) indicating the number of points used in the original roof plan and the number of
sections used in the compromise roof. These will be followed by n lines each containing two floating points
numbers xi yi, specifying the n points in the roof plan. These values will be given in increasing order of x, and
the last point will be guaranteed to have the highest y value of any of the points. All values will be between
0.0 and 10000.0. The last case is followed by a line containing 0 0 which indicates end-of-input and should
not be processed.
Output
For each test case, output the maximum distance between the best compromise roof and the initial points,
rounded to the nearest thousandth.
Sample Input
62
0.0 0.0
1.0 3.0
3.0 6.0
6.0 9.0
8.0 10.0
17.0 12.0
00
Sample Output
1.500
For this problem, you will be given grids and must count the number of maximal snakes in each.
Input
Input will consist of multiple test cases. The first line of each test case will contain two positive integers n m
indicating the number of rows and columns in the grid (the maximum value of each will be 200). The next n
lines will consist of m characters (either 0 or 1) specifying the grid. The last case is followed by a line
containing 0 0 which indicates end-of-input and should not be processed.
Output
For each test case, output a single line containing the number of maximal snakes in the grid.
Sample Input
7 10
1111111110
0000000010
1100000011
1011110001
1010010001
1010010111
1110011100
7 10
1111111110
0000000010
0001010011
1011010001
1010010001
1010010111
1110011100
7 10
1011111110
0100000010
1101011011
1011010001
1010010001
1010010111
1110011100
Sample Output
1
0
3
00
In order to test how good this game is, the gang at Gazillion has hired you to write a program which can play
the game. Specifically, given any starting configuration, they would like a program to determine the best
move for the current player, i.e., the score which maximizes the points awarded to that player (or minimizes
those awarded to the players opponent).
Input
Input will consist of multiple test cases. Each test case will start with a line containing a positive integer n (<=
8) indicating the size of the board. Next will come n lines describing the current board layout (row 0 first,
followed by row 1, etc). Each of these lines will contain n characters taken from 0, 1 and ., where .
represents an empty square. The first character will be in column 0, the second in column 1, etc. The number
of 0s on the board will either be equal to the number of 1s or one greater, and there will be between 1 and
10 (inclusive) empty squares. The last case is followed by a line containing 0 which indicates end-of-input
and should not be processed.
Output
For each test case, output a single line containing two items: the coordinates of the best move for the player
and the best point total achieved by that player. In case of ties, print the move which comes first
lexicographically. Use the format shown in the sample output.
Sample Input
4
01.1
00..
.01.
...1
4
0.01
0.01
1..0
.1..
Sample Output
(1,2) 2
(2,2) -1
Sample Output
1
1234
Your task is to determine the minimum amount of energy that Mr. Frog needs to spend to get from his home
to Ms. Toads home.
Input
The input contains several test cases. The first line of a test case contains two integers, C and R, indicating
respectively the number of columns and rows of the marsh (1 <= C,R <= 1000). The second line of a test
case contains four integers Cf , Rf , Ct, and Rt, where (Cf ,Rf ) specify Mr. Frogs home location and (Ct,Rt)
specify Ms. Toads home location (1 <= Cf ,Ct <= C and 1 <= Rf ,Rt <= R). The third line of a test case
contains an integer W (0 <= W <= 1000) indicating the number of watery places in the marsh. Each of the
next W lines contains four integers C1, R1, C2, and R2 (1 <= C1 <= C2 <= C and 1 <= R1 <= R2 <= R)
describing a rectangular watery place comprising cells whose coordinates (x, y) are so that C1 <= x <= C2
and R1 <= y <= R2. The end of input is indicated by C = R = 0.
The input must be read from standard input.
Output
For each test case in the input, your program must produce one line of output, containing the minimum
calories consumed by Mr. Frog to go from his home location to Ms. Toads home location. If there is no way
Mr. Frog can get to Ms. Toads home, your program should output impossible.
The output must be written to standard output.
Sample input
44
1142
2
2133
4344
44
1142
1
2134
76
4276
5
4171
Sample Output
14
impossible
12
5155
2434
7575
6666
00
35.Problem: Jukebox
The ICPC judges are preparing a party for the opening ceremony. For the party, they intend to add a playlist
with some songs to the jukebox software (a simple MP3 player). However, there are so many songs in the
computer that it is difficult to find the ones they want to add.
As a consequence, they need to use the search feature many times.
In this jukebox, when you search for a string s, the software returns every music whose title or artist name
contains s as a substring. String s is a substring of string t if t contains all characters of s as a contiguous
sequence (for example, bc is a substring of abcd, but ac is not). To save their precious time, while looking
for a song, they always use one of the songs golden string, i.e. one of the shortest strings for which the
search returns as a result only the song they want.
In the example above, a possible golden string for the song johnnatan is ta. Note that ta is not a substring
of the name of another song nor a substring of the artist of another song. Note also that there is no string of
size equal to 1 that could identify uniquely the song johnnatan.
They discovered that if they remove the artist fields from some of the songs they can get even smaller
golden strings. For the song john, there is no golden string. However, if one removes the artist field from all
other songs, the string c becomes the golden string for the song john.
Given the song list (each song with name and artist), your job is to determine the minimum sum of the golden
string sizes for all songs that can be obtained if one is allowed to remove some of the artist fields. In the
figure above you can see a possible best result with the golden strings in bold. The minimum sum of the
golden string sizes in this case is 10.
Input
The input contains several test cases. The first line of each test case contains one integer N (1 <= N <= 30),
which indicates the number of songs. Following there will be N pairs of lines (2 <= N lines), one pair for each
song. The first line of a pair will contain the song name, the second line will contain the artist name. Both
artist and song names are strings containing only lower case letters or underlines and having at least 1 and
at most 30 characters. There will be at most 6 different artists in the list. The end of the input is given by N =
0.
The input must be read from standard input.
Output
For each test case your program must output one single line with the minimum sum of the golden string
sizes. You may assume that there will always be a solution.
The output must be written to standard output.
Sample input
8
a_flor
los_hermanos
anna_julia
los_hermanos
quem_sabe
los_hermanos
pierrot
los_hermanos
azedume
los_hermanos
johnny
massacration
johnnatan
massacration
john
massacration
4
c
axc
b
axc
d
cc
xc
cc
0
Sample Output
10
5
Any region can be further subdivided. For example, the region named ms can be further divided into subregions msp, msq, msr and mss, as illustrated below.
As another example, the figure below shows the result of subdividing the child sub-regions of the region
named msr.
Sub-regions with names of the same length have the same zoom level, since they represent regions of the
same size. Sub-regions in the same zoom level that share a common side are said to be neighbors.
Anything that lies outside the base region m is not mapped and, for every zoom level, all sub-regions of m
are mapped.
Bubbles map technology provides a way for the user to navigate from a given sub-region to neighboring
sub-regions in the directions up, down, left and right. You mission is to help Bubble Inc. in finding the
neighboring sub-regions of a given sub-region. That is, given the name of a rectangular sub-region, you must
determine the names of its four neighboring sub-regions.
Input
The input contains several test cases. The first line contains one integer N indicating the number of test
cases. Each of the following N lines represents a test case, containing the name of a region composed by C
characters (2 <= C <= 5000), the first always being the letter m and the following being either p, q, r or
s.
The input must be read from standard input.
Output
For each test case in the input your program must produce one line of output, containing the names of the
four neighboring regions of the given region in the order of direction up, down, left, right. For the neighbors
that are not mapped you should output <none> instead of its name. Leave one blank space between two
consecutive names.
The output must be written to standard output.
Sample input
Sample Output
2
mrspr
mps
Dr. Kabal has hired a lot of research assistants to collect and analyse onions for him. Since he does not want
to share his discovery with the world yet, he didnt tell the assistants to look for onions with an odd number of
layers. Instead, each assistant was given the task of collecting onions, and selecting points from each of the
layers outer borders, so that an approximation of the layer structure of the onion can be reconstructed later.
Dr. Kabal told the assistants that the next step will be a complicated analysis of these points. In fact, all he
will do is simply to use the points to count the number of layers in each of the onions, and select the ones
with an odd number of layers.
It is clear that the approximation obtained by Dr. Kabal, from the points collected, might have a different
shape than the original onion. For instance, only some of the points of the onion shown in Figure 1 would be
extracted in the process, giving rise to a set of points as shown in Figure 2. With these points Dr. Kabal will
try to approximate the original layers of the onion, obtaining something like what is shown in Figure 3. The
approximation procedure followed by Dr. Kabal (whose result is shown in Figure 3) is simply to recursively
find nested convex polygons such that at the end every point belongs to precisely one of the polygons. The
assistants have been told to select points in such a way that the number of layers in the approximation, if
done in this recursive manner, will be the same as in the original onion, so that is fine with Dr. Kabal. The
assistants are also aware that they need at least three points to approximate a layer, even the innermost
one.
Your task is to write a program that, given a set of points collected by an assistant (as shown in Figure 2),
determines if the respective onion should be taken to the laboratory.
Input
The input contains several test cases. Each test case consists of an integer 3 <= N <= 2000 in a single line,
indicating the number of points collected by the assistants. Following, there are N lines, each containing two
integers 2000 <= X, Y <= 2000 corresponding to the coordinates of each point. The input is finished by a
problem with N = 0 points, which should not be processed.
The input must be read from standard input.
Output
There should be one line of output for each test case in the input. For each test case print the
String Take this onion to the lab! if the onion should be taken to the laboratory or Do not take this onion to
the lab! if the onion should not be taken to the laboratory.
The output must be written to standard output.
Sample input
7
00
08
16
31
66
80
88
11
26
32
66
00
0 11
11
19
71
79
8 10
80
0
Sample Output
Do not take this onion to the lab!
Take this onion to the lab!
Sample Output
0
3
Sample Output
1
2
0
0 10 33
10 0 33
00
40.Problem:
Report Recovery
At the end of the week, John asked Mary to send him an urgent sales report. Mary was in a hurry because
she was leaving for her holiday. She then copy-pasted the sales sheet on an email, sent it to John and went
out. She did not want to be annoyed with work issues, so she left without telling anyone where she would be.
She announced that she would be simply not available for the next two weeks, turned off her cell phone, and
left.
When John received the message he realized that the report had no spaces at all! He knew that the report
should have a header line with product codes of the form P1, P2, . . ., PN and the word Totals at the end.
Then there would be several lines reporting product sales for the different sellers of Marys office. Each seller
was identified with a name composed by one word (only alphabetical characters). The line corresponding to
a seller should begin with his/her name, followed by the number of sold products, according to the columns
report. The last line of the report should begin with the two letters TP followed by the totals of each column in
the report (of course, no sellers name began with the letters TP). John knew that there were no negative
numbers in the report, a zero quantity was reported with a single 0, and there were no leading zeros when
reporting a positive quantity.
At this point, John decided to reconstruct Marys report. He knew that there could be more than one possible
result, but he wanted to do it anyway with the first consistent solution that he could find (maybe he could fix
any mistakes when Mary comes back).
Could you help John with the recovering of Marys sales report?
Input
The input consists of several test cases. The first line in the input contains an integer C specifying the
number of test cases. The first line of a report is a header line, containing the product codes P1, P2, . . . PN
and the word Totals, as described above. The numbering of products in this header line is consecutive, from
1 to N, with 1 <= N <= 5. Then there are a number of lines, each representing a row of the report, as
described above. The last line of the report starts with the letters TP and have the format described above.
Consider that each seller sold less than 1000 units of each product. There are no more than 4 sellers on
each test case.
Each seller name will not exceed 10 characters (only uppercase and lowercase letters).
The input must be read from standard input.
Output
For each test case in the input your program must produce one possible Marys report. Each line of the
answer must be left aligned, with its items separated by a single space, and with no space at its end.
The output must be written to standard output.
Sample input
2
P1P2P3Totals
Amanda121100131
Charles5141772
Monique14121238
TP1862629241
P1P2Totals
Ingrid9519851936
Candid49212504
Peter10313
Camila000
TP145310002453
Sample Output
P1 P2 P3 Totals
Amanda 121 10 0 131
Charles 51 4 17 72
Monique 14 12 12 38
TP 186 26 29 241
P1 P2 Totals
Ingrid 951 985 1936
Candid 492 12 504
Peter 10 3 13
Camila 0 0 0
TP 1453 1000 2453
Balls end up lodged in the same relative positions that they were thrown in the roulette. That is, if balls a, b
and c are thrown in that sequence, they end up lodged such that, in clockwise direction, a is followed by b
which is followed by c which is followed by a. The value of a ball in a turn is calculated by multiplying the
balls number by the sum of the numbers of the two adjacent slots over which the ball is lodged. If a balls
value is positive, the player who bet on that ball receives that amount (the balls value) from the dealer; if a
balls value is negative, the player who bet on that ball must pay that amount to the dealer. The profit of the
dealer in a turn is the total amount received minus the total amount paid.
For example, in the figure above, the dealer pays $5.00 for ball numbered 1, pays $7.00 for ball numbered
7, receives $24.00 for ball numbered 12 and does not pay nor receive anything for ball numbered 3.
Therefore, in this turn the dealer makes a profit of $12.00 (24 5 7); note that the dealers profit in a turn
may be negative (loss).
You will be given the description of the roulette, the description of the balls and the sequence in which the
balls are thrown into the roulette. Write a program to determine the maximum profit that the dealer can make
in one turn.
Input
Input contains several test cases. The first line of a test case contains two integers S and B which indicate
respectively the number of slots in the roulette (3 <= S <= 250) and the number of balls used (1 <= B <=
S/2 ). The second line of a test case contains S integers Xi, indicating the numbers associated to the
roulettes slots, in clockwise direction (64 <= Xi <= 64, for 1 <= i <= S). The third line of a test case contains
B integers Yi, indicating the numbers associated to the balls (64 <= Yi <= 64, for 1 <= i <= B), in the
sequence the balls are thrown into the roulette (notice it is in this order that they end lodged in the roulette, in
clockwise direction). The end of input is indicated by S = B = 0.
The input must be read from standard input.
Output
For each test case in the input your program must write one line of output, containing an integer indicating
the maximum profit the dealer can make in one turn.
The output must be written to standard output.
Sample input
42
-1 0 2 -1
Sample Output
4
-11
-1 1
52
3 2 -1 7 1
23
73
-4 3 2 1 0 -4 -2
-10 0 1
42
0230
-2 -2
00
56
10
Standard Output
7 PlayerM S
15 PlayerP G
1 PlayerD D
3 PlayerU D
6 PlayerI D
10 PlayerC D
2 PlayerB M
4 PlayerV M
8 PlayerF M
9 PlayerA M
5 PlayerR S
0
43. Problem: Barbara Bennett's Wild Numbers
A wild number is a string containing digits and question marks (like 36?1?8). A number X matches a wild
number W if they have the same length, and every non-question mark character in X is equal to the
character in the same position in W (it means that you can replace a question mark with any digit). For
example, 365198 matches the wild number 36?1?8, but 360199, 361028, or 36128 does not. Write a
program that reads a wild number W and a number X from input, both of length n, and determines the
number of n-digit numbers that match W and are greater than X.
Input
There are multiple test cases in the input. Each test case consists of two lines of the same length. The first
line contains a wild number W, and the second line contains an integer number X. The length of input lines is
between 1 and 10 characters. The last line of input contains a single character #.
Output
For each test case, write a single line containing the number of n-digit numbers matching W and greater than
X (n is the length of W and X).
Sample Input and Output
B.in
36?1?8
236428
8?3
910
?
5
#
Standard Output
100
0
4
Standard Output
21758
36432
Standard Output
4 Yes
1 No
Standard Output
6
move 2
turn right
move 3
turn left
turn left
move 1
At each instant of time Betty, stands on a square of the chessboard, facing one of the four directions (up,
down, left, right) when the board is viewed from the above. Performing a "move n" instruction, she moves n
squares forward in her current direction. If moving n squares goes outside the board, she stays at the last
square on the board and does not go out. There are three types of turns: turn right, turn left, and turn back,
which change the direction of Betty. Note that turning does not change the position of Betty.
If Betty faces a chess piece when moving, she pushes that piece, together with all other pieces behind (a
tough beetle she is!). This may cause some pieces fall of the edge of the chessboard, but she doesn't care!
For example, in the following figure, the left board shows the initial state and the right board shows the state
after performing the script in the above example. Upper-case and lower-case letters indicate the white and
black pieces respectively. The arrow shows the position of Betty along with her direction. Note that during the
first move, the black king (r) falls off the right edge of the board!
c
p
a
p
P
P
a
p
P
P
R
P
p
You are to write a program that reads the initial state of the board as well as the practice dance script, and
writes the final state of the board after the practice.
Input
There are multiple test cases in the input. Each test case has two parts: the initial state of the board and the
script. The board comes in eight lines of eight characters. The letters r, d, t, a, c, p indicate black pieces, R,
D, T, A, C, P indicate the white pieces and the period (dot) character indicates an empty square. The square
from which Betty starts dancing is specified by one of the four characters <, >, ^, and v which also indicates
her initial direction (left, right, up, and down respectively). Note that the input is not necessarily a valid chess
game status.
The script comes immediately after the board. It consists of several lines (between 0 and 1000). In each line,
there is one instruction in one of the following formats (n is a non-negative integer number):
move n
turn left
turn right
turn back
At the end of each test case, there is a line containing a single # character. The last line of the input contains
two dash characters.
Output
The output for each test case should show the state of the board in the same format as the input. Write an
empty line in the output after each board.
Sample Input and Output
F.in
.....c..
.p..A..t
D..>T.Pr
....aP.P
p.d.C...
.....p.R
........
........
move 2
turn right
move 3
turn left
turn left
move 1
#
--
Standard Output
.....c..
.p..A..t
D.....TP
....a..P
p.d.C^..
.......R
.....P..
.....p..
Standard Output
20
Standard Output
1
IMPOSSIBLE
*****
*$3**
*.2**
***#*
--
y
S1
b1
S2
b2 b3
b4
S3
The goal is to find which squares are visible, either entirely or partially, when viewed from above. In the
example above, the squares S1, S2, and S4 have this property. More formally, Si is visible from above if it
contains a point p, such that no square other than Si intersect the vertical half-line drawn from p upwards.
Input
The input consists of multiple test cases. The first line of each test case is n (1 n 50), the number of
squares. The second line contains n integers between 1 to 30, where the ith number is the length of the sides
of Si. The input is terminated by a line containing a zero number.
Output
For each test case, output a single line containing the index of the visible squares in the input sequence, in
ascending order, separated by blank characters.
Sample Input and Output
I.in
4
3514
3
212
0
Standard Output
124
13
Distance d1
Distance d2
Output
For each case, display the case number (they start with 1 and increase sequentially). Then, on each
of the next two lines, display the number of segments and the prime number lengths of track (in
ascending order) to be used in constructing the oval regions of the figure 8. Because of the track
shortage these primes must all be unique. As noted above, there may be more than one correct set
of prime-length track segments, but minimizing the number of segments is required.
Separate the output for consecutive cases with a blank line. Your output should appear similar to
that shown in the sample below.
Sample Input
301 501
210 435
00
Case 1
3 segments: 373, 991, 997
2 segments: 499, 919
Case 2
2 segments: 7, 983
3 segments: 61, 991, 997
Angle of
pans side
with
horizontal
surface,
Pans base, of
diameter d
Pans rim, of
width r
Two pieces of dough are required for each pie. One piece of dough is placed in the bottom of the
pan, up the inside, and out to the outside edge of the rim. The second piece of dough goes over the
top of the pie, from the outside of the rim up to a point in the center of the pie forming a perfect
cone. For clarity, note that the dough is two layers thick at the very outside edge of the rim.
Given values for , d, r, p, and h (as identified in the preceding figures), determine the volume of
dough required for each pie, in cubic inches, by first calculating the necessary surface areas and
then considering the dough to be 1/8 inches thick.
Input
The input wil contain multiple cases. For each case, the input will consist of a line containing real
numbers for , d, r, p, and h. Since these are real pies, will always be in the range 10 to 80
degrees, and the values for d, r, p, and h will be positive and less than or equal to 16 inches.
Input for the last case will be fol owed by a line containing a single 1.
Output
For each case, display the case number (they start with 1 and increase sequentially), and the total
volume of crust required, in cubic inches, with three fractional digits. Separate the output for
consecutive cases with a blank line. Your output should appear similar to that shown in the sample
below.
Sample Input
Each of the segments in a single display has an expected lifetime specified by the manufacturer.
This lifetime is the minimum cumulative time each segment is expected to be capable of being
illuminated, independent of how frequently it is turned on or off.
In normal use, a display doesnt always illuminate the same segments. That is, different digits are
displayed with different frequencies. As a result, some segments might be illuminated longer than
others, and thus the actual length of time the display can be expected to display the proper results
is dependent on the values it displays.
Given the values to be displayed, their probability of appearance, and the lifetime specified by the
manufacturer, you are to determine the minimum time the display can be expected to display the
proper values.
Multiple single-digit displays may be required, the actual number of such depending on the largest
value to be displayed. Values are displayed with leading zeroes, if necessary, to use all single-digit
displays. The displays are entirely blank (no segments illuminated) if no value is displayed.
Examples
As a simple example, suppose the manufacturer specifies a particular display as having a 100 hour
lifetime. If only the digits 0 and 1 are displayed, each with a 25 percent probability, then the
display will require only a single digit, and it will be blank 50 percent of the time. During the
remaining time, the rightmost two vertical segments will be illuminated, since they are on during
the display of 0 or 1. Given these conditions, the display will correctly operate for at least 200
hours.
Suppose the values to be displayed are 0, 1, 10, and 11, each with a probability of 25 percent. If the
display has the same manufacturer-specified lifetime, then two single-digit display units will be
required, and the display will correctly operate for at least 100 hours.
Finally, assume arbitrary decimal digits are to be displayed (with equal probability) 50 percent of
the time. With a segment lifetime of 50 hours, the display can be expected to operate correctly
for at least 111.11 hours. This is because no segment is illuminated in more than 90 percent of the
digits displayed.
Input
For this problem there are multiple cases. The input for each case begins with two integers. The
first of these is the manufacturer-specified lifetime of a display, in hours; the second is the
number of ranges of values to be displayed. For each of these ranges there follows a group of three
integers that give the lowest and highest values in the range, and the probability that one of these
values will appear. The largest value will never require a display with more than six digits. Input for
the last case is followed by a single integer 1.
Output
For each case, display the case number (starting with 1) and the minimum time (with two fractional
digits) the display will operate correctly. Leave a single blank line between the output for
consecutive cases.
Sample Input
100 1
0 1 50
100 4
0 0 25
1 1 25
10 10 25
11 11 25
100 2
0 1 50
10 11 50
50 1
0 9 50
-1
Score
41
22
2
11
24
26
4
Maximum
Possible
42
64
26
44
27
70
30
Sample Input
41 42 22
64 2 26 11 44
24 27
26 70 4
30 -1
-1
Output for the Sample Input
Case 1:
Dropping no grades: 42.90
Dropping 1 grade: 46.21
Dropping 2 grades: 50.22
Dropping 3 grades: 56.80
Sample Input
5
145 472 812
827 133 549
381 371 900
271 389 128
718 217 491
4
432 123 139
942 844 783
481 487 577
677 581 701
-1
Case 1: 2 boxes
Case 2: 4 boxes
Input
There may be multiple cases. The input for each case begins with a line containing three integers
that specify the widths of the conveyor belts, in increasing order. That is, conveyor A is the
narrowest, and conveyor C is the widest. No two conveyor belts will have the same width. This line
will be followed by additional lines, one for each box, in the order they are placed on the conveyor
belts. Each of these lines contains three positive non-zero integers giving the dimensions of a box.
The first of these lines gives data for box 1, the second line for box 2, and so forth. The last box in
each case will be followed by a line containing three integers, each 1.
Input for the last case is followed by a line containing three integer zeroes.
Output
For each case, display the case number (starting with 1) on a line by itself. Then display additional
lines, each of which gives the number of a box and the letter (A, B, or C) identifying the conveyor
belt from which it fell. These must be in the correct temporal order, over all conveyor belts. That
is, if box X falls off conveyor B before box Y falls off conveyor A, then output from box X must
precede the output for box Y, even if box Y was placed on conveyor A before box X was placed on
conveyor B. Make your output appear similar to that shown in the samples below. Leave a single
blank line between the output for consecutive cases. Note that there will be fewer lines of output
than there are boxes, since some boxes will remain on the conveyors at the end of the program.
Also, placing one large box on the conveyor may force more than one box (or no boxes) off the end.
Sample Input
10 15 20
6 8 10
4 11 8
19 8 8
5 9 12
10 10 10
888
9 9 14
-1 -1 1
000
Case 1:
Box 1 fell off conveyor A
Box 2 fell off conveyor A
23
88
-1
Case 1: 19029075
Case 2: 817488
6
12345 12346 17345 17346 22346 26346
6
59304 58304 8300 48304 19304 58303
5
10057 57 10056 50056 58
0
Case 1. 6 values
Case 2. 4 values
Case 3. 5 values
The football foundation (FOFO) has been researching on soccer; they created a set of sensors to describe the
ball behavior based on a grid uniformly distributed on the field. They found that they could predict the ball
movements based on historical analysis. Each square sensor of the grid can detect the following patterns:
N north (up the field)
S south (south the field)
E east (to the right on the field)
W west (to the left on the field)
For example, in grid 1, suppose the ball was thrown into the field from north side into the field. The path the
sensors detected for this movement follows as shown. The ball went through 10 sensors before leaving the
field.
Comparing with what happened on grid 2, the ball went through 3 sensors only once, and started a loop
through 8 instructions and never exits the field.
You are selected to write a program in order to evaluate line judges job, with the following out put based on
each grid of sensors, the program needs to determine how long it takes to the ball to get out of the grid or how
the ball loops around.
Input
There will be one or more grids of sensors for the same game. The data for each is in the following form. On the
first line are three integers separated by blanks: The number of rows in the grid, the number of columns in the
grid, and the number of the column in which the ball enters from the north. The grid columns number starts with
one at the left. Then come the rows of direction instructions. The lines of instructions contain only the characters
N, S,E or W, with no blanks. The end of input is indicated by a grid containing 0 0 0 as limits.
Output
For each grid in the input there is one line of output. Either the ball follows a certain number of sensors and exits
the field on any one of the four sides or else the ball follows the behavior on some number of sensors repeatedly.
The sample input below corresponds to the two grids above and illustrates the two forms of output.
The word step is always immediately followed by (s) whether or not the number before is 1.
Sample Input
365
NEESWE
WWWESS
SNWWWW
451
SESWE
EESNW
NWEEN
EWSEN
000
Sample Output
10 step(s) to exit
3 step(s) before a loop of 8 step(s)
Since R2-D2 needs an exact solution, we ask him to report the following:
The solution needs to be given as a pair of relative prime numbers a,b such that
f(N)= a/b if the solution is not an exact integer. Otherwise just give the exact integer. The numbers processed
by R2-D2 were of eight digits (99999999). Remember that R2-D2 was built long long time ago. His circuits are
not that fast but he is clever. R2-D2 was able to perform one of these operations in less than one second. Can
you do this assignment as fast as R2-D2 did it???
Input
You will receive an input line with natural numbers separated by comma. Each number is less than 99999999.
You will receive no more than 20 numbers.
Output
You need to give a sequence of lines each one with the solution of the corresponding input case. The solution
is either a pair of natural numbers separated by the symbol / representing the pair a,b mentioned above (when
the division is not exact) or just one natural number (when the division is exact). Notice that these numbers
could require more than 8 digits.
Sample Input
1,2
Sample Output
1
6/5
5575
8 10 16 11
16 11 13 6
11 3 8 5
10 10 20 10 20 20 10 20
5
15 15 15 19
25 19 25 17
17 17 17 15
15 19 25 19
17 17 25 17
Sample Output
The area free for your father is: 85.000 and your land is: 5 7 8 10 12 9 13 6 11 3
8555
Trying to steal neighbours land
Trying to steal neighbours land
66. Problem: Q
Introduction
You've got a queue. And you just got to mess with it.
Given a queue of items and a series of queue operations, return the resulting queue.
Queue operations are defined as follows:
starting-position to requested-position
meaning one wants the item at the starting position to be moved to the requested position. So if the queue of
items were:
Item1 Item2 Item3 Item4 Item5
(Item1 being in position 1, Item2 in position 2, etc.)
after applying the queue operation:
5 to 2
the resulting queue would be:
Item1 Item5 Item2 Item3 Item4
as Item5 (the item in position 5) was moved to position 2. Multiple queue operations are applied at the same
time, however; e.g., given the queue of items:
Item1 Item2 Item3 Item4 Item5 Item6 Item7 Item8
If the following queue operations were applied:
2 to 6; 6 to 3; 4 to 5; 5 to 2; 7 to 4; 8 to 1
then the resulting queue would be:
Item8 Item5 Item6 Item7 Item4 Item2 Item1 Item3
As you can see, the queue operations are strictly enforced, with other items (not involved in queue
operations) maintaining their order and moving to vacant positions in the queue. Note that no two queue
operations will have the same starting-position or same requested-position defined.
Input
Input to this problem will begin with a line containing a single integer x indicating the number of datasets.
Each data set consists of three components:
1. Start line A single line, "m n" (1 <= m, n <= 20) where m indicates the number of items in the
queue and n indicates the number of queue operations.
2. Queue items A line of short (between 1 and 8 characters) alphanumeric names for the items in the
queue. Names are unique for a given data set and contain no whitespace.
3. Queue operations n lines of queue operations in the format "starting-position requestedposition".
Output
For each dataset, output the queue after the queue operations have been applied. Print the elements of the
queue on a single line, starting from the first and ending with the last, with a single space separating each
item.
Sample Input
35
1
alpha beta gamma delta epsilon
52
86
abcdefgh
26
63
45
52
74
81
32
foo bar baz
31
13
Sample Output
alpha epsilon beta gamma delta
hefgdbac
baz bar foo
LAMPSHADE
EDIT
SO
PLAYER
ESTEEM
55
#####
#.#.#
#####
#.#.#
#####
6A
DAGE
ANGRY
YEARN
NEEDS
FLUTE
XYZZY
Sample Output:
Puzzle #1
..C......
P.O......
LAMPSHADE
A.P.O...D
Y.U.....I
ESTEEM..T
R.E......
Puzzle #2
I cannot generate this puzzle.
Redcode Simulator (MARS). Your goal is to write a MARS that will read in two Redcode programs,
simulate them, and print out which program was the winner.
MARS simulates a somewhat unusual environment compared to other virtual machines and processor
architectures. The following list describes these differences in detail:
1. MARS simulates a machine with 8000 memory locations and each location stores exactly one
Redcode instruction. In fact, a memory location can only store instructions and cannot directly store
any data. However, each instruction includes two numeric operands, and these in turn can be
manipulated by other instructions for data storage. This also makes self-modifying code possible.
2. The memory locations are arranged as a continuous array with the first location having address 0 and
the last having 7999. All address calculations are performed using modulo 8000 arithmetic. Put in
another way, memory addresses wrap around so that addresses 8000, 8001, and 8002 refer to same
memory locations respectively as addresses 0, 1, and 2. This also works for negative numbers. For
example, -7481, -15481, 519, and 8519 all refer to the same memory location.
3. All arithmetic and comparison operations are performed modulo 8000. Additions must normalize their
final result to be in the range of 0 to 7999 (inclusive) before writing that result into memory. This also
implies that -124 is considered to be greater than 511 since after normalization, -124 becomes 7876,
and 7876 is greater than 511.
4. The simulator maintains two separate instruction pointers (IPs) that store the address of the next
instruction to be executed by the warrior programs. After loading both programs into memory, these
IPs are initialized to the first instruction of each program. As the programs run, the IP is incremented
by one (modulo 8000) after each instruction is executed. If a jump/skip instruction is executed, then
the IP is instead loaded with the destination address of the jump/skip and execution continues from
this new address.
5. The simulator "time slices" between warriors by executing one instruction at a time, and alternating
between programs after each instruction. For example, if the two programs were loaded at addresses
2492 and 6140, the first six instructions would be executed in this order (assuming no jump/skip
instruction were executed): 2492, 6140, 2493, 6141, 2494, 6142.
Every instruction in MARS consists of an opcode, written as a three letter mnemonic, and two operands
called the A and B fields. Each operand is a number in the range 0-7999 (inclusive) and each can use one of
three addressing modes: immediate, direct, and indirect. These modes are explained in more detail below:
Immediate operands are written with a "#" sign in front, as in #1234. An immediate operand specifies a
literal value for the instruction to operate on. For example, the first operand (i.e. the A field) of an ADD
instruction (which performs integer addition) can be an immediate. In that case, the literal value specified
by the first operand provides one of the numbers being added.
Direct operands identify the memory locations which an instruction is to access. They are written with a
"$" sign in front, as in $1234. One example would be ADD #5 $3. A direct operand is actually an offset
relative to the current IP address. For example, if the ADD #5 $3 instruction were stored in memory
location 4357, it would actually be adding together a literal number five with a second value stored in the
B field of location 4360 (4357 + 3). However, if that same instruction were stored at location 132 it would
be adding five to a value in the B field of location 135 (132 + 3).
Indirect operands are analogous to how pointers in some programming languages work. Indirect
operands are written with a "@" sign in front of the number, as in ADD #5 @3. Like before, the indirect
operand is an offset relative to the current IP address, and therefore identifies a particular memory
location. However, the value stored in the B field of this memory location is then used as an offset relative
to that location to identify a second location. It is the B field of this second location which will actually be
operated on by the instruction itself. For example, if location 4357 contained ADD @1 @3, location 4358
contained 11 in its B field, and location 4360 contained 7996 in its B field, then this instruction would
actually be adding the values stored in locations 4369 (4358 + 11) and 4356 (4360 + 7996 modulo 8000).
The list below explains what each instruction does based on its opcode. Although not all instructions use
both of their operands, these must still be specified since other instructions might use these operands for
data storage. Some instructions update the B field of another instruction; this only affects the
numerical value of the field, but does not change its addressing mode.
DAT
This instruction has two purposes. First, it can be used as a generic placeholder for arbitrary data.
Second, attempting to execute this instruction terminates the simulation and the program which tried
to execute it loses the match. This is the only way that a program can terminate, therefore each
warrior attempts to overwrite the other one's program with DAT instructions. Both A and B operands
must be immediate.
MOV
If the A operand is immediate, the value of this operand is copied into the B field of the instruction
specified by MOV's B operand. If neither operand is immediate, the entire instruction (including all
field values and addressing modes) at location A is copied to location B. The B operand cannot be
immediate.
ADD
If the A operand is immediate, its value is added to the value of the B field of the instruction
specified by ADD's B operand, and the final result is stored into the B field of that same instruction. If
neither operand is immediate, then they both specify the locations of two instructions in memory. In
this case, the A and B fields of one instruction are respectively added to the A and B fields of the
second instruction, and both results are respectively written to the A and B fields of the instruction
specified by the ADD's B operand. The B operand cannot be immediate.
JMP
Jump to the address specified by the A operand. In other words, the instruction pointer is loaded
with a new address (instead of being incremented), and the next instruction executed after the JMP
will be from the memory location specified by A. The A operand cannot be immediate. The B
operand must be immediate, but is not used by this instruction.
JMZ
If the B field of the instruction specified by JMZ's B operand is zero, then jump to the address
specified by the A operand. Neither the A nor B operand can be immediate.
SLT
If A is an immediate operand, its value is compared with the value in the B field of the instruction
specified by SLT's B operand. If A is not immediate, the B fields of the two instructions specified by
the operands are compared instead. If the first value (i.e the one specified by A) is less than the
second value, then the next instruction is skipped. The B operand cannot be immediate.
CMP
The entire contents of memory locations specified by A and B are checked for equality. If the two
locations are equal, then the next instruction is skipped. Memory locations are considered equal to
another if they both have the same opcodes and they have the same values and addressing modes in
their respective operand fields. The A or B operands cannot be immediate.
Input:
The input begins with a line containing a single integer n indicating the number of independant simulations
to run. For each simulation the input will contain a pair of programs, designated as warrior number one and
warrior number two. Each warrior program is specified using the following format:
One line with integer m (1 <= m <= 8000) indicating the number of instructions to load for this warrior. A
second line containing an integer a (0 <= a <= 7999) gives the address at which to start loading the warrior's
code. These two lines are then followed by m additional lines containing the warrior's instructions, with one
instruction per line. If the warrior is loaded at the end of memory, the address will wrap around and the
instructions continue loading from the beginning of memory.
The address ranges occupied by the two programs will not overlap. All other memory locations which
were not loaded with warrior code must be initialized to DAT #0 #0. Execution always begins with
warrior number one (i.e. the warrior read in first from the input file).
Output:
Each simulation continues running until either warrior executes a DAT instruction or until a total of 32000
instructions (counting both warriors) are executed. If one warrior program executes a DAT, the other is
declared the winner; display "Program #x is the winner.", where x is either 1 or 2 and represents the
number of the winning warrior. If neither program executes a DAT after the maximum instruction count is
reached, then the programs are tied; display "Programs are tied."
Sample Input:
231
85
ADD #4 $2
JMP $-1 #0
DAT #0 #-3
51
00
JMP $2 #0
DAT #0 #-1
ADD #5 $-1
MOV $-2 @-2
JMP $-2 #0
15
524
MOV $0 $1
55
39
JMP $2 #0
DAT #0 #-1
ADD #5 $-1
MOV $-2 @-2
JMP $-2 #0
Sample Output:
Program #2 is the winner.
Programs are tied.
that will unlock it. This control panel is accessible from only one side of the door. So, for example, if the
layout of a house looked like this:
with rooms numbered 0-6 and control panels marked with the letters "CP" (each next to the door it can
unlock and in the room that it is accessible from), then one could say that the minimum number of locks to
perform to secure room 2 from room 1 is two; one has to lock the door between room 2 and room 1 and the
door between room 3 and room 1. Note that it is impossible to secure room 2 from room 3, since one would
always be able to use the control panel in room 3 that unlocks the door between room 3 and room 2.
Input
Input to this problem will begin with a line containing a single integer x indicating the number of datasets.
Each data set consists of two components:
1. Start line a single line "m n" (1 <=m<= 20; 0 <=n<= 19) where m indicates the number of rooms in
the house and n indicates the room to secure (the panic room).
2. Room list a series of m lines. Each line lists, for a single room, whether there is an intruder in that
room ("I" for intruder, "NI" for no intruder), a count of doors c (0 <= c <= 20) that lead to other
rooms and have a control panel in this room, and a list of rooms that those doors lead to. For
example, if room 3 had no intruder, and doors to rooms 1 and 2, and each of those doors' control
panels were accessible from room 3 (as is the case in the above layout), the line for room 3 would
read "NI 2 1 2". The first line in the list represents room 0. The second line represents room 1, and
so on until the last line, which represents room m - 1. On each line, the rooms are always listed in
ascending order. It is possible for rooms to be connected by multiple doors and for there to be more
than one intruder!
Output
For each dataset, output the fewest number of locks to perform to secure the panic room from all the
intruders. If it is impossible to secure the panic room from all the intruders, output "PANIC ROOM BREACH".
Assume that all doors start out unlocked and there will not be an intruder in the panic room.
Sample Input
37
2
NI 0
I3045
NI 2 1 6
NI 2 1 2
NI 0
NI 0
NI 0
72
I0
NI 3 0 4 5
NI 2 1 6
I212
NI 0
NI 0
NI 0
43
I0
NI 1 2
NI 1 0
NI 4 1 1 2 2
Sample Output
2P
ANIC ROOM BREACH
1
1. With at least 10 hcp and a yxxx distribution (y >= 8), bid the suit with y cards at the 4 level. This is
known as a preemptive bid.
2. With 1013 hcp and a 7xxx distribution, bid the suit with 7 cards at the 3level. This is known as a
preemptive bid.
3. With 89 hcp and a yxxx distribution (y >= 7), bid the suit with y cards at the 2level if the ycard suit
is Spades or Hearts. This is known as a "weaktwo" bid.
4. With 811 hcp and a 6xxx distribution, in which Spades or Hearts is one of the 6card suits, bid the
higher rank suit at the 2 level. This is known as a "weaktwo" bid.
5. With 1115 hcp, a distribution of 4441 or 5440, and at least 4 spades, bid Diamonds at the 2
level. This is called the "Mini Roman Convention".
6. With 1517 hcp and a balanced distribution, bid No Trump at the 1 level provided that at least 3 suits are
"stopped." A suit is considered stopped if the suit contains at least one of the following:
an A;
a K and one other;
a Q and two others; or
a J and three others;
7. With 2022 hcp and a balanced distribution, bid No Trump at the 2 level.
8. With at least 22 hcp, bid Clubs at the 2 level.
9. With 1316 hcp:If there is a 5card or longer suit in Spades or Hearts, bid it at the 1 level. If both bids are
possible, bid the longer suit.
a. If both suits have the same length, bid the higher ranking suit.
b. Without a 5card suit in Spades or Hearts, bid the longer of Diamonds or Clubs at the 1
level (whichever one has the most number of cards) . If there is a tie, bid the higher
ranking suit.
10. With at least 17 hcp, bid the longest suit at the 1 level. If there is a tie, bid the lowest ranking suit. This is
known as a "reverse".
11. If none of the rules above is applicable, bid Pass.
In the example above, rule 9a applies and a bid of 1 Hearts should be made.
Input
The input consists of a number of cases. The bridge hand for each case is specified on one line, with a single
space separating each of the 13 cards in the hand. Each card is given as a twocharacter string. The first letter
is the suit (S, H, D, C) and the second character is the rank (A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, 2). The end of
input is terminated by endoffile.
Output
For each case, print the hand number (starting from 1), followed by a colon and a space, and then the
suggested bid on a single line (see below for the exact format). Each bid is either "Pass" or a level and a suit
("No Trump", "Spades", "Hearts", "Diamonds", "Clubs") separated by a single space.
Sample input
SA S2 HK HJ HT H9 H2 D3 CK CQ C7 C4 C3
SK SQ HT H8 H4 CA CQ CT C5 DK DQ DJ D8
SA SK SQ S3 S2 HT D7 D9 CA CK CQ C7 C5
Output for sample input
Hand #1: 1 Hearts
Hand #2: 1 No Trump
Hand #3: 1 Clubs
Problem: GPA
Each course grade is one of the following five letters: A, B, C, D, and F. (Note that there is no grade E.) The
grade A indicates superior achievement, whereas F stands for failure. In order to calculate the GPA, the letter
grades A, B, C, D, and F are assigned the following grade points, respectively: 4, 3, 2, 1, and 0.
Input
The input file will contain data for one or more test cases, one test case per line. On each line there will be one
or more upper case letters, separated by blank spaces.
Output
Each line of input will result in exactly one line of output. If all upper case letters on a particular line of input
came from the set {A, B, C, D, F} then the output will consist of the GPA, displayed with a precision of two
decimal places. Otherwise, the message "Unknown letter grade in input" will be printed.
Sample input
ABCDF
BFFCCA
DCEF
Output for sample input
2.00
1.83
Unknown letter grade in input
When n is larger, things may not be quite as clear. Below we see a knot on 6 vertices. We might consider
moving vertex 4 between 5 and 6, then vertex 5 between 1 and 2, and finally vertex 6 between 3 and 4; this
unwinds the knot in 3 moves.
But clearly we can unwind the same knot in only two moves:
Input
The input consists of a number of cases. Each case starts with a line containing the integer n (3 <= n <= 500),
giving the number of vertices of the graph. The vertices are labelled clockwise from 1 to n. Each of the next n
lines gives a pair of neighbors, where line i (1 <= i <= n) specifies the two vertices adjacent to vertex i. The
input is terminated by n = 0.
Output
For each case, if there is no solution, print "Not solvable." on a line by itself. If there is a solution, print "Knot
solvable." on a line by itself, followed by the minimum number of moves required to solve the problem, on a
line by itself.
Sample input
6
45
35
26
16
12
34
6
26
14
56
25
34
13
0
Output for sample input
Knot solvable.
2
Knot solvable.
1
76.Problem: Knots
An even number N of strands are stuck through a wall. On one side of the wall, a girl ties N/2 knots between
disjoint pairs of strands. On the other side of the wall, the girl's groomtobe also ties N/2 knots between
disjoint pairs of strands. You are to find the probability that the knotted strands form one big loop (in which
case the couple will be allowed to marry).
For example, suppose that N = 4 and you number the strands 1, 2, 3, 4. Also suppose that the girl has created
the following pairs of strands by tying knots: {(1, 4), (2,3)}. Then the groomtobe has two choices for tying
the knots on his side: {(1,2), {3,4)} or {(1,3), (2,4)}.
Input
The input file consists of one or more lines. Each line of the input file contains a positive even integer, less
than or equal to 100. This integer represents the number of strands in the wall.
Output
For each line of input, the program will produce exactly one line of output: the probability that the knotted
strands form one big loop, given the number of strands on the corresponding line of input. Print the
probability to 5 decimal places.
Sample input
4
20
Output for sample input
0.66667
0.28377
Problem: Marbles in Three Baskets
Each of three baskets contains a certain number of marbles. You may move from one basket into another
basket as many marbles as are already there, thus doubling the quantity in the basket that received the
marbles. You must find a sequence of moves that will yield the same number of marbles in the three baskets.
Moreover, you must achieve the goal in the smallest possible number of moves. Your program must also
recognize the case in which there is no such sequence of moves.
Input
Each line of the input file will contain data for one instance of the problem: three positive integers, with one
blank space separating adjacent integers. The three integers represent the initial numbers of marbles in the
three baskets. The sum of the three integers will be at most 60.
Output
The output will begin with the initial configuration from the input. Thereafter, on successive lines, the number
of marbles in the respective baskets will be printed after each move, concluding with the line in which the
three numbers are identical. As stated above, the goal must be achieved in the smallest possible number of
moves. (The correct output is not unique, however. There may be different sequences of moves which achieve
the goal correctly in the smallest possible number of steps.) If there is no sequence of moves to achieve the
goal, only the initial configuration will be printed. Each integer in the output will be rightjustified in a field
of width 4. Each instance of the problem will be concluded by a line of 12 equal signs.
Sample input
6 7 11
15 18 3
567
|4|,|0|
|5| |0|
|6|M|1|
|7|a| |
|8|r| |
|9|c| |
|0|h| |
|1| | |
|2|2| |
|3|0| |
|4|0| |
|5|2| |
-------
INPUT FORMAT
The input will consist of one or more scenarios, each scenario consisting of two lines.
The first line contains a descriptive title, which is a string of letters or spaces no more
than 200 characters long, containing at least 1 letter.
The second line starts with the number of basins n (3 n 200), a space, and then n
integers in the range 0 to 99, separated by single spaces, representing the water
levels in the tanks.
The scenarios sequence is terminated by a single # character on a line by itself.
OUTPUT FORMAT
Output one line for each input scenario. The line consists of the first letter of each
word in the descriptive title in upper case, followed by a colon (:), a space, and then
the minimum number of valves that need to be open to achieve equal heights in all
tanks.
SAMPLE OUTPUT:
HFDB: 2
TAE: 5
SAMPLE INPUT:
High four dude basins
44433
At each simulation step the two sons move in lock-step, each hopping according to
his own instructions. To avoid conflicts, each time Raul and George are about to hop
to the next tile the simulation must check whether they would land on the same tile.
If so, the simulation ends without them moving, and the landing tile remains painted
in its previous colour, if any. Otherwise, the simulation will end as soon as one of the
sons ends his instructions.
Each tile can contain only one colour spot, either red or green. Since it is possible
that Raul and George land on the same tile at different times, the simulation should
only count the tile towards the son landing there last.
To avoid Raul and George falling off the edge of the tile grid, they are allowed to
wrap around, in all directions. For example, for a grid of the same size as above, one
hypothetical move from (8,3) in the direction (2,3) results in the tile (0,1).
y
x
Your task is to write a program that computes the results of such a simulation given
the grid size and the instructions for each son.
INPUT FORMAT
The input consists of one or more scenarios. Each scenario consists of 3 lines. The
first line contains two numbers separated by a space, N and M, 2 N, M 1000,
respectively representing the width and the height of the grid. The second line
contains the instructions for Raul and the third line the instructions for George. Each
instruction line starts with a number C, in the range 1 to 100, followed by C groups of
3 numbers. In each group the first number is a repetition count in the range 1 to
1,000,000,000, the second number is an increment along the x-axis, and the third
number an increment along the y-axis - both increments are in the range -1,000 to
1,000. All numbers are separated by single spaces. The end of the input is indicated
by a grid of size 0, i.e., a 0 on a line by itself.
OUTPUT FORMAT
Output one line for each input scenario. Each output line should show two numbers
separated by a single space, representing the earnings of Raul and George, in this
order.
SAMPLE INPUT:
10 5
2210321
3 4 -2 0 1 0 -9 2 1 0
10 10
2 1 15 5 1 0 0
2 1 0 0 2 -4 -4
10 7
2 1000 2 -1 1000 0 -1
2 1000 -1 0 1000 -1 0
10 10
5 1000 2 -1 1000 1 0 2 5 5 3 1 1 10 1 1
5 1000 -1 0 1000 0 1 3 -4 -4 2 -1 -1 10 -1 -1
0
SAMPLE OUTPUT:
56
21
30 10
18 18
Your task is to write a program that displays all possible matches for given digit
sequences, using a given dictionary.
A digit sequence corresponds to a sequence of words, with zero digits (0) indicating
spaces. Leading and trailing zeros are ignored, and multiple consecutive embedded
zeros are treated as a single zero. For each sequence of non-zero digits, display the
matching word from the dictionary. When more than one match is available, display
all matches in dictionary order between round parentheses and separated by bars
(|). If there is no matching word, display a sequence of asterisks (*) of the same
length. For example, with a dictionary consisting solely of the words i, loud,
love, programming, the digit sequence
0040568300077647266464077770
will be displayed as the text
i (loud|love) programming ****
INPUT FORMAT
The input will consist of one or more scenarios, each scenario consisting of a
dictionary of permitted words and a series of digit sequences to be interpreted as text
messages.
The dictionary consists of 1 to 1,000 words, one word per line, in increasing
dictionary order, with no duplicates. Each word consists of 1 to 30 lowercase letters.
For any given non-zero digit sequence there will be no more than 10 matching words
in the dictionary. The end of the dictionary is indicated by a line consisting of a single
#.
The digit sequences to interpret as text messages follow the dictionary, one per line.
Each message line consists of 1 to 100 digits, with at least 1 non-zero digit. The end
of messages is indicated by a line consisting of a single #.
The end of input is indicated by an empty dictionary (a dictionary with zero words).
OUTPUT FORMAT
For each scenario output a line consisting of the word SET (all uppercase) followed
by a space and then the scenario number, starting with 1. Following this output the
list of interpreted text messages, one message per line.
SAMPLE INPUT:
i
loud
love
programming
#
0040568300077647266464077770
#
a
game
go
golf
good
hand
hold
hole
home
in
me
of
to
#
2046630426306304653
46086020466304663
#
#
SAMPLE OUTPUT:
SET 1
i (loud|love) programming ****
SET 2
a (good|home) (game|hand) (me|of) (golf|hold|hole)
(in|go) to a (good|home) (good|home)
Write a program that will read in a sequence of tiles and a target pattern and
determine whether the target pattern can be made by some arrangement of all or
some of the input tiles.
If there are several ways of achieving the target, then choose the pile with fewest tiles.
If there are still several ways of achieving the target, then at every point in the pile, in a topdown order,
choose first the lowest numbered appropriate tile and, if still needed, the lowest numbered appropriate
transformation.
INPUT FORMAT
The input will consist of one or more of problems. The first line of each problem
contains the title of the problem as a string of 1 to 30 characters other than space,
followed by a space, and the number of tiles n (1 n 10). This is followed in turn by
n+1 lines, the first n lines specifying the tiles (implicitly numbered 0 to n-1); and the
last line specifying the target pattern. Each of these n+1 lines contains 4 blocks of 4
characters, either an upper case letter representing a colour, or a full stop (.)
representing transparency. Blocks are separated by single spaces and represent grid
rows, in successive row order. Characters composing blocks represent grid cells, in
successive column order. The end of input is signified by a line consisting of a single
#.
OUTPUT FORMAT
Output consists of one line for each problem, consisting of the title of the problem,
followed by a space, and either the word noway (all lowercase) if the target cannot
be achieved, or a description of the pile if the target can be achieved. The tiles in the
pile should be listed in order from the top of the pile downwards, in the form: tile
number (0 through n-1), slash (/), transformation number (0 through 7). Separate
descriptions of successive tiles by single spaces.
SAMPLE INPUT:
OBVIOUS 1
RRGG RRGG YYBB YYBB
BBGG BBGG YYRR YYRR
EASY 2
BBBB BBBB ..BB ..BB
RRRR RRRR .... ....
RRRR RRRR BBBB BBBB
Is-this-possible? 2
BBBB BBBB ..BB ..BB
RRRR RRRR .... ....
RRBB RRBB BBRR BBRR
#
SAMPLE OUTPUT:
OBVIOUS 0/7
EASY 1/0 0/1
Is-this-possible? noway
Each day the postal van leaves the post office, drives around the suburb and returns
to the post office, passing exactly once through every intersection (including those on
borders or corners). The executives from the post company want to know how many
distinct routes can be established for the postal van (of course, the route direction is
significant in this count).
For example, the following diagrams show 2 such routes for the above suburb:
As another example, the following diagrams show all the 4 possible routes for a
suburb with N=3 streets.
Write a program that will determine the number of such distinct routes given the
number of streets.
INPUT FORMAT
The input text consists of one or more lines, each containing a single number from 1
to 1000 inclusive the number of parallel streets. A single # on a line by itself
indicates the end of input.
OUTPUT FORMAT
There is a single line of output for each input value. Each output line consists of the
number of streets followed by a colon (:) and a space, followed by the number of
possible distinct routes corresponding to that many streets. Each number is
displayed as a decimal number, with commas (,) used as separators between
groups of 3 digits, counting from the right.
SAMPLE INPUT:
1
2
3
4
10
30
#
SAMPLE OUTPUT:
1: 0
2: 2
3: 4
4: 12
10: 3,034
30: 374,605,036,706
As another example, the images (e) and (f) below could also show two possible
rearrangements of the same tree.
This plan is a great success and the tourists are flocking back to see the constantly
changing forest. Our friends Mary and Paul have been there several times and each
time theyve brought home many good pictures. They have now decided to put a bit
of order in their collection of pictures, by identifying all matching tree images, i.e., all
images that could represent the same tree. To achieve this result, they intend to
associate a tag number with each image, such that images of trees are given the
same tag if, and only if, they match. For examples, the images (a), (b), (c), (d) above
could receive the tags 0, 0, 1, 2, in this order.
They have started by coding their collection of tree images. For each tree they
labelled each node, in no particular order, with a distinct number in the range 0 to k1, where k is the number of the nodes in that tree.
Your task is to write a program that will allow them to identify matching tree images.
INPUT FORMAT
Input consists of one or more scenarios, with each scenario consisting of a number of
tree images. Each scenario starts with a line containing a single number, n (1 n
100) specifying the number of images in the scenario, followed by n lines containing
image descriptions. Each image description line has at most 5,000 characters and
consists of a number k (1 k 1000) specifying the number of nodes in the tree,
followed by k numbers in the range -1 to k-1, specifying the parent of each node in
turn, using -1 for the root node (which has no parent). The sequence of scenarios is
terminated by an empty scenario, i.e., a line consisting of single zero (0).
OUTPUT FORMAT
Output consists of one line for each scenario, beginning with a scenario sequence
number (starting with 1), a colon (:), a space, and followed by a succession of tag
numbers, one for each image, in input order, and separated by single spaces. Tag
numbers are allocated successively in input image order, starting with 0, and
increased by 1 at the first occurrence of an image not matching any of the previous
images.
SAMPLE INPUT:
4
7 -1 0 0 6 6 6 0
7 -1 3 3 0 3 0 0
7 -1 0 1 1 6 6 1
7 -1 3 3 0 5 0 0
2
13 -1 0 0 0 1 1 2 2 3 4 4 5 6
13 -1 0 0 0 1 1 2 3 3 5 7 8 8
5
2 -1 0
3 -1 0 0
2 1 -1
3 -1 0 1
3 2 2 -1
0
SAMPLE OUTPUT:
1: 0 0 1 2
2: 0 0
3: 0 1 0 2 1
Note that the following are legal frequency assignments to these two tower configurations. However,
the second arrangement does not use the fewest number of frequencies possible, since the tower with
frequency 5 could have frequency 1.
Input
There will be multiple test cases. Input for each test case will consist of two lines: the first line will
contain the integer n, indicating the number of towers. The next line will be of the form x1 y1 x2 y2
... xn yn where xi yi are the coordinates of tower i. A pair of towers are considered near" each other
if the distance between them is no more than 20. There will be no more than 12 towers and no tower
will have more than 4 towers near it. A value of n = 0 indicates end of input.
Output
For each test case, you should print one line in the format:
The towers in case n can be covered in f frequencies.
where you determine the value for f. The case numbers, n, will start at 1.
Sample Input
5
0 0 5 7.5 1 -3 10.75 -20.1 12.01 -22
6
0 1 19 0 38 1 38 21 19 22 0 21
0
Sample Output
The towers in case 1 can be covered in 3 frequencies.
The towers in case 2 can be covered in 2 frequencies.
Suppose the top wall is programmed to move down 3 units (then retreats, as the walls always will) and
then the right wall is programmed to move left 14 units. The first operation can be performed with no
problem, but the second one can not be carried out without crushing some boxes. Therefore, the right
wall will move only 13 units, the maximum distance it can move until boxes are packed tightly between
it and the left wall. The boxes will then be in the configuration shown in the following figure. The
locations of the boxes are (3,1), (3,2), (6,0), (6,1), (6,2), (7,2), (8,2).
Input
There will be multiple data sets for this problem. The first line of each data set will be two integers
giving the height and width of the room. (We'll visualize the room as if on a piece of paper, as drawn
above.) Each dimension will be no more than 20. The next line will contain an integer n (0 < n <= 10)
followed by n pairs of integers, each pair giving the location of a box as the distances from the top and
the left walls of the room. The following lines will be of the form direction m, where direction is
either down, left, up, right, or done and m is a positive integer. For example, left 2 would mean
to try to move the right wall 2 spaces to the left. The \direction" done indicates that you are finished
pushing this set of boxes around. There will be no integer m following the direction done, of course.
The data sets are followed by a line containing 0 0.
Output
For each data set you are to produce one line of output of the form:
Data set d ends with boxes at locations (r1; c1) (r2; c2) (rn; cn).
where the (ri; ci) are the locations of the boxes given from top-to-bottom, left-to-right, (separated by
one space) and d is the data set number (starting at 1).
Sample Input
12 16
7 1 13 3 2 6 2 6 4 6 6 7 6 8 9
down 3
left 14
done
44
3102123
right 3
up 2
left 1
done
00
Sample Output
Data set 1 ends with boxes at locations (3,1) (3,2) (6,0) (6,1) (6,2) (7,2) (8,2).
Data set 2 ends with boxes at locations (0,2) (1,1) (1,2).
Note that this procedure only works as stated if the image is a square and has a side length equal to
a power of 2. For those images which do not meet those requirements, we pad the rows and columns
with 0's (on the right and on the bottom, respectively) until we have a bitmap of the appropriate size.
For example, a 5x13 image would be converted to a 16x16 bitmap (with the original image residing in
the upper left portion, and the remainder of the image filled with 0's).
While quadtrees can result in a significant savings in space over the original image, even more savings
can be achieved if we identify repeated subtrees. For example, in the tree above, the first and third
subtrees of the root are identical, so we could replace the root of the third subtree with a reference to
the first subtree, obtaining something that symbolically looks like the following:
We will call these compressed quadtrees super quadtrees, or squadtrees. For our purposes the use of a
reference saves space only when the tree it replaces has height of at least 1. Thus, while we could replace
5 of the nodes which contain a B with references to the first node with a B, this would not in practice
save any space in the compression. Using this rule, our squadtree contains only 12 nodes, as opposed
to 17 in the original quadtree. Your job for this problem is to take a set of images and determine the
number of nodes in both the resulting quadtrees and squadtrees.
Input
Input will consist of multiple problem instances. Each instance will start with a single line containing
two integers n and m, indicating the number of rows and columns in the image. The maximum values
for these integers is 128. The next n lines will each contain m characters representing the image to
process. A black pixel will be represented by a `1', and a white pixel will be represented by a `0'. The
input line 0 0 will terminate input and should not be processed.
Output
For each problem instance, output two integers separated by a single space. The first value is the
number of nodes in the quadtree for the problem instance, and the second is the number of nodes in
the squadtree.
Sample Input
44
1011
0111
1010
0111
67
1110111
1010101
0000000
0100010
1011101
1010101
00
Sample Output
17 12
61 24
Your problem is to determine, for a number of dierent cakes, the best cut, i.e., the one that divides the
cake into two pieces whose areas (we are disregarding the thickness of the cake) are as nearly equal as
possible. For instance, given a cake whose vertices (when the cake is viewed from above) are located, in
counterclockwise order, at the points (0; 1), (6; 0), (5; 2) and (2; 3), the best possible cut would divide
the cake into two pieces, one with area 4.375, the other with area 5.125; the cut joins the points (1; 2)
and (5:5; 1) (the midpoints of two of the sides).
Input
Input consists of a sequence of test cases, each consisting of four (x; y) values giving the counterclockwise
traversal of the cake's vertices as viewed from directly above the cake; the final test case is followed by
a line containing eight zeros. No three points will be collinear, all quadrilaterals are convex, and all
coordinates will have absolute values of 10000 or less.
Output
For each cake, the cake number followed by the two areas, smaller first, to three decimal places of
precision.
Sample Input
01605223
0 0 100 0 100 100 0 100
00000000
Sample Output
Cake 1: 4.375 5.125
Sample Output
3
124
25
194
101.Problem: Shufflem Up
A common pastime for poker players at a poker table is to shuffle stacks of chips. Shuffling chips is performed by
starting with two stacks of poker chips, S1 and S2, each stack containing C chips. Each stack may contain chips of
several different colors.
The actual shuffle operation is performed by interleaving a chip from S1 with a chip from S2 as shown below for
C=5:
The single resultant stack, S12, contains 2*C chips. The bottommost chip of S12 is the bottommost chip from S2. On
top of that chip, is the bottommost chip from S1. The interleaving process continues taking the 2nd chip from the
bottom of S2 and placing that on S12, followed by the 2nd chip from the bottom of S1 and so on until the topmost chip
from S1 is placed on top of S12.
After the shuffle operation, S12 is split into 2 new stacks by taking the bottommost C chips from S12 to form a new
S1 and the topmost C chips from S12 to form a new S2. The shuffle operation may then be repeated to form a new
S12.
For this problem, you will write a program to determine if a particular resultant stack S12 can be formed by shuffling
two stacks some number of times.
Input
The first line of input contains a single integer N, (1 N 1000) which is the number of datasets that follow.
Each dataset consists of four lines of input. The first line of a dataset specifies an integer C, (1 C 100) which is
the number of chips in each initial stack (S1 and S2). The second line of each
dataset specifies the colors of each of the C chips in stack S1, starting with the bottommost chip. The third line of
each dataset specifies the colors of each of the C chips in stack S2 starting with the bottommost chip. Colors are
expressed as a single uppercase letter (A through H). There are no blanks or separators between the chip colors.
The fourth line of each dataset contains 2*C uppercase letters, (A through H), representing the colors of the
desired result of the shuffling of S1 and S2 zero or more times. The bottommost chips color is specified first.
Output
Output for each dataset consists of a single line that displays the dataset number (1 though N), a space, and an
integer value which is the minimum number of shuffle operations required to get the desired resultant stack. If the
desired result can not be reached using the input for the dataset, display the value negative 1 (-1) for the number
of shuffle operations.
Sample Input
Sample Output
2
4
AHAH
HAHA
HHAAAAHH
3
CDE
CDE
EEDDCC
12
2 -1
Sample Output
3
3
4
3
1 3 25
2 4 149
3 3 25
Description
[nl]
[sc<digit>]
Insert <digit> blank character cells between each pair of text characters in the following string until
changed.
[/sc]
[jl2]
Set left justified text (the first character of the text is the leftmost character of the line).
[jl3]
Set center justified text (the number of character positions before and after the text on the line is the
same or the number after is one more than the number before).
[jl4]
Set right justified text (the final character of the string is the rightmost character on the line).
[jl5]
Set fully justified text (an equal number of blank character spaces, as large as possible for the line
length, is placed between each pair of characters in the text; the resulting string is centered in the
line as for centered text).
Generated Output
[jl2]MESSAGE
MESSAGE
[jl3]MESSAGE
MESSAGE
[jl4]MESSAGE
MESSAGE
[jl2][sc2]MESSAGE
MESSAGE
[jl5]MESSAGE
MESSAGE
[jl2]THIS[jl3]IS A[jl4]MESSAGE
THISIS AMESSAGE
Letters within tags are case-insensitive. That is [nl] = [NL] = [Nl] = [nL].
The default justification at the beginning of a message is left justification and the default character spacing is 0.
Justification and character spacing are maintained across [nl] tags.
The [jl2] and [jl5] tags may only be used before any text has been output on a line. Otherwise it is an error (TAG
CONFLICT).
Once [jl5] text has been output on a line, no other justification tag may be set on that line. Otherwise it is an error
(TAG CONFLICT).
The [jl3] tag may not be used after right justified text ([jl4]) has been output on a line. Otherwise it is an error
(TAG CONFLICT).
A justification tag [jl?] with the same value as the current value does not cause a TAG CONFLICT error.
Extra character spacing specified by the [sc?] tag is ignored on lines with fully justified text. The full justification
rules determine the extra spaces.
If too many characters are required on a line or too many lines are required in a message, it is an error (TOO
BIG). A [nl] tag does not begin a new line unless followed by text output.
If left justified text and center justified text appear on the same line, there must be at least one blank character cell
between the last character of left justified text and the first character of center justified text. Otherwise it is an error
(TOO BIG).
If center justified text and right justified text appear on the same line, there must be at least one blank character
cell between the last character of center justified text and the first character of right justified text. Otherwise it is an
error (TOO BIG).
If left justified text and right justified text appear on the same line, there must be at least one blank character cell
between the last character of left justified text and the first character of right justified text. Otherwise it is an error
(TOO BIG).
The only tags allowed in a message are the seven tags listed above otherwise it is an error (BAD TAG). A
malformed tag or an unmatched single open or closed bracket is a BAD TAG error.
For this problem you will write a program which takes as input the dimensions of the character cell array and a
MULTI string and either outputs an error string or a correctly formatted message.
Input
The first line of input contains a single integer N, (1 N 100), which is the number of datasets that follow. Each
dataset consists of a single line containing an integer R, (1 R 25), a blank, an integer C, (1 C 80), a blank,
and the remainder of the line is a MULTI-Text string. R is the number of rows in the character cell array, C is the
number of columns in the character cell array, and the MULTI-Text is the text to be formatted.
Output
For each dataset, output the dataset number on a line by itself, followed by one of the error strings (TAG
CONFLICT, TOO BIG, BAD TAG) on a line by itself in the case of an error, or, R lines each of which has exactly
C characters (other than terminating newlines) representing the formatted message using space characters for
empty character cells. The last line of output for a dataset result should be a single blank line.
Note: For ease in grading, a dataset that contains an error will only contain one type of error.
Sample Input
7
4 24 [jl2]MESSAGE[nl][jl3]MESSAGE[nl][jl4]MESSAGE
2 24 This[jl3]is a[jl4]message
2 24 This is a very long message which will not fit
4 24 This[nl]message[nl]has[nl]too[nl]many[nl]lines
2 32 [jl3]This message has a [[ and a ]]
2 32 This is a bad tag[xy34]
2 32 [jl3]This message [jl5] has a tag conflict.
Sample Output
(^ added after the last character of the lines for illustrative purposes. It should NOT appear in program output.)
1
MESSAGE ^
MESSAGE ^
MESSAGE^
^
2
This is a message^
^
3
TOO BIG
4
TOO BIG
5
This message has a [ and a ] ^
^
6
BAD TAG
7
TAG CONFLICT
Write a program which, given a value for the size, N, computes the number of visible points (x,y) with 0 x, y N.
Input
The first line of input contains a single integer C, (1 C 1000) which is the number of datasets that follow.
Each dataset consists of a single line of input containing a single integer N, (1 N 1000), which is the size.
Output
For each dataset, there is to be one line of output consisting of: the dataset number starting at 1, a single space,
the size, a single space and the number of visible points for that size.
Sample Input
Sample Output
4
2
4
5
231
125
2 4 13
3 5 21
4 231 32549
Write a program, which, given the size, N, of the triangular array, finds a maximal set of non-attacking queen
positions on the array (floor((2*N + 1)/3) of them).
Input
The input begins with a line containing an integer value specifying the number of datasets that follow, C, (1 C
1000). Each dataset consists of a single line containing a single integer N, (1 N 1000), which is the size of the
triangular array.
Output
The first output line for each problem gives the problem number starting at 1, a single space, the input size, a
single space and the number of queen positions. Following the first line will be the queen positions, 8 positions
per line except perhaps for the last line of positions. Each position has the format open bracket ([), row number
starting with 1, a comma, the position from the left within the row starting at 1 and a close bracket (]). Positions
within a line are separated by a single space. For example, the queen positions in Figure 2 are [1,1] [4,2] [5,4]
[6,3]. The lines of position values are followed by a single blank line.
Sample Input
Sample Output
6
3
6
9
10
14
18
132
[1,1] [3,2]
264
[3,1] [4,3] [5,5] [6,2]
396
[4,1] [5,3] [6,5] [7,7] [8,2] [9,4]
4 10 7
[4,1] [5,3] [6,5] [7,7] [8,2] [9,4] [10,6]
5 14 9
[6,1] [7,3] [8,5] [9,7] [10,9] [11,11] [12,2] [13,4]
[14,6]
6 18 12
[7,1] [8,3] [9,5] [10,7] [11,9] [12,11] [13,13] [14,2]
[15,4] [16,6] [17,8] [18,10]
Notes
11. There may be many different correct answers to a particular problem, so your answers need not be the
same as those in the Sample Output above.
22. Some solution methods for this problem may cause the time limit to be exceeded. Be sure to try the larger
values before submitting your solution.
Sample Output
6
1
7
31
7776
531441
123456789
1 1 [0,0]
2 2 [2,0] [0,1]
3 3 [4,0] [0,2] [1,1]
4 1 [5,5]
5 1 [0,12]
6 8 [3,13] [4,12] [2,15] [7,8] [9,6] [0,16] [10,5] [15,2]
16 5
7
Sample Output
2
6 25
8 9 8 7 16 5
30 250
1 2 3 4 5 6 7 8 9 10 11
12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
1 15
2 16509438
Sample Output
4
3
4
5
10
1 3 45
2 4 105
3 5 210
4 10 2145
109.Problem: Sudoku
The input starts with the number of test cases 0 N 50 on a single line.
Then for every test case follow nine lines describing last weeks puzzle solution, fromtop
to bottom. Each line corresponds to a row in the puzzle and consists of nine digits (1 . . . 9),
describing the contents of the cell from left to right.
Last weeks solution is followed by nine lines describing this weeks unsolved puzzle.
Here, also, every line corresponds to a puzzle row and every digit (0 . . . 9) describes the
contents of a cell. 0 indicates that the cell is empty. The rows are presented ordered from top
to bottom, and within each row, the cells are ordered from left to right.
After every test case except the last one follows a blank line. Every unsolved puzzle
is guaranteed to be uniquely solvable and last weeks solution is always a proper sudoku
solution.
Output
For every test case, output Yes if the sudoku puzzle can be derived from the given solved
puzzle using the allowed operations, or No if this is not possible.
Sample input
2
963174258
178325649
254689731
821437596
496852317
735961824
589713462
317246985
642598173
060104050
200000001
008305600
800407006
006000300
700901004
500000002
040508070
007206900
534678912
672195348
198342567
859761423
426853791
713924856
961537284
287419635
345286179
010900605
025060070
870000902
702050043
000204000
490010508
107000056
040080210
208001090
Sample output
Yes
No
An integer 0 T 5 on the first line gives the cardinality of the set of test cases. The first
line of each test case contains the number of operations 0 N 2 000. Then follow N lines
each containing one of the five commands. It is guaranteed that the SetStack computer can
execute all the commands in the sequence without ever popping an empty stack.
Output
For each operation specified in the input, there will be one line of output consisting of a
single integer. This integer is the cardinality of the topmost element of the stack after the
corresponding command has executed. After each test case there will be a line with ***
(three asterisks).
Sample input
2
9
PUSH
DUP
ADD
PUSH
ADD
DUP
ADD
DUP
UNION
5
PUSH
PUSH
ADD
PUSH
INTERSECT
Sample output
0
0
1
0
1
1
2
2
2
***
0
0
1
0
0
***
111.Problem: Pie
My birthday is coming up and traditionally Im serving pie. Not just one pie, no, I have
a number N of them, of various tastes and of various sizes. F of my friends are coming to
my party and each of them gets a piece of pie. This should be one piece of one pie, not several
small pieces since that looks messy. This piece can be one whole pie though.
My friends are very annoying and if one of them gets a bigger piece than the others,
they start complaining. Therefore all of them should get equally sized (but not necessarily equally
shaped) pieces, even if this leads to some pie getting spoiled (which is better than spoiling the party).
Of course, I want a piece of pie for myself too, and that piece should also be of the same size. What is
the largest possible piece size all of us can get? All the pies are cylindrical in
shape and they all have the same height 1, but the radii of the pies can be different.
Input
One line with a positive integer: the number of test cases. Then for each test case:
One line with two integers N and F with 1 N, F 10 000: the number of pies and
the number of friends.
One line with N integers ri with 1 ri 10 000: the radii of the pies.
Output
For each test case, output one line with the largest possible volume V such that me and my
friends can all get a pie piece of size V. The answer should be given as a floating point
number with an absolute error of at most 103.
Sample input
3
33
433
1 24
5
10 5
1423456542
Sample output
25.1327
3.1416
50.2655
For each game, output a single line containing a single integer, the minimum possible cost
to set up all four train lines.
Sample input
10 15
stockholm
amsterdam
london
berlin
copenhagen
oslo
helsinki
dublin
reykjavik
brussels
oslo stockholm 415
stockholm helsinki 396
oslo london 1153
oslo copenhagen 485
stockholm copenhagen 522
copenhagen berlin 354
copenhagen amsterdam 622
helsinki berlin 1107
london amsterdam 356
berlin amsterdam 575
london dublin 463
reykjavik dublin 1498
reykjavik oslo 1748
london brussels 318
brussels amsterdam 173
stockholm amsterdam
oslo london
reykjavik dublin
brussels helsinki
21
first
second
first second 10
first first
first first
second first
first first
00
Sample output
3907
10
No wonder the old bookcase caved under the massive piles of books Tom had stacked
on it. He had better build a new one, this time large enough to hold all of his books.
Tomfinds it practical to have the books close at hand when he works at his desk. Therefore,
he is imagining a compact solution with the bookcase standing on the back of
the desk. Obviously, this would put some restrictions on the size of the bookcase, it
should preferably be as small as possible. In addition, Tom would like the bookcase
to have exactly three shelves for aesthetical reasons.
Wondering how small his bookcase could be, he models the problem as follows. He measures
the height hi and thickness ti of each book i and he seeks a partition of the books in
three non-empty sets S1, S2, S3 such that
is minimized,
i.e. the area of the bookcase as seen when standing in front of it (the depth needed is obviously
the largest width of all his books, regardless of the partition). Note that this formula
does not give the exact area of the bookcase, since the actual shelves cause a small additional
height, and the sides cause a small additional width. For simplicity, we will ignore this small
discrepancy.
Thinking a moment on the problem, Tom realizes he will need a computer program to
do the job.
Input
The input begins with a positive number on a line of its own telling the number of test
cases (at most 20). For each test case there is one line containing a single positive integer N,
3 N 70 giving the number of books. Then N lines follow each containing two positive
integers hi, ti, satisfying 150 hi 300 and 5 ti 30, the height and thickness of book i
respectively, in millimeters.
Output
For each test case, output one line containing the minimum area (height times width) of a
three-shelf bookcase capable of holding all the books, expressed in square millimeters.
Sample input
2
4
220 29
195 20
200 9
180 30
6
256 20
255 30
254 15
253 20
252 15
Sample output
251 9
18000
29796
For each test case, print one line with a single integer; the number of minutes until your job
is completely printed, assuming that no additional print jobs will arrive.
Sample input
3
10
5
42
1234
60
119111
Sample output
1
2
5
The ministers of the cabinet were quite upset by the message from the Chief of Security stating that
they would all have to change the four-digit room numbers on their offices.
It is a matter of security to change such things every now and then, to keep the enemy in the dark.
But look, I have chosen my number 1033 for good reasons. I am the Prime minister, you know!
I know, so therefore your new number 8179 is also a prime. You will just have to paste four new
digits over the four old ones on your office door.
No, its not that simple. Suppose that I change the first digit to an 8, then the number will read 8033
which is not a prime!
I see, being the prime minister you cannot stand having a non-prime number on your door even for a
few seconds.
Correct! So I must invent a scheme for going from 1033 to 8179 by a path of prime numbers where
only one digit is changed from one prime to the next prime.
Now, the minister of finance, who had been eavesdropping, intervened.
No unnecessary expenditure, please! I happen to know that the price of a digit is one pound.
Hmm, in that case I need a computer program to minimize the cost. You dont know some very
cheap software gurus, do you?
In fact, I do. You see, there is this programming contest going on. . .
Help the prime minister to find the cheapest prime path between any two given four-digit
primes! The first digit must be nonzero, of course. Here is a solution in the case above.
1033
1733
3733
3739
3779
8779
8179
The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2
can not be reused in the last step a new 1 must be purchased.
Input
One line with a positive number: the number of test cases (at most 100). Then for each test
case, one line with two numbers separated by a blank. Both numbers are four-digit primes
(without leading zeros).
Output
One line for each case, either with a number stating the minimal cost or containing the word
Impossible.
Sample input
3
1033 8179
1373 8017
1033 1033
Sample output
6
7
0
Lineland is a strange country. As the name suggests, its shape (as seen from above) is just a
straight line, rather than some two-dimensional shape. The landscape along this line is very
mountainous, something which occasionally leads to some problems. One such problem
now occurs: in this modern era the king wants to build an airport to stimulate the countrys
economy. Unfortunately, its impossible for airplanes to land on steep airstrips, so a horizontal
piece of land is needed. To accommodate for the larger airplanes, this strip needs to have
length at least L.
Over the years, the inhabitants of Lineland have become very proficient in flattening
pieces of land. Given a piece a land, they can remove rock quickly. They dont want to
add rock for that may lead to an unstable landing strip. To minimize the amount of effort,
however, they want to remove the least amount of rock necessary to reach their goal: a flat
piece of land of length L. What is this minimum amount? Because of the low-dimensional
nature of Lineland, the amount of rock that needs to be removed is measured as the total
area of land above the place where the landing strip is placed, rather than the volume (so in
the Figure below, the amount of land removed is given by the lightly shaded area).
Input
One line with a positive number: the number of test cases (at most 25). Then for each test
case:
One line with an integer N, 2 N 500, the number of points, and an integer L,
1 L 10 000, the necessary length to flatten.
N lines with two integers xi and yi with 0 xi, yi 10 000 describing the landscape
of Lineland. The xi are in (strictly) ascending order. At position xi the height of the
landscape is yi. Between two xi the landscape has constant slope. (So the landscape is
piecewise linear). The difference between xN and x1 is greater than or equal to L.
Output
For each test case, output one line with the minimum amount of rock which must be removed
in order to build the airport. The answer should be given as a floating point number
with an absolute error of at most 103.
Sample input
4
35
02
42
14 0
43
02
20
40
53
3 10
10 2
30 2
35 7
2 777
222 333
4444 5555
Sample output
0.9000
0.3750
0.0000
373362.4867
I just bought Leonardos secret notebook! Rare object collector Stan Ucker was really agitated
but his friend, special investigator Sarah Kepticwas unimpressed.
How do you know it is genuine?
Oh, it must be, at that price. And it is written in the da Vinci code.
Sarah browsed a few of the pages. It was obvious to her that the code was a substitution cipher, where
each letter of the alphabet had been substituted by another letter.
Leonardo would have written the plain-text and left it to his assistant to encrypt, she said. And he
must have supplied the substitution alphabet to be used. If we are lucky, we can find it on the back
cover!
She turned up the last page and, lo and behold, there was a single line of all 26 letters of the
alphabet:
QWERTYUIOPASDFGHJKLZXCVBNM
This may be Leonardos instructions meaning that each A in the plain-text was to be
replaced by Q, each B withW, etcetera. Let us see...
To their disappointment, they soon saw that this could not be the substitution that was used
in the book. Suddenly, Stan brightened.
Maybe Leonardo really wrote the substitution alphabet on the last page, and by mistake
his assistant coded that line as he had coded the rest of the book. So the line we have here is
the result of applying some permutation TWICE to the ordinary alphabet!
Sarah took out her laptop computer and coded fiercely for a few minutes. Then she turned
to Stan with a sympathetic expression.
No, that couldnt be it. I am afraid that you have been duped again, my friend. In all
probability, the book is a fake.
Write a program that takes a permutation of the English alphabet as input and decides if it
may be the result of performing some permutation twice.
Input
The input begins with a positive number on a line of its own telling the number of test cases
(at most 500). Then for each test case there is one line containing a permutation of the 26
capital letters of the English alphabet.
Output
For each test case, output one line containing Yes if the given permutation can result from
applying some permutation twice on the original alphabet string ABC...XYZ, otherwise output
No.
Sample input
2
QWERTYUIOPASDFGHJKLZXCVBNM
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Sample output
No
Yes
118.Problem: Shoot-out
This is back in the Wild West where everybody is fighting everybody. In particular, there are n cowboys, each with
a revolver. These are rather civilized cowboys, so they have decided to take turns firing their guns until only one is
left standing. Each of them has a given probability of hitting his target, and they all know each others probability.
Furthermore, they are geniuses and always know which person to aim at in order to maximize their winning
chance, so they are indeed peculiar cowboys. If there are several equally good targets, one of those will be
chosen at random. Note that a cowboys code of ethics forces him to do his best at killing one of his opponents,
even if intentionally missing would have increased his odds (yes, this can happen!)
Input specifications
On the first line of the input is a single positive integer t, telling the number of test cases
to follow. Each case consists of one line with an integer 2 <= n <= 13 giving the number
of cowboys, followed by n positive integers giving hit percentages for the cowboys in
the order of their turns.
Output specifications
For each test case, output one line with the percent probabilities for each of them
surviving, in the same order as the input. The numbers should be separated by a
space and be correctly rounded to two decimal places.
Sample input
5
2 1 100
3 100 99 98
3 50 99 100
3 50 99 99
3 50 99 98
Input specifications
A number of test cases consisting of: A line with an integer 1 <= n <= 8, the number of
people on the tour. A line with an floating point number 1 < v <= 100, your maximum
speed (you start in the bus at the origin). Then follow n lines, each containing four
floating point numbers xi yi vi ai, the starting coordinates (106 <= xi, yi <= 106), speed
(1 <= vi < 100) and direction (0 <=ai < 2) of each of the tour guests.
The input is terminated by a case with n = 0, which should not be processed. All
floating point numbers in the input will be written in standard decimal notation, and
have no more than 10 digits.
Output specifications
For each test case, print a line with the time it takes before everybody is back in the bus
(the origin). Round the answer to the nearest integer. The answer will never be larger
than 106.
Sample input
1
50.0
125.0 175.0 25.0 1.96
3
100.0
40.0 25.0 20.0 5.95
-185.0 195.0 6.0 2.35
30.0 -80.0 23.0 2.76
0
You are the CEO of Nasty Hacks Inc., a company that creates small pieces of malicious software which teenagers
may use to fool their friends. The company has just finished their first product and it is time to sell it. You want to
make as much money as possible and consider advertising in order to increase sales. You get an analyst to
predict the expected revenue, both with and without advertising. You now want to make a decision as to whether
you should advertise or not, given the expected revenues.
Input specifications
The input consists of n cases, and the first line consists of one positive integer giving n.
The next n lines each contain 3 integers, r, e and c. The first, r, is the expected revenue
if you do not advertise, the second, e, is the expected revenue if you do advertise, and
the third, c, is the cost of advertising. You can assume that the input will follow these
restrictions: 106 <= r, e <= 106 and 0 <= c <= 106.
Output specifications
Output one line for each test case: advertise, do not advertise or does not matter,
presenting whether it is most profitable to advertise or not, or whether it does not make
any difference.
Sample input
3
0 100 70
100 130 30
-100 -70 40
121.Problem: Jezzball
JezzBall is a computer game in which red-and-white atoms bounce about a rectangular field of play. The player
advances to later levels (with correspondingly higher numbers of atoms and lives)
by containing the atoms in progressively smaller spaces, until at least 75% of the
area is blocked off. (wikipedia.org) The picture to the right is a screenshot
from the original game, where the player has already covered some space
(the black part). In this problem we will consider a slightly different, non-discrete,
version of the game. That is, while the length unit is still pixels, you should treat them as non-discrete in the sense
that all objects can be at non-integer coordinates and all movements are continuous.
The size of the playing field will be 1024 768 pixels. The atoms that bounce
around will be infinitely thin (and not round balls like in the screenshot). The atoms
will move at a constant speed and only change direction when hitting the edge of the
playing field (x-coordinate 0 and 1024 or y-coordinate 0 and 768), where they bounce
without loss of energy. The atoms do not hit each other.
The player can divide the playing field in two by shooting a horizontal or vertical
ray from (in this problem) a fixed point on the playing field. The ray will then extend
in both directions simultaneously (up and down for vertical rays, or left and right for
horizontal rays) at a uniform speed (in this problem always 200 pixels per second). The
rays will also be infinitely thin. If no atom touches any part of the ray while its still
being extended, the field has sucessfully been divided. Otherwise the player loses a
life.
If an atom touches the endpoint of an extending edge, this will not be counted as a
hit. Also, if an atom hits the ray at the same instant it has finished extending, this will
also not count as a hit. Write a program that determines the minimum time the player
must wait before he can start extending a ray so that an atom will not hit it before the
ray has been completed.
Input specifications
Each test case starts with a line containing a single integer n, the number of atoms
(1 <= n <= 10). Then follows a line containing two integers, x and y, the position where
the two ray ends will start extending from (0 < x < 1024, 0 < y < 768). Then n lines
follow, each containing four integers, x, y, vx and vy describing the initial position and
speed of an atom (0 < x < 1024, 0 < y < 768, 1 <= |vx| <= 200, 1 <= |vy| <= 200). The
speed of the atom in the x direction is given by vx, and the speed in the y direction is
given by vy. All positions in each input will be distinct. The input is terminated by a
case where n = 0, which should not be processed. There will be at most 25 test cases.
Output specifications
For each test case, output the minimum time (with exactly 5 decimal digits) until the
player can extend either a horizontal or vertical ray without an atom colliding with it
while it is being drawn. The input will be constructed so that the first time this occurs
will be during an open interval at least 105 seconds long. If no such interval is found
during the first 10000 seconds, output Never (without quotes).
Sample input
3
700 420
360 290 170 44
900 150 -53 20
890 100 130 -100
4
10 10
1 1 192 144
513 385 192 144
1023 767 -192 -144
511 383 -192 -144
0
The magician shuffles a small pack of cards, holds it face down and performs the following procedure:
1. The top card is moved to the bottom of the pack. The new top card is dealt face up onto the table. It is the Ace
of Spades.
2. Two cards are moved one at a time from the top to the bottom. The next card is dealt face up onto the table. It
is the Two of Spades.
3. Three cards are moved one at a time . . .
4. This goes on until the nth and last card turns out to be the n of Spades.
This impressive trick works if the magician knows how to arrange the cards
beforehand (and knows how to give a false shuffle). Your program has to determine
the initial order of the cards for a given number of cards, 1 <= n <= 13.
Input specifications
On the first line of the input is a single positive integer, telling the number of test cases
to follow. Each case consists of one line containing the integer n.
Output specifications
For each test case, output a line with the correct permutation of the values 1 to n, space
separated. The first number showing the top card of the pack, etc . . .
Sample input
2
4
5
Output for sample input
2143
31452
Long before the days of international trade treaties, a salesman would need to pay taxes at every
border crossed. So your task is to find the minimum number of borders that need to be crossed
when traveling between two countries. We model the surface of Earth as a set of polygons in three dimensions
forming a closed convex 3D shape, where each polygon corresponds to one country. You are
not allowed to cross at points where more than two countries meet.
Input specifications
Each test case consists of a line containing c, the number of countries (4 <= c <= 6000),
followed by c lines containing the integers n x1 y1 z1 . . . xn yn zn, describing (in order)
the n corners of a closed polygon (3 <= n <= 20). Then follows a line with one integer
m (0 < m <= 50), and then m lines with queries ca cb, where ca and cb are country
numbers (starting with 1). No point will be on the line between two connected points,
and 106 <=x, y, z <= 106 for all points. No two non-adjacent edges of a country share
a common point. The input is terminated by a case where c = 0, which should not be
processed.
Output specifications
For each query, output the number of borders you must cross to go from ca to cb.
Sample input
6
4000001011010
4100101111110
4000100101001
4010110111011
4000010110100
4001011111101
2
12
13
0
Output for sample input
2
1
124.Problem: Whac-a-Mole
While visiting a traveling fun fair you suddenly have an urge to break the high
score in the Whac-a-Mole game. The goal of the Whac-a-Mole game is to... well...
whack moles. With a hammer. To make the job easier you have first consulted
the fortune teller and now you know the exact appearance patterns of the moles.
The moles appear out of holes occupying the n2 integer points (x, y) satisfying
0 <= x, y < n in a two-dimensional coordinate system. At each time step, some
moles will appear and then disappear
again before the next time step. After the moles appear but before they disappear, you
are able to move your hammer in a straight line to any position (x2, y2) that is at distance
at most d from your current position (x1, y1). For simplicity, we assume that you
can only move your hammer to a point having integer coordinates. A mole is whacked
if the center of the hole it appears out of is located on the line between (x1, y1) and
(x2, y2) (including the two endpoints). Every mole whacked earns you a point. When
the game starts, before the first time step, you are able to place your hammer anywhere
you see fit.
Input specifications
The input consists of several test cases. Each test case starts with a line containing three
integers n, d and m, where n and d are as described above, and m is the total number
of moles that will appear (1 <= n <= 20, 1 <= d <= 5, and 1 <= m <= 1000). Then follow
m lines, each containing three integers x, y and t giving the position and time of the
appearance of a mole (0 <= x, y < n and 1 <= t <= 10). No two moles will appear at the
same place at the same time.
The input is ended with a test case where n = d = m = 0. This case should not be
processed.
Output specifications
For each test case output a single line containing a single integer, the maximum
possible score achievable.
Sample input
426
001
313
012
022
102
202
543
001
121
241
000
Output for sample input
4
2
125.Problem H: RandomWalking
The Army of Coin-tossing Monkeys (ACM) is in the business of producing randomness. Good random
numbers are important for many applications, such as cryptography, online gambling, randomized algorithms
and panic attempts at solutions in the last few seconds of programming competitions.
Recently, one of the best monkeys has had to retire. However, before he left, he invented a new,
cheaper way to generate randomness compared to
directly using the randomness generated by coin-tossing monkeys. The method starts
by taking an undirected graph with 2n nodes labelled 0, 1, . . . , 2n 1. To generate k
random n-bit numbers, they will let the monkeys toss n coins to decide where on the
graph to start. This node number is the first number output. The monkeys will then
pick a random edge from this node, and jump to the node that this edge connects to.
This new node will be the second random number output. They will then select a
random edge from this node (possibly back to the node they arrived from in the last
step), follow it and output the number of the node they landed on. This walk will
continue until k numbers have been output.
During experiments, the ACM has noticed that different graphs give different
output distributions, some of them not very random. So, they have asked for your
help testing the graphs to see if the randomness is of good enough quality to sell.
They consider a graph good if, for each of the n bits in each of the k numbers
generated, the probability that this bit is output as 1 is greater than 25% and smaller
than 75%.
Input specifications
The input will consist of several data sets. Each set will start with a line consisting
of three numbers k, n, e separated by single spaces, where k is the number of n-bit
numbers to be generated and e is the number of edges in the graph (1 <= k <= 100,
1 <= n <= 10 and 1 <= e <= 2000). The next e lines will consist of two space-separated
integers v1, v2 where 0 <= v1, v2 < 2n and v1 v2. Edges are undirected and each
node is guaranteed to have at least one edge. There may be multiple edges between
the same pair of nodes.
The last test case will be followed by a line with k = n = e = 0, which should not
be processed.
Output specifications
For each input case, output a single line consisting of the word Yes if the graph is good,
and No otherwise.
Sample input
10 2 3
03
13
23
524
01
03
12
23
000
Output for sample input
No
Yes
126.Problem: HoneycombWalk
A bee larva living in a hexagonal cell of a large honeycomb decides to creep for a walk. In each step the larva
may move into any of the six adjacent cells and after n steps, it is to end up in its original cell.
Your program has to compute, for a given n, the number of different such larva walks.
Input specifications
The first line contains an integer giving the number of test cases to follow. Each case
consists of one line containing an integer n, where 1 <= n <= 14.
Output specifications
For each test case, output one line containing the number of walks. Under the
assumption 1 <= n <= 14, the answer will be less than 231.
Sample input
2
2
4
Output for sample input
6
90
Sample Output
2
3
536
ababccd
2
42
ababcd
7
4
Sample Output
3
25
0
01000
00010
46
1
011000
001011
011110
011100
22
0
01
10
7
10
-1
Output
For each test case, write in one line YES if it is possible to construct a schedule to satisfy all the given relations
among the given tasks, NO otherwise.
Sample Input
Sample Output
2
22
1 2 -2
121
21
1 2 -1
NO
YES
Sample Output
2
23
AGG
CGT
(0,1)
55
ACGTG
ACATG
CTATG
ATATG
GTATT
((0,1),(2,(3,4))
)
2
5
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the first line contains a single positive integer n (n 1000) the size of the grid. The i th line of
the following n lines contains n character Cij (i = 1, 2, ..., n; j = 1, 2, ..., n) specifying color pattern of the grid.
Character Cij is B or W indicating that the color of cell (i, j) is black or white respectively.
Output
For each data set, write in one line YES if given grid is white-colorable or NO otherwise.
Sample Input
Sample Output
2
3
WWW
WBB
WBB
3
BWB
BWW
WWB
NO
YES
Sample Input
Sample Output
2
4
-1 1 2
043
532
1 -1 2
2
010
021
3
002
113
2 10 2
2
111
020
5
5
Decimal number
Decimal number
-4
-5
-3
-2
Given m, n and k (1 k min{n m + 1, 2 147 473 547}), your task is to write a program to find a number
corresponding to k-th representation in the sorted sequence.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the only line contains 3 integers m, n and k separated by space.
Output
For each data set, write in one line the k-th number of the sorted numbers.
Sample Input
Sample Output
2
053
-5 -2 2
2
-5
134.Problem: Domino
A set of double-six dominoes with 28 tiles is the most popular size of dominoes set. In a double-six domino set,
the numbers on the tiles range from 0 (or blank) to 6. In a double-six set, there are seven suits (0 or blank, 1, 2, 3,
4, 5, 6), each with seven members.
The game can be started with any tile. Until the first double played, the game layout has only 2 end opens. After
the first double played (which is called spinner), the game can be played on two additional edges (the game layout
has 4 open ends now). All subsequent doubles can only played as other tiles except that its value is counted
twice when calculating the score of the game layout.
In one play turn, a tile can be added to an open end if the number of points in the added head of the tile matches
the number of points in this open end.
The Domino game usually is played by at least 2 persons. Lets consider a game played by just a single person.
The object of the game is to create as much as possible situations where the open ends of the game layout added
up to a multiple of five (5, 10, 15, 20, etc.). The score at each play turn is the total sum of open ends when they
added up to a multiple of five. This score is added up to the current score of the game.
In this case, the game is quite simple. At first, a sequence of 28 tiles in random order is given. Then the tiles are
taken from the sequence one by one. For each tile, the player might add it into the game layout or leave it out.
Your task is to write a program to play the game in order to obtain the highest total score.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a
positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, a single line contains 56 numbers separated by space represents 28 tiles of the game, 2
consecutive numbers for each tile.
Output
For each data set, write in one line the highest score that can be obtained.
Sample Input
2
0136251116032405444606152345005604335534026612352213142
6
1533222406113502361355040325454426140546000134566616122
3
Sample Output
150
145
The game layout to obtain the highest score for the first data set in the sample input
You are part of a team working on the simulation of a dynamic system of particles interacting according
to classical mechanics Newtonian physics with gravitational and electromagnetic forces. Your part
of the problem solution is to bring the system into a standard orientation following the simulation based
on rotating the coordinate system (or, if you like, you can think of it as rotating all of the particles).
In the final coordinate system, the first three particles are to lie in a plane parallel with the XY plane,
either on or above the XY plane. In addition, the first particle is to lie in the YZ plane with a nonnegative Y coordinate. If the first three points do not define a plane (that is, they either are not distinct
or are collinear), print an error message and go to the next problem.
Subscripting the first particle as subscript 0, the second as 1, and the third as 2, these conditions are
summarized thus:
z0 = z1 = z2 > 0
x0 = 0; y0 > 0
note that you may have y0 = 0
Only the coordinate system rotates; the particles retain their positions with respect to each other. If
youre thinking of this as a rotation of the particles, it is to be a rigid-body rotation with respect to the
origin of the coordinate system.
Input data specification
Sets of problem specifications:
(1) Number of particles in the complete system, followed by descriptive textual information (to the end
of the line) that needs to be retained for output, preserving any leading blanks and/or tabs.
(2) The required number of triples of numbers, giving the x, y, and z coordinates as white-space
delimited numbers (they may be on the same line or on successive lines), without any descriptive
text or commas to discard.
(3) A blank line separating problems.
The input data set ends when a system of fewer than three particles is specified. (It will in fact be zero.)
This trailer record will terminate with an end-of-line before the end-of-file.
Output data specification
For each valid problem specification, list on separate lines
(1) Number of particles in the complete system, followed by the descriptive textual information from the
input file, reproducing exactly the spacing of the input.
(2) The required number of triples of numbers, giving the x, y, and z coordinates, separated by a single
blank and with only three digits to the right of the decimal point. Note that you may report a value of
-0.000 in case the value is small and negative.
(3) A blank line. This includes a blank line at the end of the file.
For an invalid problem specification, print the following message:
Illegal data: points do not define a plane
followed by a blank line.
Sample input:
6 octahedral symmetry obscured by rotation
0.500000 0.500000 -0.707107
-0.146447 0.853553 0.500000
-0.853553 0.146447 -0.500000
-0.500000 -0.500000 0.707107
0.146447 -0.853553 -0.500000
0.853553 -0.146447 0.500000
3 Duplicate point test
1
2
3
123
5
3
1
4 null operation test
0 0 3
0 -3 3
2 3 3
-1 -2 -3
0 termination record
Matching output:
6 octahedral symmetry obscured by rotation
0.000 0.816 0.577
0.707 -0.408 0.577
-0.707 -0.408 0.577
-0.000 -0.816 -0.577
-0.707 0.408 -0.577
0.707 0.408 -0.577
Illegal data: points do not define a plane
4 null operation test
0.000 0.000 3.000
0.000 -3.000 3.000
2.000 3.000 3.000
-1.000 -2.000 -3.000
136.Problem: SpinLock
Output
The output file should print the final positions of each spinner puzzles wheels. Provide the output
header Spinlock Results on the first line. Each puzzle follows on a separate line, formatted as below:
Sample Output:
Spinlock Results
3348
36976919
The output begins with a case number (starting at one) followed by a line stating how many man-hours are
required. Print a blank line after every output case (this means the output will have two newlines at the end
before the end-of-file.) Sample output follows.
Sample Output:
Case #1:
4 street blocks need to be painted.
Case #2:
4 street blocks need to be painted.
21
12
12
Sample Output
Data Set 1, Best average difference: 0.000000
Best Pairing 1
Supervisor 1 with Employee 1
Supervisor 2 with Employee 2
Supervisor 3 with Employee 3
Supervisor 4 with Employee 4
Supervisor 5 with Employee 5
Supervisor 6 with Employee 6
Supervisor 7 with Employee 7
Data Set 2, Best average difference: 0.250000
Best Pairing 1
Supervisor 1 with Employee 1
Supervisor 2 with Employee 2
Mom and dad have a problem: their child John never puts his toys away when he is finished playing
with them. They gave John a rectangular box to put his toys in. Unfortunately, John is rebellious and
obeys his parents by simply throwing his toys into the box. All the toys get mixed up, and it is
impossible for John to find his favorite toys anymore.
John's parents came up with the following idea. They put cardboard partitions into the box. Even if John
keeps throwing his toys into the box, at least toys that get thrown into different partitions stay separate.
The box looks like this from the top:
Problem
For each i > 0 such that there exists a partition with i toys, determine how many partitions have i toys.
Provide a list of the values of i and their count of associated partitions.
Input
The input consists of a number of cases. The first line consists of six integers n m x1 y1 x2 y2. The
number of cardboards to form the partitions is n (0 < n <= 1000) and the number of toys is given in m (0
< m <= 1000). The coordinates of the upper-left corner and the lower-right corner of the box are (x1,y1)
and (x2,y2), respectively. The following n lines each consists of two integers Ui Li, indicating that the
ends of the i-th cardboard is at the coordinates (Ui,y1) and (Li,y2). You may assume that the
cardboards do not intersect with each other. The next m lines each consists of two integers Xi Yi
specifying where the i-th toy has landed in the box. You may assume that no toy will land on a
cardboard or on the boundary of the box.
The input is terminated by a line consisting of a single 0. Each line of input in the file is
terminated by the end of line character (\n).
Output
For each box, first provide a header stating Box on a line of its own. After that, there will be one line
of output per count (i > 0) of toys in a partition. The value i will be followed by a colon and a space,
followed the number of partitions containing i toys. Output will be sorted in ascending order of i for
each box.
Sample Input
4 10 0 10 100 0
20 20
80 80
60 60
40 40
59
15 9
95 9
25 9
65 9
75 9
35 9
45 9
55 9
85 9
5 6 0 10 60 0
43
15 30
31
68
10 10
21
28
15
55
40 9
79
0
Sample Output
Box
2: 5
Box
1: 4
2: 1
The output is to be identical to the input except for this filtering, including reproducing the spacing.
Input
The input text is terminated by the end-of-file, which may or may not be preceded by an end-of-line. Note that you
are reproducing the input text exactly except for filtering out the use of l for 1 and the use of O for 0.
Warning: use the specified context rule as stated above, not what you would have chosen as the transformation
rules. For instance, this will not handle exponential notation correctly or arithmetic expressions without embedded
blanks.
Example Input:
l23.O5 liters water
Use distilled or at least deionized
ll.OOl ml O-negative blood
Note: negative on ALL Rh factors
l3.2Ol ml O-positive blood
Use procedure OOO.OOl2.l234
Example Output:
123.05 liters water
Use distilled or at least deionized
11.001 ml O-negative blood
Note: negative on ALL Rh factors
13.201 ml O-positive blood
Use procedure OOO.OOl2.l234
32
Output:
The output should indicate for each m,s, exactly how many s-digit positive palindromes are divisible by m, with
one problem instance per line.
Sample input and output appear on the next page.
SAMPLE Input
5
31
25 3
12 4
30 3
81 6
SAMPLE Output
3
2
7
0
0
Explanation. There are three positive 1-digit multiples of 3, namely, 3, 6, and 9; all 1-digit numbers are trivially
palindromes. Among the 3-digit palindromes, 525 and 575 are multiples of 25. The 4-digit multiples of 12 that are
palindromes are 2112, 2772, 4224, 4884, 6336, 6996, 8448. There are no positive palindromic numbers ending
in 0 (since we do not allow leading 0's). No 6-digit palindromes are divisible by 81.
2
4
1 R 55
2 R 55
2 U 55
1 U 55
8
1 R 55
2 R 55
1 R 70
1 U 55
2 U 80
3 R 70
3 U 80
3 U 70
Output
Your output will list each history and whether it requires investigation, as seen below. There are four spaces
between the colon and the result for each history.
SAMPLE Output
History #1: Needs Investigation
History #2: OK
Note: in the case of History #2 in the example above, the valid serial history would be to perform Transaction #2
first, followed by Transaction #1, followed by Transaction #3.
145.Problem: CMDB
Swamp County College is embarking on an effort to improve the management of the Colleges data center. The
college is adopting the ITIL (Information Technology Information Library) model for IT service management.
Originally developed by the British Government, ITIL covers a wide spectrum of IT service, application, and
infrastructure management best practices. ITIL is now being adopted widely in both the public and private sectors
worldwide.
The college IT department has determined that it needs to improve its understanding of the infrastructure within
the data center. In accordance with the ITIL model, the IT managers want to build a Configuration Management
Data Base (a CMDB) that contains information about the equipment in the data center, the connections between
that equipment, and the databases and software applications that run on the equipment. The objective is to be
able to identify the potential impact of downtime or maintenance of one infrastructure component on the
databases and applications supported by the infrastructure.
Building a full CMDB is a major undertaking. In order to get some value out of the process quickly, and gain
executive support and funding for the full project, the college is asking your team to develop a proof-of-concept
database and tool that will demonstrate the basic functions of a CMDB and help them when planning upgrades to
their critical infrastructure.
This proof-of-concept database will handle the following infrastructure components and the relationships between
them:
Storage Arrays
Storage (Fibre Channel) Switches
Network (IP) Switches
Servers
Databases
Applications
Each of these infrastructure components is referred to by ITIL as a configuration item (CI). The database will
contain a type definition of each CI and a list of relationships between them. Each CI will be defined as one of the
above types (storage array, storage switch, network switch, server, database, or application). CI names are
strings of between 1 and 31 upper case letters and digits, with the first character being a letter. No two CIs will
have the same name.
Relationships will be defined as connections or usage relationships between CIs; for example, a storage array
connects to a storage switch, a server connects to a network switch, a server may connect to a storage switch, an
application runs on a server, an application may use a database, an application may use another application, and
a server may use a storage array. Databases and applications that depend on each other may reside on different
servers, communicating with each other over the IP network.
Storage switches provide connections between a server and a storage array. Every path between a server and its
external storage will pass through only one storage switch. However, connections to storage arrays may be
redundantthat is, a given server may have independent connections to multiple switches, as may a storage
array. This means that there may be multiple paths between a server and a storage array. These redundant paths
are used to provide additional
bandwidth and redundancy, so that if one storage switch fails or is taken down for maintenance, access to storage
is not interrupted.
Similarly, servers may have connections to multiple network switches, providing multiple paths for network traffic
among databases and applications. Unlike storage, there may be multiple IP switches in a path between server
network ports.
Your team is to write a program that will read CMDB entries, then use the CMDB entries to answer queries about
the impact that a single down CI would have on database and application CIs.
Input to your program will be a series of CI definitions, followed by a series of CI relationships, and ending with
a series of queries. Each definition, relationship, and query appears on a line by itself, with the fields separated
from each other by one or more spaces. No input line will exceed 80 columns.
Each CI will be defined on a line containing the string CI, the CI name, and the type:
storage-array
storage-switch
network-switch
server
database
application
Each relationship will be defined on a line containing the string RE, a CI, the type of relationship (as listed
Output
Query: PDB
Application: FINANCE
Query: S2
Database: ODB
Application: CRM
Output
Campus-Visit: R $149.04
Management-Visit: F $317.00
Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be
formatted according to the following description, and there will be no blank lines separating data sets.
A single data set has 3 components:
1. Start line - A single line:
START R C
where R and C are integers (2 (R,C) 9) indicating the number of rows and columns in the input
image described by this data set.
2. Original Image - A series of R lines, each of which contains C integers from 0 to 9 inclusive. These
integers represent the grayscale value of a pixel in the original image and will not be separated by
spaces.
3. End line - A single line:
END
After the last data set, there will be a single line:
ENDOFINPUT
Output
The output will be the anti-aliased image, which will be R - 1 rows, each with C - 1 integer pixel values.
Each pixel in the output will be generated by averaging (and rounding down) the grayscale pixel values of
the corresponding square of four pixels in the Original Image.
Sample Input
START 2 2
00
00
END
START 2 9
012345678
012345678
END
START 4 4
4440
4400
4000
0000
END
START 9 9
900000009
090000090
009000900
000909000
000090000
000909000
009000900
090000090
900000009
END
ENDOFINPUT
Sample Output
00
1234567
431
310
100
42000024
24200242
02422420
00244200
00244200
02422420
24200242
42000024
END
START 1 10
9I
2A
3B
4C
5D
6E
7F
8G
9H
AB
CDEFGHXE
ND
ENDOFINPUT
Sample Output
YES
YES
NO
Sample Input
START 5 5 5
1,1,1 2,2,2 3,3,3
4,3,0 4,4,4 3,0,2 2,1,3 3,3,3
END
START 2 3 4
1,1,10 1,1,1 0,2,2
0,0,1
END
ENDOFINPUT
Sample Output
AIEE, I got 1 fish, me!
None of dem fish blowed up!
When Boudreaux
brings a window to the foreground, all of its squares come to the top, overlapping any
squares it shares with other windows. For example, if window 1 and then window 2 were brought to the
foreground, the resulting representation would be:
. . . and so on . . .
Unfortunately, Boudreaux's computer is very unreliable and crashes often. He could easily tell if a crash
occurred by looking at the windows and seeing a graphical representation that should not occur if windows
were being brought to the foreground correctly. And this is where you come in . . .
Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be
formatted according to the following description, and there will be no blank lines separating data sets.
A single data set has 3 components:
165.Problem: OK Sudoku?
Sudoku is a popular puzzle game where one puts numbers on a grid. The grid has 9 rows
and 9 columns, and is divided into 9 blocks, each with 9 squares. In each square one of
the numbers from '1' to '9' is placed. For example, the following is an example of a
completed Sudoku grid:
123 456 789
456 789 123
789 123 456
234 567 891
567 891 234
891 234 567
345 678 912
678 912 345
912 345 678
The grid is considered valid if all of the following rules are met:
1.Each row contains the numbers from 1 to 9 (inclusive) exactly once each.
2. Each column contains the numbers from 1 to 9 (inclusive) exactly once each.
3. Each 3 by 3 block, of which there are 9, contains the numbers from 1 to 9
(inclusive) exactly once each.
Thus, the above example satisfies these rules and can be considered as valid. The grid is
considered invalid if any of the rules are broken. For example, the following is an
example of an invalid grid:
123 456 789
912 345 678
891 234 567
789 123 456
678 912 345
567 891 234
456 789 123
345 678 912
234 567 891
In this grid, the first block contains the number 1 three times, the number 2 twice, the
number 9 twice, and is missing the numbers 4, 5, 6, and 7. For these reasons, among
others, the grid is invalid. Your task is simple, to write a validity tester for Sudoku grids.
Input
Your input will consist of 11 lines of text. Lines 1 to 3, 5 to 7, and 9 to 11 each contain 3
groups of 3 integers separated by a single space. Each line is a row in a Sudoku grid, and
the 9 integers are the values in the 9 columns. Lines 4 and 8 are blank.
Output
Your output will consist of a single word. Output the word valid if the input represents
a valid Sudoku grid, otherwise output the word invalid if the input does not represent
a valid Sudoku grid.
Example Input
111 222 333
222 333 444
333 444 555
444 555 666
555 666 777
666 777 888
777 888 999
888 999 111
999 111 222
Example Output
invalid
Sample Output
SS 0 to 3: 0 1 2 3
SS 1 to 2: none
SS 3 to 0: none
SS 3 to 3: none
Note that the second shortest path from s to f in graph G is the shortest over all paths
from s to f over all graphs which are the same as G but are missing one of the edges from
the shortest path s to f in G.
and use
3 2 1
171.Problem: SumPrimes
Dr. Prime is looking for SumPrimes. SumPrimes are primes whose sum of digits is also prime. For example,
11 is a SumPrime because
1 + 1 = 2, which is prime
Your program will identify and print all the SumPrimes in a given range along with the sum of their digits.
Your program will be given one line of input containing a minimum and maximum value (inclusive) of a range to
search. Minimum and maximum have the following constraints: 2 <= minimum <= 1000, 2 <= maximum <=
1000, minimum <= maximum.
Then, in increasing order, one per line, print each SumPrime and its sum separated by a single space.
Sample Input
2 20
Sample Output
22
33
55
77
11 2
The most centrally located of the given intersections is (2, 2), with an eccentricity of 5.
The maximum size of the city grid is 100 100. The first line of the input contains the number N of intersections (2
N 50). The next N lines each contain the integer X and Y coordinates of a location, separated by a single
space (0 X 100 and 0 Y 100).
For the output, list all of the most centrally located intersections (that is, list all intersections with minimum
eccentricity). The locations must be output in ascending sorted order (sorted first by
X, then by Y).
Sample Input
9
40
01
31
61
22
34
54
45
26
Sample Output
22
scathe
echo
churl
tread
school
ecru
wrath
sharon
erect
erne
ether
sheath
shiver
acumen
hitch
hunt
luck
ketch
bleach
shunts
swathe
choose
match
math
rare
ocala
drover
tether
Sample Output
swathe--school--choose
-r---a---h---u---u---i
-a--scathe--acumen---t
-t---h---e---k---teach
there-stirs-c---s----e
--t-c-t---tahoe-mother
s-h-h-o-m-a-u---a---rhe-ocala-y-r---shiver
ecru-a--t--bleach---ca---s--c--l--c---both
t-s--h-sharon-h---a--hitch--p---c-remain--d
--a--t-a-k-k---a--t--r
e-i--rather--d-t-audio
rare-e-s-t--tether---v
n----a---c---w---i---e
etched--shuntsgather
176.Problem : Insiders
Input
There are multiple test cases in the input file. Each test case starts with three integers S, T and
M (1 S 100; 1 T 2000; 0 M 10), representing the number of schools, the number
of teams participating in the preliminary contest, and the minimum number of problems which
is required to be solved in order to enter the on-site competition, respectively.
Each of the following S lines consists of three integers Id, P and Q, (1 Id S; 0 P;Q 1),
representing the Id of the school, whether this school satisfies condition b), and whether this
school satisfies condition c).
The last part of each test case consists of T lines. There are two integers on each of the T lines,
Sid and Tot (1 Sid S; 0 Tot 10), meaning that a team from school Sid had solved Tot
problems in the preliminary contest.
Two consecutive test cases are separated by a blank line. S = 0; T = 0;M = 0 indicates the end
of input and should not be processed by your program.
Output
For each test case, print the total number of teams which are allowed to participate in the on-site
competition on a separate line in the format as indicated in the sample output.
Sample Input
586
501
400
100
311
211
26
33
29
57
48
36
28
16
586
301
511
201
111
410
57
25
45
55
33
56
20
47
000
2
Output for the Sample Input
Case 1: 10
Case 2: 9
Output
For each test case, if it is possible to balance the scale in question, output one number, the number
of different ways to balance this scale, in the format as indicated in the sample output. Rotations
and reversals of the same arrangement should be counted only once.
Sample Input
87 33 98 83 67 97 44 72 91 78 46 49 64 59 85 88
0
Output Input
Case 1: 15227223
Input
There are multiple test cases in the input file. Each test case starts with one integer N, (1
N 100), the number of star systems on the telescope. N lines follow, each line consists of
two integers: the X and Y coordinates of the Kth planet system. The absolute value of any
coordinate is no more than 109, and you can assume that the planets are arbitrarily distributed
in the universe.
N = 0 indicates the end of input file and should not be processed by your program.
Output
For each test case, output the maximum value you have found on a single line in the format as
indicated in the sample output.
Sample Input
10 2 3
92
74
34
57
15
10 4
10 6
11 4
46
0
Sample Output
Case 1: 7
0444
2334
3 1 5 10
10 0 0 0
0000
Output for the Sample Input
Case 1: 28
Case 2: -1
Explanation for Sample Input / Output
The 1st shortest path in this example is 0 -> 4, with a total travel time of 4 seconds; the 2nd
shortest path is 0 (Wait 2 seconds) -> 2 (Wait 2 seconds) -> 4, with a total travel time of 18
seconds; the 3rd shortest path is 0 (Wait 2 seconds) -> 2 (Wait 2 seconds) -> 3 -> 0 -> 4, with a
total travel time of 28 seconds.
furlongs fathoms
1 furlongs = 110 fathoms
feet inches
12 inches = 1 feet
1 fathoms = 6 feet
1 furlongs
0.5 furlongs 0.25 fathoms
Example Output
3 km 218 m 99 cm
0 km 0 m 3 cm
660 feet 0 inches
331 feet 6 inches
1
12
23
4
4
5
1
3
2
1
4
2
10
00
Example Output
1345
189.Problem: Shrew-ology
Dr. Montgomery Moreau has been observing a population of Northern Madagascar Pie-bald
Shrews in the wild for many years. He has made careful observations of all the shrews in the area,
noting their distinctive physical characteristics and naming each one.
He has made a list of significant physical characteristics (e.g., brown fur, red eyes, white feet,
prominent incisor teeth, etc.) and taken note of which if these appear to be dominant (if either
parent has this characteristic, their children will have it) or recessive (the children have this characteristic only if
both parents have it).
Unfortunately, his funding from the International Zoological Institute expired and he was
forced to leave the area for several months until he could obtain a new grant. During that time
a new generation was born and began to mature. Upon returning, Dr. Moreau hopes to resume his
work, starting by determining the likely parentage of the each member of the new generation.
Input
The first line of input will containing a sequence of 1 to 80 consecutive D and R characters
describing a list of physical characteristics, indicating whether each is dominant or recessive.
After this line will follow several lines, each describing a single adult shrew. Each shrew is
described by a name of 1-32 non-blank characters terminated by a blank space, then a single M
or F character indicating the gender of the animal, another blank space, then a list of consecutive
0 or 1 characters, describing the animal. A 1 indicates that the animal possesses that physical
characteristic, a 0 indicates that it does not. The list of adults is terminated by a line containing
only the string ***.
This is followed by one or more lines describing juvenile animals. These contain a name and
description, each formatted identically to those for the adults, separated by a blank space. The list
of juveniles is terminated by a line containing only the string ***.
Output
For each juvenile animal, print a single line consisting of the animals name, the string by , then
a (possibly empty) list of all possible parents for that animal. A set of parents should be printed
as the name of the mother, a hyphen, then the name of the father. If the animal has multiple pairs
of possible parents, these pairs should be printed in alphabetic (lexicographic) order first by the
mothers name, then by the fathers name among pairs where the mother is the same. Each pair
should be printed separated by the string or .
Example Input
RDDR
Speedy M 0101
Jumper F 0101
Slowpoke M 1101
Terror F 1100
Shadow F 1001
***
Frisky 0101
Sleepy 1101
***
Example Output
Frisky by Jumper-Slowpoke or Jumper-Speedy or Shadow-Speedy
Sleepy by Shadow-Slowpoke
The resulting ASCII characters for all pixels are printed top-to-bottom and left-to-right to get a visual
representation of the drawing.
Input
The first line of the input file contains integers n, w, and h (3 n 100, 1 w; h 100) number
of vertices in the polygon, width and height of the canvas respectively. The following n lines contain
coordinates of the polygon vertices in clockwise order. Point i is described by two integers xi and yi
(0 xi w, 0 yi h).
Output
Write to the output file h lines with w ASCII characters each that represent ASCII art drawing of the
given polygon.
Sample input
687
76
10
17
55
24
23
Sample output
.$+.....
.##$+...
.#$oo+..
.#+$o...
.##o....
.#o.....
.o......
Sample Output
35
1 usa
70 cis
71 cis
72 cis
76 rsv
77 spec
78 spec
790 cis
7910 cis
7911 cis
7912 cis
7913 cis
7914 cis
7915 cis
7916 cis
7917 cis
7918 cis
7919 cell
7920 cell
7921 cell
7922 cis
7923 cis
7924 cis
7925 cis
7926 cis
7927 cis
7928 rsv
7929 rsv
793 cis
794 cis
795 cis
796 cis
797 cis
798 cis
799 cis
Input
The first line of the input file contains integer numbers r and n (1 r 100, 0 n 30), where r is
the radius of the flying saucer, and n is the number of skyscrapers. The next line contains four integer
numbers xA, yA, xB, and yB (-1000 xA, yA, xB, yB 1000), where (xA; yA) are the coordinates of
the starting point of the flying saucers mission and (xB; yB) are the coordinates of its finishing point.
The following n lines describe skyscrapers. Each skyscraper is represented by four integer numbers x1,
y1, x2, and y2 (-1000 x1, y1, x2, y2 1000, x1 < x2, y1 < y2) coordinates of the corners of the
corresponding rectangle.
Skyscrapers neither intersect nor touch each other. Starting and finishing points of the flying saucers
mission are valid locations for flying saucer, that is, it does not intersect any skyscraper in those points,
but may touch some of them.
Output
Write to the output file text no solution (without quotes) if the flying saucer cannot reach its finishing
point from the starting one. Otherwise, write to the output file a single number the shortest distance
that the flying saucer needs to travel to get from the starting point to the finishing point. Answer has to
be precise to at least 6 digits after the decimal point.
Sample input
13
2771
3264
7598
1859
24
0056
8 3 10 6
5 9 9 10
1428
3153
12
0 5 10 5
2245
6588
Sample output
10.570796
11.652892
no solution
194.Problem: Exchange
You are taking part in a large project to automate operations for Northeastern Exchange of Resources
and Commodities (NEERC). Different resources and commodities are traded on this exchange via public auction.
Each resource or commodity is traded independently of the others and your task is to write a core engine for this
exchange its order book. There is a separate instance of an order book for each traded resource or commodity
and it is not your problem to get the correct orders into order books.
The order book instance you will be writing is going to receive the appropriate orders from the rest of
exchange system.
Order book receives a stream of messages. Messages are orders and requests to cancel previously issued
orders. Orders that were not cancelled are called active. There are orders to buy and orders to sell. Each order to
buy or to sell has a positive size and a positive price. Order book maintains a list of active orders and generates
quotes and trades. Active order to buy at the highest price is the best buy order and its price is called bid price.
Active order to sell at the lowest price is the best sell order and its price is called ask price. Ask price is always
lower than bid price, that is, buyers are willing to pay less than sellers want to receive in return.
A current quote from the order book contains current bid size, bid price, ask size, and ask price. Here
bid and ask sizes are sums of the the sizes of all active orders with the current bid price and the current
ask price correspondingly.
A trade records information about transaction between buyer and seller. Each trade has size and price.
If an order to buy arrives to the order book at a price greater or equal to the current ask price, then the
corresponding orders are matched and trade happens buyer and seller reached agreement on a price.
Vice versa, if an order to sell arrives to the order book at a price less or equal to the current bid price,
then trade happens, too. For the purpose of order matching, order book works like a FIFO queue for
orders with the same price (read further for details).
When an order to buy arrives to the order book at a price greater or equal to the current ask price it is
not immediately entered into the order book. First, a number of trades is generated, possibly reducing
the size of incoming order. Trade is generated between incoming buy order and the best order to sell.
If there are multiple best orders (at the ask price), then the order that entered the order book first is
chosen. Trade is generated at the current ask price with the size of the trade being equal to the smaller
of the sizes of two matching orders. Sizes of both matching orders are reduced by the size of the trade.
If that reduces the size of sell order to zero, then it becomes inactive and is removed from the order
book. If the size of incoming buy order becomes zero, then the process is over incoming order becomes
inactive. If the size of incoming buy order is still positive and there is another sell order to match with, then the
process continues generating further trades at the new ask price (ask price can increase as sell orders are traded
against and become inactive). If there is no sell order to match with (current ask price became greater than
incoming buy order price), then incoming buy order is added to the order book with its remaining size.
For incoming sell order everything works similarly it is matched with buy orders from the order book
and trades are generated on bid price.
On incoming cancel request the corresponding order is simply removed from the order book and becomes
inactive. Note, that by the time of the cancel request the quantity of the corresponding order might have been
already partially reduced or the order might have become inactive. Requests to cancel inactive order do not
change anything in the order book.
On every incoming message the order book has to generate all trades it causes and the current quote
(bid size, bid price, ask size, ask price) after processing of the corresponding message, even when nothing has
changed in the order book as a result of this message. Thus, the number of quotes the order book generates is
always equal to the number of incoming messages.
Input
The first line of the input file contains a single integer number n (1 n 10 000) the number of
incoming messages that the order book has to process. The following n lines contain messages. Each line starts
with a word describing the message type BUY, SELL, or CANCEL followed after a space by the message
parameters.
BUY and SELL denote an order to buy or to sell correspondingly, and are followed by two integers q and p (1 q
99 999, 1 p 99 999) order size and price. CANCEL denotes a request to cancel previously issued order. It
is followed by a single integer i which is the number of the message with some preceding order to buy or to sell
(messages are numbered from 1 to n).
Output
Write to the output file a stream of quotes and trades that the incoming messages generate. For every
trade write TRADE followed after space by the trade size and price. For every quote write QUOTE followed after
space by the quote bid size, bid price, minus sign (-), ask size, ask price (all separated by spaces).
There is a special case when there are no active orders to buy or to sell in the order book (bid and/or ask are not
defined). This case is treated as follows. If there is no active order to buy, then it is assumed that bid size is zero
and bid price is zero. If there is no active order to sell, then it is assumed that ask size is zero and ask price is 99
999. Note, that zero is not a legal price, but 99 999 is a legal price. Recipient of quote messages distinguishes
actual 99 999 ask price from the special case of absent orders to sell by looking at its ask size.
See example for further clarification.
Sample input
11
BUY 100 35
CANCEL 1
BUY 100 34
SELL 150 36
SELL 300 37
SELL 100 36
BUY 100 38
CANCEL 4
CANCEL 7
BUY 200 32
SELL 500 30
Sample output
QUOTE 100 35 - 0 99999
QUOTE 0 0 - 0 99999
QUOTE 100 34 - 0 99999
QUOTE 100 34 - 150 36
QUOTE 100 34 - 150 36
QUOTE 100 34 - 250 36
TRADE 100 36
QUOTE 100 34 - 150 36
QUOTE 100 34 - 100 36
QUOTE 100 34 - 100 36
QUOTE 100 34 - 100 36
TRADE 100 34
TRADE 200 32
QUOTE 0 0 - 200 30
45C
AS 6S 7S 8S
9S TS JS QS KS
32C
6H JS JD
AD 6C
Sample output
SECOND
FIRST
SECOND
FIRST
196.Problem: Graveyard
Programming contests became so popular in the year 2397 that the governor of New Earck the largest humaninhabited planet of the galaxy opened a special Alley of Contestant Memories (ACM) at the local graveyard.
The ACM encircles a green park, and holds the holographic statues of famous contestants placed equidistantly
along the park perimeter. The alley has to be renewed from time to time when a new group of memorials arrives.
When new memorials are added, the exact place for each can be selected arbitrarily along the ACM, but the
equidistant disposition must be maintained by moving some of the old statues along the alley.
Surprisingly, humans are still quite superstitious in 24th century: the graveyard keepers believe the
holograms are holding dead people souls, and thus always try to renew the ACM with minimal possible
movements of existing statues (besides, the holographic equipment is very heavy). Statues are moved
along the park perimeter. Your work is to find a renewal plan which minimizes the sum of travel distances of all
statues. Installation of a new hologram adds no distance penalty, so choose the places for newcomers wisely!
Input
Input file contains two integer numbers: n the number of holographic statues initially located at the
ACM, and m the number of statues to be added (2 n 1000; 1 m 1000). The length of the
alley along the park perimeter is exactly 10 000 feet.
Output
Write a single real number to the output file the minimal sum of travel distances of all statues (in
feet). The answer must be precise to at least 4 digits after decimal point.
Sample input
21
23
31
10 10
Sample output
1666.6667
1000.0
1666.6667
0.0
Pictures show the first three examples. Marked circles denote original statues, empty circles denote new
equidistant places, arrows denote movement plans for existing statues.
In the example on the picture the hardest team consists of people 1, 2, 4, and 5. Among 4 of them 5
pairs work poorly in the same team, thus hardness factor is equal to 5/ 4 . If we add person number 3 to
the team then hardness factor decreases to 6/ 5 .
Input
The first line of the input file contains two integer numbers n and m (1 n 100, 0 m 1000). Here
n is a total number of people in the company (people are numbered from 1 to n), and m is the number
of pairs of people who work poorly in the same team. Next m lines describe those pairs with two integer
numbers ai and bi (1 ai; bi n, ai bi) on a line. The order of people in a pair is arbitrary and no
pair is listed twice.
Output
Write to the output file an integer number k (1 k n) the number of people in the hardest team,
followed by k lines listing people from this team in ascending order. If there are multiple teams with the
same hardness factor then write any one.
Sample input
56
15
54
42
25
12
31
40
Sample output
4
1
2
4
5
1
1
Note, that in the last example any team has hardness factor of zero, and any non-empty list of people is
a valid answer.
198.Problem: Interconnect
There are two serious problems in the Kingdom of Lipshire: the roads and the fools who build them.
Once upon a time, the King of Lipshire has decided to improve the road system because some roads
became completely impassable it was easier to travel cross-country instead of using those roads.
By Kings decree, new roads are to be built in Lipshire. Of course, the new road system must interconnect all
towns, i. e. there must be a path connecting any two towns of Lipshire.
The road administration of Lipshire has resources to build exactly one road per year. Unfortunately, the
fools who build these roads are completely out of control. So, regardless of the orders given, the fools
randomly select two different towns a and b and build a road between them, even when those towns are already
connected by a road. All possible choices are equiprobable. The road is build in such a manner that the only
points where a traveler can leave it are the towns connected by this road. The only good thing is that all roads are
bidirectional.
The King knows about the problem, but he cannot do anything about it. The only thing King needs to
know is the expected number of years to wait before the road system of Lipshire becomes interconnected.
He asked you to provide this information.
Input
The first line of the input contains two integers n and m (2 n 30, 0 m 1 000) the number of
towns in Lipshire, and the number of roads which are still good. The following m lines describe roads,
one per line. Each road is described with two endpoints two integer numbers ui and vi (1 ui; vi n,
ui vi). There can be multiple roads between two towns, but the road from a town to itself is not
allowed.
Output
Output the expected number of years to wait for the interconnected road system. If the system is already
interconnected, output zero as an answer. Output the number with at least six precise digits after the decimal
point.
Sample input
21
12
42
12
34
Sample output
0.0
1.5
200.Problem: Kickdown
A research laboratory of a world-leading automobile company has received an order to create a special
transmission mechanism, which allows for incredibly efficient kickdown an operation of switching to
lower gear. After several months of research engineers found that the most efficient solution requires
special gears with teeth and cavities placed non-uniformly. They calculated the optimal flanks of the
gears. Now they want to perform some experiments to prove their findings.
The first phase of the experiment is done with planar toothed sections, not round-shaped gears. A section of
length n consists of n units. The unit is either a cavity of height h or a tooth of height 2h. Two sections are
required for the experiment: one to emulate master gear (with teeth at the bottom) and one for the driven gear
(with teeth at the top).
There is a long stripe of width 3h in the laboratory and its length is enough for cutting two engaged
sections together. The sections are irregular but they may still be put together if shifted along each
other.
The stripe is made of an expensive alloy, so the engineers want to use as little of it as possible. You need to find
the minimal length of the stripe which is enough for cutting both sections simultaneously.
Input
There are two lines in the input file, each contains a string to describe a section. The first line describes
master section (teeth at the bottom) and the second line describes driven section (teeth at the top). Each
character in a string represents one section unit 1 for a cavity and 2 for a tooth. The sections can not be flipped
or rotated.
Each string is non-empty and its length does not exceed 100.
Output
Write a single integer number to the output file the minimal length of the stripe required to cut off
given sections.
Sample input
2112112112
2212112
12121212
21212121
2211221122
21212
Sample output
10
8
15