You are on page 1of 64

[Club Pemrograman Java]

Buku Latihan Algoritma

Author: Hayi Nukman

STMIK AKAKOM
Yogyakarta

July 2011

Petunjuk

An algorithm must be seen to be believed.

Buku ini terdiri dari enam bagian yang masing-masing berisi beberapa soal/case. Tugas anda adalah: Mencari minimal 3 (tiga) cara penyelesaian/algoritma yang berbeda untuk masing-masing case. Buat Program dari algoritma-algoritma tersebut (Java/C/C++). Kemudian buat catatan singkat mengenai Algoritma yang Anda Gunakan untuk menyelesaikan kasus tersebut. Post ke Blog anda, kemudian kirimkan link posting tersebut ke email: (Bila perlu disertai dengan source code program dalam bentuk Attachment). Contoh: UVA: 154 - Recycling

hayi.nkm@gmail.com

Recycling
Kerbside recycling has come to New Zealand, and every city from Auckland to Invercargill has leapt on to the band wagon. The bins come in 5 dierent coloursred, orange, yellow, green and blueand 5 wastes have been identied for recyclingPlastic, Glass, Aluminium, Steel, and Newspaper. Obviously there has been no coordination between cities, so each city has allocated wastes to bins in an arbitrary fashion. Now that the government has solved the minor problems of today (such as i

ii reorganising Health, Welfare and Education), they are looking around for further challenges. The Minister for Environmental Doodads wishes to introduce the Regularisation of Allocation of Solid Waste to Bin Colour Bill to Parliament, but in order to do so needs to determine an allocation of his own. Being a rm believer in democracy (well some of the time anyway), he surveys all the cities that are using this recycling method. From these data he wishes to determine the city whose allocation scheme (if imposed on the rest of the country) would cause the least impact, that is would cause the smallest number of changes in the allocations of the other cities. Note that the sizes of the cities is not an issue, after all this is a democracy with the slogan One City, One Vote. Write a program that will read in a series of allocations of wastes to bins and determine which citys allocation scheme should be chosen. Note that there will always be a clear winner.

Input and Output


Input will consist of a series of blocks. Each block will consist of a series of lines and each line will contain a series of allocations in the form shown in the example. There may be up to 100 cities in a block. Each block will be terminated by a line starting with e. The entire le will be terminated by a line consisting of a single #. Output will consist of a series of lines, one for each block in the input. Each line will consist of the number of the city that should be adopted as a national example.

Sample input:
r/P,o/G,y/S,g/A,b/N r/G,o/P,y/S,g/A,b/N r/P,y/S,o/G,g/N,b/A r/P,o/S,y/A,g/G,b/N e r/G,o/P,y/S,g/A,b/N r/P,y/S,o/G,g/N,b/A r/P,o/S,y/A,g/G,b/N r/P,o/G,y/S,g/A,b/N ecclesiastical #

iii

Sample output
1 4 Case review: 1st Algorithm: Brute Force For each city, iterate through every other city, and count the number of dierences. So, keep a counter, and if city[i]s red bin != city[j]s red bin, add one to the count. Output the city with the fewest dierences. Source: Your Code here .... 2nd Algorithm: Brute Force Make an array of chars [100][5] where a[i][0] is the color of the plastic bin, a[i][1] is the color of the glass bin, and so on. Then compare each city brute force against all other cities, and return the most optimal one. Source: Your Code here .... dan seterusnya. Catatan: Review sebaiknya menggunakan Bahasa Inggris (tidak diharuskan). Boleh lebih dari 3 cara. Utamakan bagaimana penyelesaian kasus terlebih dahulu, optimalisasi algoritma bisa belakangan.

iv Algoritma kedua dan seterusnya boleh berupa optimalisasi dari algoritma pertama atau algoritma-algoritma sebelumnya.

Regards. Hayi Nukman (July 2011), a Created with: L TEX.

Daftar Isi

Recycling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Easy 1.1 The Blocks Problem . 1.2 Greedy Gift Givers . . 1.3 Number Chains . . . . 1.4 The Bases Are Loaded 1.5 Combinations . . . . .

i 1 1 4 6 8 9 11 11 12 14 16 20

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

2 Medium 2.1 Lining Up . . . . . . . . . . . 2.2 The Tower of Babylon . . . . 2.3 Points in Figures: Rectangles 2.4 King . . . . . . . . . . . . . . 2.5 Number Maze . . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

3 Hard 23 3.1 Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.2 The Probable n-Ascendants . . . . . . . . . . . . . . . . . . . 25 3.3 Poker Hands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 4 Math 4.1 LCM . . . . . . . . . . 4.2 Minimum Sum LCM . 4.3 Hendrie Sequence . . . 4.4 Modular Fibonacci . . 4.5 Polynomial coecients 4.6 Pizza Cutting . . . . . 31 31 32 35 36 38 39

. . . . . .

. . . . . .

. . . . . .

. . . . . . v

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

vi

DAFTAR ISI 43 43 47 48

5 Sorting and Searching 5.1 Crossword Answers . . . . . . . . . . . . . . . . . . . . . . . . 5.2 The Department of Redundancy Department . . . . . . . . . . 5.3 Error Correction . . . . . . . . . . . . . . . . . . . . . . . . .

6 Other 51 6.1 Group Reverse . . . . . . . . . . . . . . . . . . . . . . . . . . 51 6.2 Testing the CATCHER . . . . . . . . . . . . . . . . . . . . . . 52 6.3 The Settlers of Catan . . . . . . . . . . . . . . . . . . . . . . . 54

BAB 1

Easy

Go for the happy endings, because life doesnt have any sequels.

1.1 The Blocks Problem

Background
Many areas of Computer Science use simple, abstract domains for both analytical and empirical studies. For example, an early AI study of planning and robotics (STRIPS) used a block world in which a robot arm performed tasks involving the manipulation of blocks. In this problem you will model a simple block world under certain rules and constraints. Rather than determine how to achieve a specied state, you will program a robotic arm to respond to a limited set of commands. The Problem The problem is to parse a series of commands that instruct a robot arm in how to manipulate blocks that lie on a at table. Initially there are n blocks on the table (numbered from 0 to n-1) with block bi adjacent to block bi+1 for all 0 i < n 1 as shown in the diagram below: Figure: Initial Blocks World The valid commands for the robot arm that manipulates blocks are: * move a onto b 1

BAB 1. EASY where a and b are block numbers, puts block a onto block b after returning any blocks that are stacked on top of blocks a and b to their initial positions. * move a over b where a and b are block numbers, puts block a onto the top of the stack containing block b, after returning any blocks that are stacked on top of block a to their initial positions. * pile a onto b where a and b are block numbers, moves the pile of blocks consisting of block a, and any blocks that are stacked above block a, onto block b. All blocks on top of block b are moved to their initial positions prior to the pile taking place. The blocks stacked above block a retain their order when moved. * pile a over b where a and b are block numbers, puts the pile of blocks consisting of block a, and any blocks that are stacked above block a, onto the top of the stack containing block b. The blocks stacked above block a retain their original order when moved. * quit terminates manipulations in the block world. Any command in which a = b or in which a and b are in the same stack of blocks is an illegal command. All illegal commands should be ignored and should have no aect on the conguration of blocks.

The Input
The input begins with an integer n on a line by itself representing the number of blocks in the block world. You may assume that 0 <n <25. The number of blocks is followed by a sequence of block commands, one command per line. Your program should process all commands until the quit command is encountered. You may assume that all commands will be of the form specied above. There will be no syntactically incorrect commands.

The Output
The output should consist of the nal state of the blocks world. Each original block position numbered i ( 0 i < n where n is the number

3 of blocks) should appear followed immediately by a colon. If there is at least a block on it, the colon must be followed by one space, followed by a list of blocks that appear stacked in that position with each block number separated from other block numbers by a space. Dont put any trailing spaces on a line. There should be one line of output for each block position (i.e., n lines of output where n is the integer on the rst line of input).

Sample Input
10 move move move move pile pile move move quit

9 8 7 6 8 8 2 4

onto over over over over over over over

1 1 1 1 6 5 1 9

Sample Output
0: 1: 2: 3: 4: 5: 6: 7: 8: 9: 0 1 9 2 4 3 5 8 7 6

Miguel Revilla 2000-04-06 HINT:

BAB 1. EASY

Use a two dimensional array where a[i][j] is the jth block in the ith stack. a[i][0] = i for all i, and a[i][j] = 1 for all j > 0. Then just implement the four functions carefully.

1.2 Greedy Gift Givers

The Problem
This problem involves determining, for a group of gift-giving friends, how much more each person gives than they receive (and vice versa for those that view gift-giving with cynicism). In this problem each person sets aside some money for gift-giving and divides this money evenly among all those to whom gifts are given. However, in any group of friends, some people are more giving than others (or at least may have more acquaintances) and some people have more money than others. Given a group of friends, the money each person in the group spends on gifts, and a (sub)list of friends to whom each person gives gifts; you are to write a program that determines how much more (or less) each person in the group gives than they receive.

The Input
The input is a sequence of gift-giving groups. A group consists of several lines: the number of people in the group, a list of the names of each person in the group, a line for each person in the group consisting of the name of the person, the amount of money spent on gifts, the number of people to whom gifts are given, and the names of those to whom gifts are given. All names are lower-case letters, there are no more than 10 people in a group, and no name is more than 12 characters in length. Money is a non-negative integer less than 2000.

5 The input consists of one or more groups and is terminated by endof-le.

The Output
For each group of gift-givers, the name of each person in the group should be printed on a line followed by the net gain (or loss) received (or spent) by the person. Names in a group should be printed in the same order in which they rst appear in the input. The output for each group should be separated from other groups by a blank line. All gifts are integers. Each person gives the same integer amount of money to each friend to whom any money is given, and gives as much as possible. Any money not given is kept and is part of a persons net worth printed in the output.

Sample Input
5 dave laura owen vick amr dave 200 3 laura owen vick owen 500 1 dave amr 150 2 vick owen laura 0 2 amr vick vick 0 0 3 liz steve dave liz 30 1 steve steve 55 2 liz dave dave 0 2 steve liz

Sample Output
dave 302 laura 66 owen -359 vick 141 amr -150 liz -3

6 steve -24 dave 27

BAB 1. EASY

HINT: Just use some Object Oriented programming. one person class solves all your problems: class person -----int ratio -----int money -----string name make an array of them, and take all the information in. When it comes time to take a persons (a) friends in, just loop through your list of people (p) and: person(a).ratio -= person(a).money/friends(a) person(p).ratio += person(a).money/friends(a) go through the people array once more, outputting the ratio and their name.

1.3 Number Chains

Given a number, we can form a number chain by 1. arranging its digits in descending order 2. arranging its digits in ascending order 3. subtracting the number obtained in (2) from the number obtained (1) to form a new number 4. and repeat these steps unless the new number has already appeared in the chain Note that 0 is a permitted digit. The number of distinct numbers in the chain is the length of the chain. You are to write a program that reads numbers and outputs the number chain and the length of that chain for each number read.

Input and Output


The input consists of a sequence of positive numbers, all less than 109 , each on its own line, terminated by 0. The input le contains at most 5000 numbers. The output consists of the number chains generated by the input numbers, followed by their lengths exactly in the format indicated below. After each number chain and chain length, including the last one, there should be a blank line. No chain will contain more than 1000 distinct numbers.

Sample Input
123456789 1234 444 0

Sample Output
Original number was 123456789 987654321 - 123456789 = 864197532 987654321 - 123456789 = 864197532 Chain length 2 Original number was 1234 4321 - 1234 = 3087 8730 - 378 = 8352 8532 - 2358 = 6174 7641 - 1467 = 6174 Chain length 4 Original number was 444 444 - 444 = 0 0 - 0 = 0 Chain length 2 HINT

BAB 1. EASY

For each number n in the chain, transfer it to an integer array where a[i] is the ith digit of n. Sort the array ascending and convert the individual digits back into a complete number. Then iterate through the array backwards and convert the digits into another number. Subtract the former from the latter to generate your next n. Keep an array p[] that holds all values previously reached. Whenever you generate a new n, search for it in p[]. If you dont nd it, add it in. If you do nd it, then stop processing and print out the length of the chain (which should be the number of elements in p[] +/- 1 depending on how you implemented it).

1.4 The Bases Are Loaded

Write a program to convert a whole number specied in any base (2..16) to a whole number in any other base (2..16). Digits above 9 are represented by single capital letters; e.g. 10 by A, 15 by F, etc.

Input
Each input line will consist of three values. The rst value will be a positive integer indicating the base of the number. The second value is a positive integer indicating the base we wish to convert to. The third value is the actual number (in the rst base) that we wish to convert. This number will have letters representing any digits higher than 9 and may contain invalid digits. It will not exceed 10 characters. Each of the input values on a single line will be separated by at least one space.

Output
Program output consists of the original number followed by the string base, followed by the original base number, followed by the string = followed by the converted number followed by the string base followed by the new base. If the original number is invalid, output the statement original Value is an illegal base original Base number

9 where original Value is replaced by the value to be converted and original Base is replaced by the original base value.

Sample input
2 10 10101 5 3 126 15 11 A4C

Sample output
10101 base 2 = 21 base 10 126 is an illegal base 5 number A4C base 15 = 1821 base 11 HINT: Convert each number into base 10, and then convert it into the nal base. Check for invalid characters, which may be things like lowercase letters or punctuation. Basically, check that only the characters in the set {0123456789ABCDEF} are used, and that the number is legal in the given base. If youre using Java, you can use Long.parseLong to do the base conversion, and you can catch NumberFormatExceptions, which indicate that the number contains invalid characters. Note that you must use longs as ints are too small for some of the inputs.

1.5 Combinations
Computing the exact number of ways that N things can be taken M at a time can be a great challenge when N and/or M become very large. Challenges are the stu of contests. Therefore, you are to make just such a computation given the following: GIVEN: 5 N 100, and 5 M 100, and M N Compute the EXACT value of:

10 N! (N M )! M !

BAB 1. EASY

C=

You may assume that the nal value of C will t in a 32-bit Pascal LongInt or a C long. For the record, the exact value of 100! is: 93,326,215,443,944,152,681,699,238,856,266,700,490, 715,968,264,381,621,468,592,963,895,217,599,993,229, 915,608,941,463,976,156,518,286,253,697,920,827,223, 758,251,185,210,916,864,000,000,000,000,000,000,000,000

Input and Output


The input to this program will be one or more lines each containing zero or more leading spaces, a value for N, one or more spaces, and a value for M. The last line of the input le will contain a dummy N, M pair with both values equal to zero. Your program should terminate when this line is read. The output from this program should be in the form:

N things taken M at a time is C exactly.


Sample Input
100 20 18 0 6 5 6 0

Sample Output
100 things taken 6 at a time is 1192052400 exactly. 20 things taken 5 at a time is 15504 exactly. 18 things taken 6 at a time is 18564 exactly.

BAB 2

Medium

STUPID = Smart Talented Unique Person In Demand

2.1 Lining Up
How am I ever going to solve this problem? said the pilot. Indeed, the pilot was not facing an easy task. She had to drop packages at specic points scattered in a dangerous area. Furthermore, the pilot could only y over the area once in a straight line, and she had to y over as many points as possible. All points were given by means of integer coordinates in a two-dimensional space. The pilot wanted to know the largest number of points from the given set that all lie on one line. Can you write a program that calculates this number? Your program has to be ecient!

Input
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs. The input consists of N pairs of integers, where 1 < N < 700. Each pair of integers is separated by one blank and ended by a new-line character. The list of pairs is ended with an end-of-le character. No pair will occur twice.

Output
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line. The 11

12

BAB 2. MEDIUM

output consists of one integer representing the largest number of points that all lie on one line.

Sample Input
1 1 1 2 2 3 3 9 10 10 11

Sample Output
3 HINT: computational geometry, sorting, line gradients (slopes). Try an O(n2 logn) algorithm.

2.2 The Tower of Babylon


Perhaps you have heard of the legend of the Tower of Babylon. Nowadays many details of this tale have been forgotten. So now, in line with the educational nature of this contest, we will tell you the whole story: The babylonians had n types of blocks, and an unlimited supply of blocks of each type. Each type-i block was a rectangular solid with linear dimensions (xi , yi , zi ) . A block could be reoriented so that any two of its three dimensions determined the dimensions of the base and the other dimension was the height. They wanted to construct the tallest tower possible by stacking blocks. The problem was that, in building a tower, one block could only be placed on top of another block as long as the two base dimensions of the upper block were both strictly smaller than the corresponding base dimensions of the lower block. This meant, for example, that blocks oriented to have equal-sized bases

13 couldnt be stacked. Your job is to write a program that determines the height of the tallest tower the babylonians can build with a given set of blocks.

Input and Output


The input le will contain one or more test cases. The rst line of each test case contains an integer n, representing the number of different blocks in the following data set. The maximum value for n is 30. Each of the next n lines contains three integers representing the values xi ,yi and zi . Input is terminated by a value of zero (0) for n. For each test case, print one line containing the case number (they are numbered sequentially starting from 1) and the height of the tallest possible tower in the format "Case case: maximum height = height"

Sample Input
1 10 20 30 2 6 8 10 5 5 5 7 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 5 31 41 59 26 53 58 97 93 23 84 62 64 33 83 27 0

14

BAB 2. MEDIUM

Sample Output
Case Case Case Case 1: 2: 3: 4: maximum maximum maximum maximum height height height height = = = = 40 21 28 342

HINT: dynamic programming, oyd warshall, other graph, DP, LIS (nonstandard). wasley: There are two main ways to do this problem... either Longest Increasing Subsequence, or nding the longest path in a DAG. I prefer the latter, because you can use Floyd-Warshall with the bounds of this problem, and thats much easier that doing LIS. Let the weight of edge (u,v) be the height of block u, if u ts on top of v, and -Inf otherwise. Then, run Floyd-Warshall, but with max instead of min. For an arbitrary graph this wont work, but for DAG its just ne. At the end, maximize (a[u][v] + h[v]) across all (u,v) where h[v] is the height of block v (because we didnt add that during Floyd).

2.3 Points in Figures: Rectangles

Given a list of rectangles and a list of points in the x-y plane, determine for each point which gures (if any) contain the point.

Input
There will be n( 10) rectangles descriptions, one per line. The rst character will designate the type of gure (r for rectangle). This character will be followed by four real values designating the x-y coordinates of the upper left and lower right corners.

15 The end of the list will be signalled by a line containing an asterisk in column one. The remaining lines will contain the x-y coordinates, one per line, of the points to be tested. The end of this list will be indicated by a point with coordinates 9999.9 9999.9; these values should not be included in the output. Points coinciding with a gure border are not considered inside.

Output
For each point to be tested, write a message of the form: Point i is contained in figure j for each gure that contains that point. If the point is not contained in any gure, write a message of the form: Point i is not contained in any figure Points and gures should be numbered in the order in which they appear in the input.

Sample Input
r 8.5 17.0 25.5 -8.5 r 0.0 10.3 5.5 0.0 r 2.5 12.5 12.5 2.5 * 2.0 2.0 4.7 5.3 6.9 11.2 20.0 20.0 17.6 3.2 -5.2 -7.8 9999.9 9999.9

Sample Output
Point 1 is contained in figure 2 Point 2 is contained in figure 2

16 Point Point Point Point Point 2 3 4 5 6 is is is is is contained in figure 3 contained in figure 3 not contained in any figure contained in figure 1 not contained in any figure

BAB 2. MEDIUM

Diagrama of sample input gures and data points HINT: 2D geometry, geometry, point in rectangle. Keep an array of rectangle objects (just a package of the co-ords). For each point i with co-ordinates x and y, and each rectangle r with co-ordinates (x1 , y1 ) and (x2 , y2 ), i lies inside r if and only if: (x > x1 &&x < x2 &&y < y1 &&y > y2 ) Make sure that youre using strict inequalities, as per the problem description.

2.4 King

17 Once, in one kingdom, there was a queen and that queen was expecting a baby. The queen prayed: If my child was a son and if only he was a sound king. After nine months her child was born, and indeed, she gave birth to a nice son. Unfortunately, as it used to happen in royal families, the son was a little retarded. After many years of study he was able just to add integer numbers and to compare whether the result is greater or less than a given integer number. In addition, the numbers had to be written in a sequence and he was able to sum just continuous subsequences of the sequence. The old king was very unhappy of his son. But he was ready to make everything to enable his son to govern the kingdom after his death. With regards to his sons skills he decided that every problem the king had to decide about had to be presented in a form of a nite sequence of integer numbers and the decision about it would be done by stating an integer constraint (i.e. an upper or lower limit) for the sum of that sequence. In this way there was at least some hope that his son would be able to make some decisions. After the old king died, the young king began to reign. But very soon, a lot of people became very unsatised with his decisions and decided to dethrone him. They tried to do it by proving that his decisions were wrong. Therefore some conspirators presented to the young king a set of problems that he had to decide about. The set of problems was in the form of subsequences Si = {asi , asi +1 , . . . , asi +ni } of a sequence S = {a1 , a2 , . . . , an }. The king thought a minute and then decided, i.e. he set for the sum asi + asi +1 + + asi +ni of each subsequence Si an integer constraint ki (i.e. asi + asi +1 + + asi +ni < ki or asi + asi +1 + + asi +ni > ki resp.) and declared these constraints as his decisions. After a while he realized that some of his decisions were wrong. He could not revoke the declared constraints but trying to save himself he decided to fake the sequence that he was given. He ordered to his advisors to nd such a sequence S that would satisfy the constraints he set. Help the advisors of the king and write a program that decides whether such a sequence exists or not.

Input
The input le consists of blocks of lines. Each block except the last corresponds to one set of problems and kings decisions about them. In

18

BAB 2. MEDIUM

the rst line of the block there are integers n, and m where 0 < n 100 is length of the sequence S and 0 < m 100 is the number of subsequences Si. Next m lines contain particular decisions coded in the form of quadruples si, ni, oi, ki, where oi represents operator > (coded as gt) or operator < (coded as lt) respectively. The symbols si, ni and ki have the meaning described above. The last block consists of just one line containing 0.

Output
The output le contains the lines corresponding to the blocks in the input le. A line contains text successful conspiracy when such a sequence does not exist. Otherwise it contains text lamentable kingdom. There is no line in the output le corresponding to the last null block of the input le.

Sample Input
4 1 2 1 1 1 0 2 2 2 2 0 0 gt 0 lt 2 gt 0 lt 0

Sample Output
lamentable kingdom successful conspiracy

HINT:

19

math, other graph, graph theory, dierence constraints, BellmanFord. This is a constraint satisfaction problem that can be solved with negative cycle detection. A system of dierence constraints is a series of constraints of the form: x1 x2 C These systems can be solved by creating a graph with a vertex for each variable, and an edge from x2 to x1 with weight C for each constraint. There exists a solution that satises all of the constraints i the graph does not contain a negative weight cycle. However, the constraints given in this problem are not of this form. They contain multiple variables, are sums rather than additions, and have strict inequalities. Luckily, we can convert them. Let a[i] be the sum of the rst i variables in the sequence (a[0] = 0). Since all of the constraints relate contiguous subsequences, we can rewrite the constraint xk + xk+1 + ... + xk+h < / > C as a[k + h] a[k 1] < / > C Now, to change the strict inequalities into non-strict inequalities, note that, when working with integers: a[k + h] a[k 1] < C is the same as a[k + h] a[k 1] C 1 And in the same vein: a[k + h] a[k 1] > C is the same as a[k 1] a[k + h] (C + 1) Now, all you have to do is create the graph, and run Bellman-Ford (or so) to detect a negative weight cycle.

20

BAB 2. MEDIUM

2.5 Number Maze

Consider a number maze represented as a two dimensional array of numbers comprehended between 0 and 9, as exemplied below. The maze can be traversed following any orthogonal direction (i.e., north, south, east and west). Considering that each cell represents a cost, then nding the minimum cost to travel the maze from one entry point to an exit point may pose you a reasonable challenge.

Problem
Your task is to nd the minimum cost value to go from the top-left corner to the bottom-right corner of a given number maze of size NxM where 1 N , M 999. Note that the solution for the given example is 24.

Input
The input le contains several mazes. The rst input line contains a positive integer dening the number of mazes that follow. Each maze is dened by: one line with the number of rows, N; one line with the number of columns, M; and N lines, one per each row of the maze, containing the maze numbers separated by spaces. Output For each maze, output one line with the required minimum value.

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

21 1 7 5 5 3 2 3 4 2 5 1 6 0 1 2 3 4 5

Sample Output
24 15 University of Porto / 2003 ACM Programming Contest / Round 2 / 2003/09/24 HINT graph theory, shortest paths, Dijkstra (on a sparse graph), array priority queue, see CLRS exercise 24.3-6: The idea behind this problem is to nd a faster way of doing Dijkstra than O(E log V), given this special type of graph (that is, one in which all weights are less than 10). This can be accomplished by using 10 queues. The idea works as such: When you want to get the next node, search all of the queues in order until you come to one that isnt empty. Take the top node from this one. When you add a node to the queues, add it to the one that is c queues away from the one you are currently at, where c is the cost of traversing that node. For example, in the rst test case: The starting node has cost 0, so we put it onto queue 0. We dequeue this node, and look at its neighbours. They have costs 3 and 7, so they go in queues (0+3)%10 and (0+7)%10 respectively. Next, we take the node from queue 3 and examine its neightbours. They have costs 1 and 3, so they go in queues 4 and 6 respectively. So you make your way around the queues in a circle, and you keep taking from one queue until either it is empty, or the next queue in the circle has a node at the front that has shorter distance.

22

BAB 2. MEDIUM

BAB 3

Hard

3.1 Data Flow

Think smarter, not harder

In the latest Lab of IIUC, it requires to send huge amount of data from the local server to the terminal server. The lab setup is not yet ready. It requires to write a router program for the best path of data. The problem is all links of the network has a xed capacity and cannot ow more than that amount of data. Also it takes certain amount of time to send one unit data through the link. To avoid the collision at a time only one data unit can travel i.e. at any instant more than one unit of data cannot travel parallel through the network. This may be time consuming but it certainly gives no collision. Each node has sucient buering capability so that data can be temporarily stored there. IIUC management wants the shortest possible time to send all the data from the local server to the nal one.

23

24

BAB 3. HARD

For example, in the above network if anyone wants to send 20 unit data from A to D, he will send 10 unit data through AD link and then 10 unit data through AB-BD link which will take 10+70=80 unit time.

Input
Each input starts with two positive integers N (2 N 100), M (1 M 5000). In next few lines the link and corresponding propagation time will be given. The links are bidirectional and there will be at most one link between two network nodes. In next line there will be two positive integers D, K where D is the amount of data to be transferred from 1st to Nth node and K is the link capacity. Input is terminated by EOF.

Output
For each dataset, print the minimum possible time in a line to send all the data. If it is not possible to send all the data, print Impossible.. The time can be as large as 1015.

Sample Input and Output

Problemsetter: Md. Kamruzzaman Member of Elite Problemsetters Panel

25

HINT: dijkstra, max ow, other graph This is a minimum-cost maximum ow problem. Basically, its the combination of shortest path and maximum ow. The general idea is not too dicult. You do Edmonds-Karp to get the maximum ow, but you replace the BFS with a weighted shortest path algorithm. Dijkstra is the best choice, except that the graph will have negative costs after you reverse edges. You can do Bellman-Ford, but unfortunately thats too slow for this problem (unless youre lucky in C perhaps). Luckily, there exists a compromise. You can run Bellman-Ford once at the beginning of the algorithm to set the graph up in such a way that Dijkstra will work from that point on. In this problem, because there are no negative costs to begin with, you dont need Bellman-Ford at all, and you can use Dijkstra to initialize the graph, but it doesnt matter much runtime-wise. I suggest reading the following to understand how this graph initialization part works. Read the subsection Successive Shortest Path Algorithm: http://www.topcoder.com/tc?module=Static&d1=tutorials &d2=minimumCostFlow2

3.2 The Probable n-Ascendants

In the biological autosomic inheritance, each characteristic of one individual is determined by a pair of genes (a gene is a part of a chromosome). When a pair of genes presents dierent information for one characteristic, the dominance of one gene over the other naturally inuences the way an individual externally presents that characteristic.

26

BAB 3. HARD

In the case of total dominance, a dominant gene imposes the external appearance of its information over the other gene of the pair. The information of a recessive gene (the dominated gene) is only externally shown if there is no dominant gene in the pair. The information of a dominant gene is represented by a capital letter, while the information of a recessive gene is represented by a small letter. One individual that possesses a pair of genes with equal information for the same characteristic is called homozigotic, otherwise it is called heterozigotic. In the guinee-pigs, the gene for the black colour (B) is dominant over the gene for the white colour (w). The descendants genetic types (composition of the pair of genes) of two parents are obtained by generating the dierent possible combinations of the 4 genes of the parents. Each ascendant contributes with only one gene to the pair of genes of the descendant. For instance, one heterozigotic guinee-pig (Bw) presents the same colour of one black homozigotic guinee-pig (BB). The descendants of two black homozigotic guinee-pigs (BB) have 100% probability of also being black homozigotic individuals. An analogous situation occurs with the descendants of two white homozigotic guinee-pigs (ww), i.e., they have 100% probability of also being white homozigotic individuals. The descendants of one black homozigotic guinee-pig (BB) and one white homozigotic guinee-pig (ww) have 100% probability of being black heterozigotic individuals. The following gure illustrates this description. Imagine that you dont know, for a particular guinee-pig, who were

27 its parents (1-ascendants), or its grand-parents (2-ascendants), or its great-grand-parents (3-ascendants). Your task is to write a program that lists the genes of the possible n-ascendants (ascendants of level n) of that individual and the associated probability of each pair of possible n-ascendants. Assume the maximum value of n is 35.

Input
The input will contain several test cases, each of them as described below. Consecutive test cases are separated by a single blank line. The rst line of the input contains the genes of the guinee-pig for whom you want to know the probable n-ascendants. The second line contains the value of n, i.e., the level of ascendant generation that you want to study.

Output
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line. The output is a list of lines, each one containing the concatenated genes of each member of the possible pair of n-ascendants, followed by the corresponding probability, truncated to 2 fractional digits. The concatenation of the 2 pair of n-ascendant genes must ensure that the resultant string is the biggest one, considering BBBB > BBBw > BBwB > ... > wwwB > wwww. The output must be sorted in descending order by value of the concatenation of the 2 pair of n-ascendant genes. Before printing any oating point value add 10-11to avoid round o error.

Sample Input
Bw 1 ww 8

Sample Output
BBBw 20.0% BBww 40.0%

28 BwBw 20.0% Bwww 20.0% BBBB BBBw BBww BwBw Bwww wwww 15.58% 16.12% 16.67% 16.67% 17.21% 17.75%

BAB 3. HARD

University of Porto / 2003 ACM Programming Contest / Round 2 / 2003/09/24

3.3 Poker Hands

A poker deck contains 52 cards - each card has a suit which is one of clubs, diamonds, hearts, or spades (denoted C, D, H, and S in the input data). Each card also has a value which is one of 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace (denoted 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, A). For scoring purposes, the suits are unordered while the values are ordered as given above, with 2 being the lowest and ace the highest value. A poker hand consists of 5 cards dealt from the deck. Poker hands are ranked by the following partial order from lowest to highest High Card: Hands which do not t any higher category are ranked by the value of their highest card. If the highest cards have the same value, the hands are ranked by the next highest, and so on. Pair: 2 of the 5 cards in the hand have the same value. Hands which both contain a pair are ranked by the value of the cards forming the pair. If these values are the same, the hands are ranked by the values of the cards not forming the pair, in decreasing order. Two Pairs: The hand contains 2 dierent pairs. Hands which both contain 2 pairs are ranked by the value of their highest pair. Hands with the same highest pair are ranked by the value of their other pair. If these values are the same the hands are ranked by the value of the remaining card.

29 Three of a Kind: Three of the cards in the hand have the same value. Hands which both contain three of a kind are ranked by the value of the 3 cards. Straight: Hand contains 5 cards with consecutive values. Hands which both contain a straight are ranked by their highest card. Flush: Hand contains 5 cards of the same suit. Hands which are both ushes are ranked using the rules for High Card. Full House: 3 cards of the same value, with the remaining 2 cards forming a pair. Ranked by the value of the 3 cards. Four of a kind: 4 cards with the same value. Ranked by the value of the 4 cards. Straight ush: 5 cards of the same suit with consecutive values. Ranked by the highest card in the hand. Your job is to compare several pairs of poker hands and to indicate which, if either, has a higher rank.

Input
The input le contains several lines, each containing the designation of 10 cards: the rst 5 cards are the hand for the player named Black and the next 5 cards are the hand for the player named White.

Output
For each line of input, print a line containing one of the following three lines: Black wins. White wins. Tie.

Sample Input
2H 2H 2H 2H 3D 4S 3D 3D 5S 4C 5S 5S 9C 2D 9C 9C KD 4H KD KD 2C 2S 2C 2D 3H 8S 3H 3H 4S AS 4S 5C 8C QS 8C 9S AH 3S KH KH

30

BAB 3. HARD

Sample Output
White wins. Black wins. Black wins. Tie. (The Decider Contest, Source: Waterloo ACM Programming Contest) HINT: adhoc Sort both players hands. Itll make the comparisons a lot easier Check for hands by decreasing value, i.e. straight ush, then four of a kind, etc. all the way down to high card. Checking four four of a kind, then three, then two, is a lot easier than the other way around

BAB 4

Math

I couldnt repair your brakes, so I just made your horn louder.

4.1 LCM

All of you know about LCM (Least Common Multiple). For example LCM of 4 and 6 is 12. LCM can also be dened for more than 2 integers. LCM of 2, 3, 5 is 30. In the same way we can dene LCM of rst N integers. The LCM of rst 6 numbers is 60. As you will see LCM will increase rapidly with N. So we are not interested in the exact value of the LCM but we want to know the last nonzero digit of that. And you have to nd that eeciently.

Input
Each line contains one nonzero positive integer which is not greater than 1000000. Last line will contain zero indicating the end of input. This line should not be processed. You will need to process maximum 1000 lines of input.

Output
For each line of input, print in a line the last nonzero digit of LCM of rst 1 to N integers.

Sample Input
3 5 31

32 10 0

BAB 4. MATH

Output for Sample Input


6 6 2 Problemsetter: Md. Kamruzzaman, Member of Elite Problemsetters Panel Special thanks to: Mohammad Sajjad Hossain

HINT: Let P(n) be the multiset of prime factors of n. So, P(60) = 2, 2, 3, 5. The LCM of a set of numbers a1 , a2 , a3 , ..., an is the product of the intersection of P (a1 ), P (a2 ), ..., P (an ). Intuitively, this means that you need enough of each prime factor in the LCM to satisfy each of the numbers. Let a[i] be the LCM of the numbers from 1 to i. To determine a[i + 1], factorize i + 1, then see if you need any of its factors. Keep an array c[] where c[j] is the number of times youve used j as a factor in your LCM so far. When you factorize i+1, check if the count of each factor, j, is greater than c[j]. If it is, multiply your current LCM by j until the count is satised. Now, the LCM grows very quickly, so we dont want to actually store the entire LCM in a[]. Instead, we store the last 7 or so digits before the nal string of zeros. So, if our LCM was 182158203800000000, we would store 1582038 in a[]. This can be accomplished by the following code: while(a[i] % 10 == 0) --- a[i] /= 10 a[i] %= 10000000 We keep 7 digits because the largest number we might multiply a[i] by is 6 digits long.

4.2 Minimum Sum LCM

33

LCM (Least Common Multiple) of a set of integers is dened as the minimum number, which is a multiple of all integers of that set. It is interesting to note that any positive integer can be expressed as the LCM of a set of positive integers. For example 12 can be expressed as the LCM of 1, 12 or 12, 12 or 3, 4 or 4, 6 or 1, 2, 3, 4 etc. In this problem, you will be given a positive integer N. You have to nd out a set of at least two positive integers whose LCM is N. As innite such sequences are possible, you have to pick the sequence whose summation of elements is minimum. We will be quite happy if you just print the summation of the elements of this set. So, for N = 12, you should print 4+3 = 7 as LCM of 4 and 3 is 12 and 7 is the minimum possible summation.

Input
The input le contains at most 100 test cases. Each test case consists of a positive integer N ( 1N231 - 1). Input is terminated by a case where N = 0. This case should not be processed. There can be at most 100 test cases.

Output
Output of each test case should consist of a line starting with Case #: where # is the test case number. It should be followed by the summation as specied in the problem statement. Look at the output for sample input for details.

Sample Input
12 10 5 0

Sample Output
Case 1: 7 Case 2: 7 Case 3: 6

34

BAB 4. MATH

Problem setter: Md. Kamruzzaman Special Thanks: Shahriar Manzoor Miguel Revilla 2004-12-10 HINT: This is a prime factorization problem with a lot of picky cases. The rst thing to see is that the prim factorization of a number is almost the minimum sum LCM set. I say almost because you have to keep copies of the same factor multipled together. For example, say N = 36. The prime factorization is 22 32 . Obviously the minimum set isnt 2,2,3,3 because this would have an LCM of 6. The set is actually 22 , 32 or 4,9. So, for *most* cases, just nd the prime factorization, keep copies of the same term together, and return the sum of the products (so 4 + 9 = 13 in the above example). However, there are some issues. First theres N = 1, and N = 23 1 1. For N = 1, you must output 2. This is a little bit counterituitive, because the set 1,1 contains two of the same number, and therefore, isnt truly a set. However, by the problem denition you must have at least two numbers in your set. For N = 23 1 1, you must output 23 1. This is a problem if youre using unsigned integers, of course. But I wouldnt bother changing to signed integers or longs. Just hardcode this case. The other issue involves numbers that are powers of a single factor. So for instance 51 , or 21 0. You cant just give 5 or 1024 as your sets, because these have only one number. Instead, you need to add 1 (so 5,1 = 6 and 1024, 1 = 1025). As far as prime factorization goes, heres how you can do it. We know our limit is 23 1, so we can generate all the primes up to 231 216 = using the Sieve of Eratosthenes, and use these to factor N. Scan through the list of primes from 2 to sqrt(N), and divide N by each prime that its divisible by (as many times as you can). Keep track of these primes as they are (obviously) factors of N. Once youve gone through all the primes <= N , there will be one of two cases. Either N = 1, in which case youre done, or N > 1, in which case N now equals the last factor of (the original) N. This is because you can have no more than one prime factor greater than the square root of the number. So if N > 1, record N as another factor.

35

4.3 Hendrie Sequence

The Hendrie Sequence H is a self-describing sequence dened as follows: H(1) = 0 If we expand every number x in H to a subsequence containing x 0s followed by the number x + 1, the resulting sequence is still H (without its rst element). Thus, the rst few elements of H are: 0,1,0,2,1,0,0,3,0,2,1,1,0,0,0,4,1,0,0,3,0,... You must write a program that, given n, calculates the nth element of H.

Input
Each test case consists of a single line containing the integer n ( 0 < n < 263 ) . Input is terminated with a line containing the number 0 which of course should not be processed.

Output
For each test case, output the nth element of H on a single line.

Sample Input
4 7 44 806856837013209088 0

Sample Output
2 0 3 16

36

BAB 4. MATH

Problem setter: Derek Kisman, University of Waterloo, Canada HINT: The sequence, strategically broken up into blocks, looks like this: 0 | 1 | 0 2 | 1 00 3 | 02 11 000 4 | 1003 0202 111 0000 5 | We note that the ith block has length 2(i2) (excepting the rst block which has length 1). Also, the ith block consists of (i-2) pieces from prior blocks, and then the number i-1. For example, the 6th block has: 1 0 0 3 (1 copy of block 4) 02 02 (2 copies of block 3) 111 (3 copies of block 2) 0000 (4 copies of block 1) 5 (the number (6-1)) As every block is dened in terms of the block before it, we can write a recursive function that simplies the problem down until it reaches a known value (say, the rst 10 values of the sequence or so). If the number given, n, is a perfect power of 2, we just return log2(n). Otherwise, we use k = floor(log2(n)) to determine which block n belongs to. n 2k is how far along the block n is. We add up the lengths of the subblocks, i 2(ki1) for i from 1 to k until the cumulative sum is greater than or equal to (n 2k ). The index i at which we stop is the number of the subblock that n belongs to. We can now simplify n down to 2(ki1) + (n 2k 1)%(2(ki1) ) + 1, and recurse on this new value. Note that (k i 1) can be < 0, in which case the rst 2(ki1) should be set to 0, and the latter should be set to 1. Be wary of double precision as it isnt quite good enough for this problem. I would suggest doing everything in longs to avoid rounding 63 errors. For instance, log(2 1) gives 63, when then actual value is log(2) slightly less than 63.

4.4 Modular Fibonacci

37 The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) are dened by the recurrence: F0 = 0 F1 = 1 Fi = Fi1 + Fi2 f or(i) > 1 Write a program which calculates Mn = Fn mod 2m for given pair of n and m. 0 n 2147483647 and 0 m < 20. Note that a mod b gives the remainder when a is divided by b.

Input and Output


Input consists of several lines specifying a pair of n and m. Output should be corresponding Mn, one per line.

Sample Input
11 7 11 6

Sample Output
89 25 Arun Kishore HINT: This problem requires an O(log n) method to calculate an arbitrary Fibonacci number. The algorithm works o of the idea that you can do the following matrix multiplication: [ ] [ ] 1 1 Fn+1 Fn = Fn Fn1 1 0 and you will get the next set of Fibonacci numbers. Thus, we can derive: F2n = Fn (Fn + 2Fn1 ) 2 2 F2n1 = Fn + Fn1 depending on whether the number is even or odd. We can use these formulas along with an algorithm that does O(log n) exponentiation to come up with the answer. Take mod m after every addition and

38

BAB 4. MATH

multiplication to keep the numbers small, and use longs because you may need to square numbers as large as 220 , and 240 wont t in an int.

4.5 Polynomial coecients

The Problem
The problem is to calculate the coecients in expansion of polynomial (x1 + x2 + ... + xk )n .

The Input
The input will consist of a set of pairs of lines. The rst line of the pair consists of two integers n and k separated with space (0 < K, N < 13). This integers dene the power of the polynomial and the amount of the variables. The second line in each pair consists of k non-negative integers n1 , ..., nk , where n1 + ... + nk = n.

The Output
For each input pair of lines the output line should consist one integer, the coecient by the monomial xn1 xn2 ...xnk in expansion of the polynomial 1 2 k (x1 + x2 + ... + xk )n .

Sample Input
2 1 2 1 2 1 12 0 0 0 0 0 0 0 0 0 1 0

Sample Output
2 2

39

HINT: Let n(k) be the power of the kth term in the monomial were asked to examine. Given the polynomial (x1 + x2 + ... + xl )n , we can break it up using the binomial theorem: ((x1 + ... + xk 1) + xk )n
k i=1

(nCi) (x1 + ... + xk 1)n i xi k

The only term we care about is where i = n(xk), so we can through away the rest. We keep breaking this down recursively until we end up with a product of Chooses, which we can then simplify into a simple nal form: n! n1 ! n2 ! ... nk !

4.6 Pizza Cutting

When someone calls Ivan lazy, he claims that it is his intelligence that helps him to be so. If his intelligence allows him to do something at less physical eort, why should he exert more? He also claims that he always uses his brain and tries to do some work at less eort; this is not his laziness, rather this is his intellectual smartness. Once Ivan was asked to cut a pizza into seven pieces to distribute it among his friends. (Size of the pieces may not be the same. In fact, his piece will be larger than the others.) He thought a bit, and came to the conclusion that he can cut it into seven pieces by only three straight cuts through the pizza with a pizza knife. Accordingly, he cut the pizza in the following way (guess which one is Ivans piece):

40

BAB 4. MATH

One of his friends, who never believed in Ivans smartness, was startled at this intelligence. He thought, if Ivan can do it, why cant my computer? So he tried to do a similar (but not exactly as Ivans, for Ivan will criticize him for stealing his idea) job with his computer. He wrote a program that took the number of straight cuts one makes through the pizza, and output a number representing the maximum number of pizza pieces it will produce. Your job here is to write a similar program. It is ensured that Ivans friend wont criticize you for doing the same job he did.

Input
The input le will contain a single integer N (0 <= N <= 210000000) in each line representing the number of straight line cuts one makes through the pizza. A negative number terminates the input.

Output
Output the maximum number of pizza pieces the given number of cuts can produce. Each line should contain only one output integer without any leading or trailing space.

Sample Input
5 10 -100

41

Sample Output
16 56 Rezaul Alam Chowdhury HINT: On the ith cut, you can cut through i pieces of pizza. Therefore the total number of cuts is the triangular number sequence. As you start with one piece, you must add one to all the terms. So for each input n, output n(n+1) + 1. 2

42

BAB 4. MATH

BAB 5

Sorting and Searching

Being Stupid isnt as easy as it may look.

5.1 Crossword Answers

A crossword puzzle consists of a rectangular grid of black and white squares and two lists of denitions (or descriptions). One list of denitions is for words to be written left to right across white squares in the rows and the other list is for words to be written down white squares in the columns. (A word is a sequence of alphabetic characters.) To solve a crossword puzzle, one writes the words corresponding to the denitions on the white squares of the grid. The denitions correspond to the rectangular grid by means of sequential integers on eligible white squares. White squares with black squares immediately to the left or above them are eligible. White squares with no squares either immediately to the left or above are also eligible. No other squares are numbered. All of the squares on the rst row are numbered. The numbering starts with 1 and continues consecutively across white squares of the rst row, then across the eligible white squares of the second row, then across the eligible white squares of the third row and so on across all of the rest of the rows of the puzzle. The picture below illustrates a rectangular crossword puzzle grid with appropriate numbering. 43

44

BAB 5. SORTING AND SEARCHING

An across word for a denition is written on a sequence of white squares in a row starting on a numbered square that does not follow another white square in the same row. The sequence of white squares for that word goes across the row of the numbered square, ending immediately before the next black square in the row or in the rightmost square of the row. A down word for a denition is written on a sequence of white squares in a column starting on a numbered square that does not follow another white square in the same column. The sequence of white squares for that word goes down the column of the numbered square, ending immediately before the next black square in the column or in the bottom square of the column. Every white square in a correctly solved puzzle contains a letter. You must write a program that takes several solved crossword puzzles as input and outputs the lists of across and down words which constitute the solutions.

Input
Each puzzle solution in the input starts with a line containing two integers r and c ( 1 r 10 and 1 c 10 ), where r (the rst number) is the number of rows in the puzzle and c (the second number) is the number of columns. The r rows of input which follow each contain c characters (excluding the end-of-line) which describe the solution. Each of those c characters is an alphabetic character which is part of a word or the character *, which indicates a black square. The end of input is indicated by a line consisting of the single number 0.

45

Output
Output for each puzzle consists of an identier for the puzzle (puzzle #1:, puzzle #2:, etc.) and the list of across words followed by the list of down words. Words in each list must be output one-per-line in increasing order of the number of their corresponding denitions. The heading for the list of across words is Across. The heading for the list of down words is Down. In the case where the lists are empty (all squares in the grid are black), the Across and Down headings should still appear. Separate output for successive input puzzles by a blank line.

Sample Input
2 2 AT *O 6 7 AIM*DEN *ME*ONE UPON*TO SO*ERIN *SA*OR* IES*DEA 0

Sample Output
puzzle #1: Across 1.AT 3.O Down 1.A 2.TO puzzle #2: Across 1.AIM 4.DEN

46 7.ME 8.ONE 9.UPON 11.TO 12.SO 13.ERIN 15.SA 17.OR 18.IES 19.DEA Down 1.A 2.IMPOSE 3.MEO 4.DO 5.ENTIRE 6.NEON 9.US 10.NE 14.ROD 16.AS 18.I 20.A

BAB 5. SORTING AND SEARCHING

HINT: Keep two arrays, c[][] and n[][]. c[i][j] is the character in the ith row, jth column. n[i][j] is the crossword number in the same cell, or 0 if its an unnumbered white cell, or a black cell. Take your input into c[][], and then iterate through n[][] setting up all of the crossword numbers. Any white cell that is on the upper or left border is numbered, and any cell that has a black cell directly above or to the left of it is also numbered. Make sure you iterate through row by row and not column by column. Now, iterate through n[][] two more times. Once for Across words, and once for Down words. Any numbered cell on the left border or with a black cell directly to the left is the beginning of an Across word. Any numbered cell on the top border or with a black cell directly above it is the beginning of a Down word. When you nd such a cell, search c[][] across or down as applicable, appending every character you come across to a temporary string, and

47 stopping when you encounter the right/bottom border or a black square. Output the number of the starting cell along with your temporary string. Make sure that you print out the Across and Down headers even when the entire puzzle consists of only black squares.

5.2 The Department of Redundancy Department

Write a program that will remove all duplicates from a sequence of integers and print the list of unique integers occuring in the input sequence, along with the number of occurences of each.

Input
The input le will contain a sequence of integers (positive, negative, and/or zero). The input le may be arbitrarily long.

Output
The output for this program will be a sequence of ordered pairs, separated by newlines. The rst element of the pair must be an integer from the input le. The second element must be the number of times that that particular integer appeared in the input le. The elements in each pair are to be separated by space characters. The integers are to appear in the order in which they were contained in the input le.

Sample Input
3 1 2 2 1 3 5 3 3 2

Sample Output
3 1 2 5 4 2 3 1

48

BAB 5. SORTING AND SEARCHING

HINT: Create a dynamic array of objects that hold a value and a quantity. For each number in the input, do a standard linear search for the object that has the same value, and increment its quantity. If you cant nd one, then add a new object to the array.

5.3 Error Correction

A boolean matrix has the parity property when each row and each column has an even sum, i.e. contains an even number of bits which are set. Heres a 4 x 4 matrix which has the parity property: 1 0 1 0 0 0 1 1 1 0 1 0 0 0 1 1

The sums of the rows are 2, 0, 4 and 2. The sums of the columns are 2, 2, 2 and 2. Your job is to write a program that reads in a matrix and checks if it has the parity property. If not, your program should check if the parity property can be established by changing only one bit. If this is not possible either, the matrix should be classied as corrupt.

Input
The input le will contain one or more test cases. The rst line of each test case contains one integer n (n<100), representing the size of the matrix. On the next n lines, there will be n integers per line. No other integers than 0 and 1 will occur in the matrix. Input will be terminated by a value of 0 for n.

Output
For each matrix in the input le, print one line. If the matrix already has the parity property, print OK. If the parity property can be established

49 by changing one bit, print Change bit (i,j) where i is the row and j the column of the bit to be changed. Otherwise, print Corrupt.

Sample Input
4 1 0 1 0 4 1 0 1 0 4 1 0 1 0 0 0 0 1 1 0 0 1 1 0 1 1 1 1 0 1 0 1 1 1 0 1 1 1 0 0 0 1 1 0 0 1 1 0 0 1 1

Sample Output
OK Change bit (2,3) Corrupt Miguel A. Revilla 1999-01-11 HINT: Keep to arrays, r[] and c[] where r[i] is the sum of row i, and c[i] is the sum of column i. You can ll these in as you take in the input. It isnt necessary to store the actual matrix. Search through each array and look for cells with odd sums. If no cells have odd sums, then the matrix is OK. If one row and one column are odd, then output Change bit (row,column). Otherwise, the matrix is corrupt.

50

BAB 5. SORTING AND SEARCHING

BAB 6

Other

If you dont know what you are talking about, at least act like you do.

For

6.1 Group Reverse

Group reversing a string means reversing a string by groups. example consider a string:

TOBENUMBERONEWEMEETAGAINANDAGAINUNDERBLUEI This string has length 48. We have divided into 8 groups of equal length and so the length of each group is 6. Now we can reverse each of these eight groups to get a new string: UNEBOTNOREBMEEMEWENIAGATAGADNAEDNUNIIEULBR Given the string and number of groups in it, your program will have to group reverse it.

Input
The input le contains at most 101 lines of inputs. Each line contains at integer G (G<10) which denotes the number of groups followed by a string whose length is a multiple of G. The length of the string is not greater than 100. The string contains only alpha numerals. Input is terminated by a line containing a single zero. 51

52

BAB 6. OTHER

Output
For each line of input produce one line of output which contains the group reversed string.

Sample Input
3 ABCEHSHSH 5 FA0ETASINAHGRI0NATWON0QA0NARI0 0

Output for Sample Input


CBASHEHSH ATE0AFGHANISTAN0IRAQ0NOW0IRAN0 Problem-setter: Shahriar Manzoor Special Thanks: Derek Kisman HINT:

6.2 Testing the CATCHER

A military contractor for the Department of Defense has just completed a series of preliminary tests for a new defensive missile called the CATCHER which is capable of intercepting multiple incoming oensive missiles. The CATCHER is supposed to be a remarkable defensive missile. It can move forward, laterally, and downward at very fast speeds, and it can intercept an oensive missile without being damaged. But it does have one major aw. Although it can be red to reach any initial elevation, it has no power to move higher than the last missile that it has intercepted. The tests which the contractor completed were computer simulations of battleeld and hostile attack conditions. Since they were only preliminary, the simulations tested only the CATCHERs vertical movement capability. In each simulation, the CATCHER was red at a sequence of oensive missiles which were incoming at xed time intervals. The only information available to the CATCHER for each incoming missile was its height at the point it could be intercepted and where it appeared in the

53 sequence of missiles. Each incoming missile for a test run is represented in the sequence only once. The result of each test is reported as the sequence of incoming missiles and the total number of those missiles that are intercepted by the CATCHER in that test. The General Accounting Oce wants to be sure that the simulation test results submitted by the military contractor are attainable, given the constraints of the CATCHER. You must write a program that takes input data representing the pattern of incoming missiles for several dierent tests and outputs the maximum numbers of missiles that the CATCHER can intercept for those tests. For any incoming missile in a test, the CATCHER is able to intercept it if and only if it satises one of these two conditions: The incoming missile is the rst missile to be intercepted in this test. -orThe missile was red after the last missile that was intercepted and it is not higher than the last missile which was intercepted.

Input
The input data for any test consists of a sequence of one or more nonnegative integers, all of which are less than or equal to 32,767, representing the heights of the incoming missiles (the test pattern). The last number in each sequence is -1, which signies the end of data for that particular test and is not considered to represent a missile height. The end of data for the entire input is the number -1 as the rst value in a test; it is not considered to be a separate test.

Output
Output for each test consists of a test number (Test #1, Test #2, etc.) and the maximum number of incoming missiles that the CATCHER could possibly intercept for the test. That maximum number appears after an identifying message. There must be at least one blank line between output for successive data sets. Note: The number of missiles for any given test is not limited. If your solution is based on an inecient algorithm, it may not execute in the allotted time.

54

BAB 6. OTHER

Sample Input
389 207 155 300 299 170 158 65 -1 23 34 21 -1 -1

Sample Output
Test #1: maximum possible interceptions: 6 Test #2: maximum possible interceptions: 2 HINT: keep two arrays, one for heights and one for values. The values array at [i] will hold the maximum number of missles that could be intercepted should the set of missles end with i. Loop through your height array using a variable x, and for each element, loop from 0 to x-1 to nd the best previously shot missle (ie the one with the highest value that is still at least as high as the current). Value[x] will be the value of the best that you found + 1 or 1 if you found nothing. Output the hightest value in the value array.

6.3 The Settlers of Catan

55 Within Settlers of Catan, the 1995 German game of the year, players attempt to dominate an island by building roads, settlements and cities across its uncharted wilderness. You are employed by a software company that just has decided to develop a computer version of this game, and you are chosen to implement one of the games special rules: When the game ends, the player who built the longest road gains two extra victory points. The problem here is that the players usually build complex road networks and not just one linear path. Therefore, determining the longest road is not trivial (although human players usually see it immediately). Compared to the original game, we will solve a simplied problem here: You are given a set of nodes (cities) and a set of edges (road segments) of length 1 connecting the nodes. The longest road is dened as the longest path within the network that doesnt use an edge twice. Nodes may be visited more than once, though. Example: The following network contains a road of length 12. o o -- o o \ / \ / o -- o o -- o / \ / \ o o -- o o -- o \ / o -- o

Input
The input le will contain one or more test cases. The rst line of each test case contains two integers: the number of nodes n ( 2 n 25) and the number of edges m ( 1 m 25). The next m lines describe the m edges. Each edge is given by the numbers of the two nodes connected by it. Nodes are numbered from 0 to n-1. Edges are undirected. Nodes have degrees of three or less. The network is not neccessarily connected.

56

BAB 6. OTHER Input will be terminated by two values of 0 for n and m.

Output
For each test case, print the length of the longest road on a single line.

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

Sample Output
2 12 Miguel A. Revilla 1999-01-11

Sequel

IKAtlah ilMU iTu denGAn meNGajarkannya.

Copyleft: Hayi Nukman (2011), a Created with: L TEX.

You might also like