This action might not be possible to undo. Are you sure you want to continue?

]

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 diﬀerent colours–red, orange, yellow, green and blue–and 5 wastes have been identiﬁed for recycling–Plastic, Glass, Aluminium, Steel, and Newspaper. Obviously there has been no coordination between cities, so each city has allocated wastes to bins in an arbitrary fashion. Now that the government has solved the minor problems of today (such as 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 city’s allocation scheme should be chosen. Note that there will always be a clear winner.

**Input and Output
**

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

Sample input:

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

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

. Hayi Nukman (July 2011). a Created with: L TEX. Regards.iv • Algoritma kedua dan seterusnya boleh berupa optimalisasi dari algoritma pertama atau algoritma-algoritma sebelumnya.

. . 31 31 32 35 36 38 39 . . . . . . . . . .5 Polynomial coeﬃcients 4. . . .4 King . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Data Flow . . . . . . . 28 4 Math 4. . . . 23 3. . . . . . . . . . . . . . .1 LCM . . . . . . . . . . . . . .2 Greedy Gift Givers . . .2 The Probable n-Ascendants . . . . . . . . . . . . . . . . . . . . . . 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1. . . . . .2 The Tower of Babylon .4 The Bases Are Loaded 1. .1 The Blocks Problem . . . . . . . . . . . . . . . . . . . . . . 2. . . . . . . . . 1 Easy 1. . . . . . . . . . . . . . . .3 Number Chains . . .5 Combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Pizza Cutting . . . . . . . . . . . . . . .2 Minimum Sum LCM . i 1 1 4 6 8 9 11 11 12 14 16 20 . . 1. . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . . 2 Medium 2. . . . . . . . . . . .5 Number Maze . 3 Hard 23 3. . . . . . . v . . . . . . . . . . . . . . . . . 4. . . . . . . . . 4. . . . . . . . 2. . . . . . . . . . . . . . . . 1. . . . . . . . . . . . .4 Modular Fibonacci . . . . . . . . . . .3 Hendrie Sequence . . . .Daftar Isi Recycling . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . . . . . . . . . . .1 Lining Up . . . . . . . . . . . . . . . . .3 Poker Hands . . . . 25 3. . . . . . . . . . . . . . . . . . . .3 Points in Figures: Rectangles 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 The Department of Redundancy Department . . . . . . . . .1 Crossword Answers . . . . . . . . . . 5. . . . . . . . . .3 The Settlers of Catan . 5. .3 Error Correction . . . . . . . . 6 Other 51 6. . 54 . . . . . . . . . . . . . .vi DAFTAR ISI 43 43 47 48 5 Sorting and Searching 5. . . . . . . . .2 Testing the CATCHER . . . . . .1 Group Reverse . . . . . . . . . . . . . . . . . 51 6. . . . . . . . 52 6. . . . . . . . .

BAB 1

Easy

“

Go for the happy endings, because life doesn’t 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 speciﬁed 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

2

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 aﬀect on the conﬁguration 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 speciﬁed 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. Don’t 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:

However. 1. you are to write a program that determines how much more (or less) each person in the group gives than they receive. the number of people to whom gifts are given. for a group of gift-giving friends. . and the names of those to whom gifts are given. the amount of money spent on gifts. and a (sub)list of friends to whom each person gives gifts.2 Greedy Gift Givers The Problem This problem involves determining. • 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. Given a group of friends. and a[i][j] = −1 for all j > 0. how much more each person gives than they receive (and vice versa for those that view gift-giving with cynicism). Money is a non-negative integer less than 2000. Then just implement the four functions carefully. there are no more than 10 people in a group. The Input The input is a sequence of gift-giving groups. some people are more giving than others (or at least may have more acquaintances) and some people have more money than others. a[i][0] = i for all i.4 BAB 1. in any group of friends. 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. and no name is more than 12 characters in length. All names are lower-case letters. A group consists of several lines: • the number of people in the group. EASY Use a two dimensional array where a[i][j] is the jth block in the ith stack. the money each person in the group spends on gifts.

Names in a group should be printed in the same order in which they ﬁrst appear in the input. Each person gives the same integer amount of money to each friend to whom any money is given. All gifts are integers. The Output For each group of gift-givers. 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 . Any money not given is kept and is part of a person’s “net worth” printed in the output.5 The input consists of one or more groups and is terminated by endof-ﬁle. The output for each group should be separated from other groups by a blank line. and gives as much as possible. 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.

we can form a number chain by 1.ratio += person(a). subtracting the number obtained in (2) from the number obtained (1) to form a new number 4. just loop through your list of people (p) and: person(a). . 1. one person class solves all your problems: class person -----int ratio -----int money -----string name make an array of them. When it comes time to take a person’s (a) friends in. You are to write a program that reads numbers and outputs the number chain and the length of that chain for each number read.money/friends(a) go through the people array once more. arranging its digits in ascending order 3. EASY HINT: Just use some Object Oriented programming.money/friends(a) person(p). arranging its digits in descending order 2.6 steve -24 dave 27 BAB 1. 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.ratio -= person(a).3 Number Chains Given a number. outputting the ratio and their name. and take all the information in.

7 Input and Output The input consists of a sequence of positive numbers. including the last one. The output consists of the number chains generated by the input numbers.123456789 = 864197532 987654321 . there should be a blank line.123456789 = 864197532 Chain length 2 Original number was 1234 4321 . each on its own line.1467 = 6174 Chain length 4 Original number was 444 444 .1234 = 3087 8730 . all less than 109 . terminated by 0. followed by their lengths exactly in the format indicated below. No chain will contain more than 1000 distinct numbers. Sample Input 123456789 1234 444 0 Sample Output Original number was 123456789 987654321 .378 = 8352 8532 . After each number chain and chain length. The input ﬁle contains at most 5000 numbers.444 = 0 0 .2358 = 6174 7641 .0 = 0 Chain length 2 HINT .

1.g. The second value is a positive integer indicating the base we wish to convert to. then stop processing and print out the length of the chain (which should be the number of elements in p[] +/.8 BAB 1. Then iterate through the array backwards and convert the digits into another number. search for it in p[]. EASY For each number n in the chain. It will not exceed 10 characters.1 depending on how you implemented it). The ﬁrst value will be a positive integer indicating the base of the number. transfer it to an integer array where a[i] is the ith digit of n. If you don’t ﬁnd it.. followed by the original base number. Subtract the former from the latter to generate your next n. Sort the array ascending and convert the individual digits back into a complete number. 15 by F. If you do ﬁnd it. Each of the input values on a single line will be separated by at least one space. followed by the string “=” followed by the converted number followed by the string “base” followed by the new base. output the statement original Value is an illegal base original Base number . This number will have letters representing any digits higher than 9 and may contain invalid “digits”. Whenever you generate a new n.16) to a whole number in any other base (2. Input Each input line will consist of three values..4 The Bases Are Loaded Write a program to convert a whole number speciﬁed in any base (2. etc. 10 by A.16). Keep an array p[] that holds all values previously reached. add it in. The third value is the actual number (in the ﬁrst base) that we wish to convert. Output Program output consists of the original number followed by the string “base”. e. If the original number is invalid. “Digits” above 9 are represented by single capital letters.

Note that you must use longs as ints are too small for some of the inputs. and M ≤ N Compute the EXACT value of: .parseLong to do the base conversion. Challenges are the stuﬀ of contests. If you’re using Java. which indicate that the number contains invalid characters. you are to make just such a computation given the following: GIVEN: 5 ≤ N ≤ 100. Therefore. Basically. and then convert it into the ﬁnal base. 1. Check for invalid characters. check that only the characters in the set {0123456789ABCDEF} are used. you can use Long. and you can catch NumberFormatExceptions. and 5 ≤ M ≤ 100. 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 that the number is legal in the given base. which may be things like lowercase letters or punctuation.9 where original Value is replaced by the value to be converted and original Base is replaced by the original base value.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.

Your program should terminate when this line is read.286.944.217.000.518.681.238.10 N! (N − M )! × M ! BAB 1.968. 20 things taken 5 at a time is 15504 exactly.592.827.223.000. the exact value of 100! is: 93.700. 18 things taken 6 at a time is 18564 exactly.215.000.697.152.381. 915. one or more spaces.993.266. M pair with both values equal to zero.326. 758.976.490.916. Sample Input 100 20 18 0 6 5 6 0 Sample Output 100 things taken 6 at a time is 1192052400 exactly.000. 715. and a value for M. a value for N.864.621.599. .856.920.156. The output from this program should be in the form: N things taken M at a time is C exactly.699.251.895.264.185.000 Input and Output The input to this program will be one or more lines each containing zero or more leading spaces.463.000.253.963.443.000.468. For the record. EASY C= You may assume that the ﬁnal value of C will ﬁt in a 32-bit Pascal LongInt or a C long.000.608. The last line of the input ﬁle will contain a dummy N.941.229.210.

The 11 . The pilot wanted to know the largest number of points from the given set that all lie on one line. Output For each test case. Indeed. No pair will occur twice. the pilot was not facing an easy task. The outputs of two consecutive cases will be separated by a blank line. the output must follow the description below. each of them as described below. Can you write a program that calculates this number? Your program has to be eﬃcient! Input The input begins with a single positive integer on a line by itself indicating the number of the cases following. where 1 < N < 700. She had to drop packages at speciﬁc points scattered in a dangerous area. This line is followed by a blank line. Furthermore.1 Lining Up “How am I ever going to solve this problem?” said the pilot.BAB 2 Medium “ STUPID = Smart Talented Unique Person In Demand ” 2. and there is also a blank line between two consecutive inputs. the pilot could only ﬂy over the area once in a straight line. The list of pairs is ended with an end-of-ﬁle character. All points were given by means of integer coordinates in a two-dimensional space. The input consists of N pairs of integers. Each pair of integers is separated by one blank and ended by a new-line character. and she had to ﬂy over as many points as possible.

that blocks oriented to have equal-sized bases . yi . we will tell you the whole story: The babylonians had n types of blocks. Sample Input 1 1 1 2 2 3 3 9 10 10 11 Sample Output 3 HINT: computational geometry. Try an O(n2 logn) algorithm. They wanted to construct the tallest tower possible by stacking blocks. zi ) . The problem was that. in building a tower. for example. and an unlimited supply of blocks of each type. 2. So now. This meant. MEDIUM output consists of one integer representing the largest number of points that all lie on one line. Nowadays many details of this tale have been forgotten. 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. sorting. in line with the educational nature of this contest. Each type-i block was a rectangular solid with linear dimensions (xi .2 The Tower of Babylon Perhaps you have heard of the legend of the Tower of Babylon.12 BAB 2. line gradients (slopes). 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.

Input is terminated by a value of zero (0) for n. 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 . 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. Each of the next n lines contains three integers representing the values xi . For each test case. The maximum value for n is 30. Input and Output The input ﬁle will contain one or more test cases.yi and zi . representing the number of different blocks in the following data set. The ﬁrst line of each test case contains an integer n.13 couldn’t be stacked.

one per line. maximize (a[u][v] + h[v]) across all (u. LIS (nonstandard). because you can use Floyd-Warshall with the bounds of this problem.14 BAB 2. Input There will be n( ≤ 10) rectangles descriptions. other graph. but for DAG it’s just ﬁne. Let the weight of edge (u. and that’s much easier that doing LIS. run Floyd-Warshall. . 2. and -Inf otherwise.. if u ﬁts on top of v. wasley: There are two main ways to do this problem. This character will be followed by four real values designating the x-y coordinates of the upper left and lower right corners. DP. At the end. 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.v) where h[v] is the height of block v (because we didn’t add that during Floyd). or ﬁnding the longest path in a DAG. determine for each point which ﬁgures (if any) contain the point. For an arbitrary graph this won’t work. but with max instead of min.. ﬂoyd warshall. Then. either Longest Increasing Subsequence. The ﬁrst character will designate the type of ﬁgure (“r” for rectangle).v) be the height of block u. I prefer the latter.3 Points in Figures: Rectangles Given a list of rectangles and a list of points in the x-y plane.

8 9999.5 r 0.5 17. Sample Input r 8.5 12.0 r 2. Points coinciding with a ﬁgure border are not considered inside. 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.5 0.3 6. The end of this list will be indicated by a point with coordinates 9999. write a message of the form: Point i is contained in figure j for each ﬁgure that contains that point.0 17. The remaining lines will contain the x-y coordinates.2 -5.9 Sample Output Point 1 is contained in figure 2 Point 2 is contained in figure 2 .7 5. of the points to be tested.9 9999.9 9999. Output For each point to be tested.0 20.0 25.0 2.0 10.9 11.2 -7.9.5 -8.15 The end of the list will be signalled by a line containing an asterisk in column one. one per line.5 12.5 2. If the point is not contained in any ﬁgure.2 20.6 3.5 * 2.0 4. these values should not be included in the output.3 5.

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

He ordered to his advisors to ﬁnd such a sequence S that would satisfy the constraints he set. After a while he realized that some of his decisions were wrong. a2 . Help the advisors of the king and write a program that decides whether such a sequence exists or not. the young king began to reign. Input The input ﬁle consists of blocks of lines. After the old king died. The king thought a minute and then decided. in one kingdom. an upper or lower limit) for the sum of that sequence. The queen prayed: “If my child was a son and if only he was a sound king. an }.” After nine months her child was born. . The set of problems was in the form of subsequences Si = {asi . there was a queen and that queen was expecting a baby. 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. . the numbers had to be written in a sequence and he was able to sum just continuous subsequences of the sequence. . i.e. a lot of people became very unsatisﬁed with his decisions and decided to dethrone him. Each block except the last corresponds to one set of problems and king’s decisions about them. asi +1 . Therefore some conspirators presented to the young king a set of problems that he had to decide about. But he was ready to make everything to enable his son to govern the kingdom after his death. . and indeed. He could not revoke the declared constraints but trying to save himself he decided to fake the sequence that he was given. Unfortunately. In . the son was a little retarded. They tried to do it by proving that his decisions were wrong. . asi + asi +1 + · · · + asi +ni < ki or asi + asi +1 + · · · + asi +ni > ki resp. With regards to his son’s 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. he set for the sum asi + asi +1 + · · · + asi +ni of each subsequence Si an integer constraint ki (i. But very soon. as it used to happen in royal families.17 Once. In addition. In this way there was at least some hope that his son would be able to make some decisions. .e.e.) and declared these constraints as his decisions. she gave birth to a nice son. The old king was very unhappy of his son. . asi +ni } of a sequence S = {a1 . .

There is no line in the output ﬁle corresponding to the last “null” block of the input ﬁle. oi. ni and ki have the meaning described above. Output The output ﬁle contains the lines corresponding to the blocks in the input ﬁle. where oi represents operator > (coded as gt) or operator < (coded as lt) respectively. Next m lines contain particular decisions coded in the form of quadruples si. Otherwise it contains text lamentable kingdom. ni.18 BAB 2. A line contains text successful conspiracy when such a sequence does not exist. MEDIUM the ﬁrst line of the block there are integers n. ki. 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: . The symbols si. The last block consists of just one line containing 0. and m where 0 < n ≤ 100 is length of the sequence S and 0 < m ≤ 100 is the number of subsequences Si.

. graph theory. A system of diﬀerence 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. we can rewrite the constraint xk + xk+1 + . the constraints given in this problem are not of this form. and an edge from x2 to x1 with weight C for each constraint. to change the strict inequalities into non-strict inequalities. They contain multiple variables. all you have to do is create the graph.19 math. are sums rather than additions. 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. and have strict inequalities. other graph. note that. BellmanFord.. we can convert them. Let a[i] be the sum of the ﬁrst i variables in the sequence (a[0] = 0). Luckily. However. . diﬀerence constraints. There exists a solution that satisﬁes all of the constraints iﬀ the graph does not contain a negative weight cycle. Since all of the constraints relate contiguous subsequences. and run Bellman-Ford (or so) to detect a negative weight cycle. + xk+h < / > C as a[k + h] − a[k − 1] < / > C Now. This is a constraint satisfaction problem that can be solved with negative cycle detection.

M. N. north. one per each row of the maze.20 BAB 2. Sample Input 2 4 5 0 3 1 2 9 7 3 4 9 9 . output one line with the required minimum value. south. as exempliﬁed below.. Output For each maze. The maze can be traversed following any orthogonal direction (i. one line with the number of columns. then ﬁnding the minimum cost to travel the maze from one entry point to an exit point may pose you a reasonable challenge. containing the maze numbers separated by spaces. MEDIUM 2.5 Number Maze Consider a number maze represented as a two dimensional array of numbers comprehended between 0 and 9. and N lines. Note that the solution for the given example is 24. M ≤ 999. Input The input ﬁle contains several mazes. Considering that each cell represents a cost.e. 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 . east and west). The ﬁrst input line contains a positive integer deﬁning the number of mazes that follow. Each maze is deﬁned by: one line with the number of rows.

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

MEDIUM .22 BAB 2.

at any instant more than one unit of data cannot travel parallel through the network. Each node has suﬃcient buﬀering capability so that data can be temporarily stored there. 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. IIUC management wants the shortest possible time to send all the data from the local server to the ﬁnal one. This may be time consuming but it certainly gives no collision. it requires to send huge amount of data from the local server to the terminal server. not harder ” In the latest Lab of IIUC. 23 . The problem is all links of the network has a ﬁxed capacity and cannot ﬂow more than that amount of data. It requires to write a router program for the best path of data.1 Data Flow Think smarter. The lab setup is not yet ready.BAB 3 Hard “ 3.e.

K where D is the amount of data to be transferred from 1st to N’th node and K is the link capacity. in the above network if anyone wants to send 20 unit data from A to D. HARD For example. Input Each input starts with two positive integers N (2 N 100). Output For each dataset.”. If it is not possible to send all the data. print ”Impossible. The links are bidirectional and there will be at most one link between two network nodes. M (1 M 5000).24 BAB 3. In next line there will be two positive integers D. print the minimum possible time in a line to send all the data. 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. In next few lines the link and corresponding propagation time will be given. The time can be as large as 1015. Sample Input and Output Problemsetter: Md. Kamruzzaman Member of Elite Problemsetters’ Panel . Input is terminated by EOF.

Basically. You can do Bellman-Ford. Luckily. max ﬂow. because there are no negative costs to begin with. it’s the combination of shortest path and maximum ﬂow.com/tc?module=Static&d1=tutorials &d2=minimumCostFlow2 3. Read the subsection ”Successive Shortest Path Algorithm”: http://www.25 HINT: dijkstra. you don’t need Bellman-Ford at all. but it doesn’t matter much runtime-wise. but you replace the BFS with a weighted shortest path algorithm. 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. When a pair of genes presents diﬀerent information for one characteristic. except that the graph will have negative costs after you reverse edges. each characteristic of one individual is determined by a pair of genes (a gene is a part of a chromosome). The general idea is not too diﬃcult.topcoder. but unfortunately that’s too slow for this problem (unless you’re lucky in C perhaps). other graph This is a minimum-cost maximum ﬂow problem. You do Edmonds-Karp to get the maximum ﬂow. In this problem. the dominance of one gene over the other naturally inﬂuences the way an individual externally presents that characteristic. and you can use Dijkstra to initialize the graph. Dijkstra is the best choice. I suggest reading the following to understand how this ”graph initialization” part works.2 The Probable n-Ascendants In the biological autosomic inheritance. . there exists a compromise.

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

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. or its great-grand-parents (3-ascendants).0% . Consecutive test cases are separated by a single blank line.0% BBww 40. Assume the maximum value of n is 35. > wwwB > wwww. The outputs of two consecutive cases will be separated by a blank line. 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. each one containing the concatenated genes of each member of the possible pair of n-ascendants. Output For each test case. Sample Input Bw 1 ww 8 Sample Output BBBw 20. or its grand-parents (2-ascendants).. The second line contains the value of n. truncated to 2 fractional digits. i. The ﬁrst line of the input contains the genes of the guinee-pig for whom you want to know the probable n-ascendants.e. The output is a list of lines.27 its parents (1-ascendants). followed by the corresponding probability. each of them as described below. considering BBBB > BBBw > BBwB > . the output must follow the description below. The concatenation of the 2 pair of n-ascendant genes must ensure that the resultant string is the biggest one. Input The input will contain several test cases... the level of ascendant generation that you want to study.

67% 17. H. 6.75% BAB 3. Hands with the same highest pair are ranked by the value of their other pair. For scoring purposes. 7. with 2 being the lowest and ace the highest value. 10.28 BwBw 20.12% 16. • Pair: 2 of the 5 cards in the hand have the same value. 4. K. D. and S in the input data). diamonds. If these values are the same.0% Bwww 20. 5. 9. 8. king. 3. the hands are ranked by the values of the cards not forming the pair. A). 5. If these values are the same the hands are ranked by the value of the remaining card. 6. • Two Pairs: The hand contains 2 diﬀerent pairs. Hands which both contain 2 pairs are ranked by the value of their highest pair. Hands which both contain a pair are ranked by the value of the cards forming the pair.3 Poker Hands A poker deck contains 52 cards . 4. 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. ace (denoted 2. HARD University of Porto / 2003 ACM Programming Contest / Round 2 / 2003/09/24 3. If the highest cards have the same value. or spades (denoted C. in decreasing order.0% BBBB BBBw BBww BwBw Bwww wwww 15. A poker hand consists of 5 cards dealt from the deck. T. hearts. the hands are ranked by the next highest. J. 7. 8. . queen. 9.67% 16.58% 16. Each card also has a value which is one of 2.21% 17.each card has a suit which is one of clubs. 3. Q. and so on. the suits are unordered while the values are ordered as given above. jack.

29 • Three of a Kind: Three of the cards in the hand have the same value. 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”. with the remaining 2 cards forming a pair. Your job is to compare several pairs of poker hands and to indicate which. Input The input ﬁle contains several lines. • Straight: Hand contains 5 cards with consecutive values. Tie. if either. Output For each line of input. • Flush: Hand contains 5 cards of the same suit. • Straight ﬂush: 5 cards of the same suit with consecutive values. Hands which both contain a straight are ranked by their highest card. has a higher rank. Ranked by the value of the 4 cards. Hands which are both ﬂushes are ranked using the rules for High Card. Ranked by the highest card in the hand. Ranked by the value of the 3 cards. 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 . • Full House: 3 cards of the same value. Hands which both contain three of a kind are ranked by the value of the 3 cards. • Four of a kind: 4 cards with the same value. print a line containing one of the following three lines: Black wins. White wins.

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

Input Each line contains one nonzero positive integer which is not greater than 1000000. ” 4. Sample Input 3 5 31 .BAB 4 Math “ I couldn’t repair your brakes. so I just made your horn louder. LCM of 2. For example LCM of 4 and 6 is 12. Last line will contain zero indicating the end of input. print in a line the last nonzero digit of LCM of ﬁrst 1 to N integers. 3. Output For each line of input. So we are not interested in the exact value of the LCM but we want to know the last nonzero digit of that. The LCM of ﬁrst 6 numbers is 60. You will need to process maximum 1000 lines of input. As you will see LCM will increase rapidly with N. LCM can also be deﬁned for more than 2 integers.1 LCM All of you know about LCM (Least Common Multiple). And you have to ﬁnd that eﬀeciently. This line should not be processed. 5 is 30. In the same way we can deﬁne LCM of ﬁrst N integers.

j. P (a2 ). Kamruzzaman. Intuitively. 5. this means that you need ”enough” of each prime factor in the LCM to ”satisfy” each of the numbers. Member of Elite Problemsetters’ Panel Special thanks to: Mohammad Sajjad Hossain HINT: Let P(n) be the multiset of prime factors of n. so we don’t want to actually store the entire LCM in a[]. check if the count of each factor. Keep an array c[] where c[j] is the number of times you’ve used j as a factor in your LCM so far. if our LCM was 182158203800000000.. When you factorize i+1. . So. a2 . To determine a[i + 1]... This can be accomplished by the following code: while(a[i] % 10 == 0) --. Instead. P(60) = 2. we store the last 7 or so digits before the ﬁnal string of zeros. . MATH Output for Sample Input 6 6 2 Problemsetter: Md. So. Let a[i] be the LCM of the numbers from 1 to i. factorize i + 1.a[i] /= 10 a[i] %= 10000000 We keep 7 digits because the largest number we might multiply a[i] by is 6 digits long. Now.. then see if you need any of its factors. P (an ). multiply your current LCM by j until the count is satisﬁed. a3 .. The LCM of a set of numbers a1 . is greater than c[j]. the LCM grows very quickly. an is the product of the intersection of P (a1 ). If it is.2 Minimum Sum LCM .32 10 0 BAB 4. 3. we would store ”1582038” in a[]. 2. 4..

which is a multiple of all integers of that set. Sample Input 12 10 5 0 Sample Output Case 1: 7 Case 2: 7 Case 3: 6 . In this problem. We will be quite happy if you just print the summation of the elements of this set. Output Output of each test case should consist of a line starting with ‘Case #: ’ where # is the test case number. 6 or 1. 2. 12 or 3. 4 or 4. Each test case consists of a positive integer N ( 1≤N≤231 .33 LCM (Least Common Multiple) of a set of integers is deﬁned as the minimum number. 3. Look at the output for sample input for details. It should be followed by the summation as speciﬁed in the problem statement. It is interesting to note that any positive integer can be expressed as the LCM of a set of positive integers. So.1). you have to pick the sequence whose summation of elements is minimum. Input is terminated by a case where N = 0. There can be at most 100 test cases. This case should not be processed. You have to ﬁnd out a set of at least two positive integers whose LCM is N. 4 etc. you will be given a positive integer N. 12 or 12. for N = 12. For example 12 can be expressed as the LCM of 1. As inﬁnite such sequences are possible. Input The input ﬁle contains at most 100 test cases. you should print 4+3 = 7 as LCM of 4 and 3 is 12 and 7 is the minimum possible summation.

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

Input is terminated with a line containing the number ‘0’ which of course should not be processed. given n.4. Input Each test case consists of a single line containing the integer n ( 0 < n < 263 ) . the resulting sequence is still H (without its ﬁrst element).1.0.0.0. calculates the nth element of H.3.35 4.2.0. Thus.0..0.1. Sample Input 4 7 44 806856837013209088 0 Sample Output 2 0 3 16 .1. output the nth element of H on a single line.3 Hendrie Sequence The Hendrie Sequence “H” is a self-describing sequence deﬁned as follows: • H(1) = 0 • If we expand every number x in H to a subsequence containing x 0’s followed by the number x + 1.. the ﬁrst few elements of H are: 0..2.0.0.1.0. Output For each test case.1. You must write a program that.0.3.

Canada HINT: The sequence. We add up the lengths of the subblocks. Also. the ith block consists of (i-2) pieces from prior blocks. n. we use k = floor(log2(n)) to determine which block n belongs to. in which case the ﬁrst 2(k−i−1) should be set to 0. Note that (k − i − 1) can be < 0. and the latter should be set to 1. I would suggest doing everything in longs to avoid rounding 63 errors. 4. when then actual value is log(2) slightly less than 63.36 BAB 4. For example. We can now simplify n down to 2(k−i−1) + (n − 2k − 1)%(2(k−i−1) ) + 1. and then the number i-1.4 Modular Fibonacci . 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(i−2) (excepting the ﬁrst block which has length 1). and recurse on this new value. is a perfect power of 2. i × 2(k−i−1) for i from 1 to k until the cumulative sum is greater than or equal to (n − 2k ). MATH Problem setter: Derek Kisman. we just return log2(n). 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 deﬁned in terms of the block before it. Otherwise. Be wary of double precision as it isn’t quite good enough for this problem. For instance. log(2 −1) gives 63. University of Waterloo. The index i at which we stop is the number of the subblock that n belongs to. strategically broken up into blocks. If the number given. the ﬁrst 10 values of the sequence or so). we can write a recursive function that simpliﬁes the problem down until it reaches a known value (say. n − 2k is how far along the block n is.

) are deﬁned by the recurrence: F0 = 0 F1 = 1 Fi = Fi−1 + Fi−2 → f or(i) > 1 Write a program which calculates Mn = Fn mod 2m for given pair of n and m. 13. We can use these formulas along with an algorithm that does O(log n) exponentiation to come up with the answer.37 The Fibonacci numbers (0. 1. one per line. 34. we can derive: F2n = Fn × (Fn + 2Fn−1 ) 2 2 F2n−1 = Fn + Fn−1 depending on whether the number is even or odd. 55. Output should be corresponding Mn. . The algorithm works oﬀ of the idea that you can do the following matrix multiplication: [ ] [ ] 1 1 Fn+1 Fn = Fn Fn−1 1 0 and you will get the next set of Fibonacci numbers. 0 ≤ n ≤ 2147483647 and 0 ≤ m < 20. 8. 2. Note that a mod b gives the remainder when a is divided by b.. 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.. Input and Output Input consists of several lines specifying a pair of n and m. Thus. 1. 3. 5. 21. Take mod m after every addition and .

+ nk = n.. The ﬁrst line of the pair consists of two integers n and k separated with space (0 < K. 4. the coeﬃcient by the monomial xn1 xn2 . The second line in each pair consists of k non-negative integers n1 . N < 13)... Sample Input 2 1 2 1 2 1 12 0 0 0 0 0 0 0 0 0 1 0 Sample Output 2 2 .. + xk )n .... MATH multiplication to keep the numbers small.. This integers deﬁne the power of the polynomial and the amount of the variables.. and 240 won’t ﬁt in an int. + xk )n . ..xnk in expansion of the polynomial 1 2 k (x1 + x2 + .38 BAB 4. where n1 + .5 Polynomial coeﬃcients The Problem The problem is to calculate the coeﬃcients in expansion of polynomial (x1 + x2 + . The Output For each input pair of lines the output line should consist one integer. The Input The input will consist of a set of pairs of lines. nk .. and use longs because you may need to square numbers as large as 220 .

rather this is his intellectual smartness.. which we can then simplify into a simple ﬁnal form: n! n1 ! × n2 ! × . In fact. + xk − 1) + xk )n k ∑ i=1 (nCi) × (x1 + . Accordingly.) He thought a bit. why should he exert more? He also claims that he always uses his brain and tries to do some work at less eﬀort.39 HINT: Let n(k) be the power of the kth term in the monomial we’re asked to examine.. We keep breaking this down recursively until we end up with a product of Chooses. he cut the pizza in the following way (guess which one is Ivan’s piece): . he claims that it is his intelligence that helps him to be so. If his intelligence allows him to do something at less physical eﬀort. his piece will be larger than the others. we can break it up using the binomial theorem: ((x1 + ..6 Pizza Cutting When someone calls Ivan lazy. + xk − 1)n − i × xi k The only term we care about is where i = n(xk). 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. Given the polynomial (x1 + x2 + . × nk ! 4. Once Ivan was asked to cut a pizza into seven pieces to distribute it among his friends... this is not his laziness... (Size of the pieces may not be the same. so we can through away the rest.. + xl )n .

and output a number representing the maximum number of pizza pieces it will produce. MATH One of his friends.40 BAB 4. Output Output the maximum number of pizza pieces the given number of cuts can produce. why can’t my computer? So he tried to do a similar (but not exactly as Ivan’s. who never believed in Ivan’s smartness. He wrote a program that took the number of straight cuts one makes through the pizza. for Ivan will criticize him for stealing his idea) job with his computer. 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. was startled at this intelligence. Each line should contain only one output integer without any leading or trailing space. if Ivan can do it. Your job here is to write a similar program. It is ensured that Ivan’s friend won’t criticize you for doing the same job he did. He thought. Sample Input 5 10 -100 . A negative number terminates the input.

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

MATH .42 BAB 4.

” No other squares are numbered. one writes the words corresponding to the deﬁnitions on the white squares of the grid. The picture below illustrates a rectangular crossword puzzle grid with appropriate numbering.) To solve a crossword puzzle. All of the squares on the ﬁrst row are numbered.” White squares with no squares either immediately to the left or above are also “eligible. One list of deﬁnitions 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. White squares with black squares immediately to the left or above them are “eligible. The numbering starts with 1 and continues consecutively across white squares of the ﬁrst row. The deﬁnitions correspond to the rectangular grid by means of sequential integers on “eligible” white squares. 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. 43 . ” 5. (A word is a sequence of alphabetic characters.1 Crossword Answers A crossword puzzle consists of a rectangular grid of black and white squares and two lists of deﬁnitions (or descriptions).BAB 5 Sorting and Searching “ Being Stupid isn’t as easy as it may look.

The end of input is indicated by a line consisting of the single number 0. . The r rows of input which follow each contain c characters (excluding the end-of-line) which describe the solution. Every white square in a correctly solved puzzle contains a letter.44 BAB 5. which indicates a black square. where r (the ﬁrst number) is the number of rows in the puzzle and c (the second number) is the number of columns. Each of those c characters is an alphabetic character which is part of a word or the character “*”. Input Each puzzle solution in the input starts with a line containing two integers r and c ( 1 ≤ r ≤ 10 and 1 ≤ c ≤ 10 ). ending immediately before the next black square in the row or in the rightmost square of the row. The sequence of white squares for that word goes across the row of the numbered square. SORTING AND SEARCHING An “across” word for a deﬁnition 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. ending immediately before the next black square in the column or in the bottom square of the column. 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. The sequence of white squares for that word goes down the column of the numbered square. A “down” word for a deﬁnition 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.

DEN .AT 3. Separate output for successive input puzzles by a blank line. puzzle #2:.45 Output Output for each puzzle consists of an identiﬁer for the puzzle (puzzle #1:. The heading for the list of across words is “Across”.AIM 4. etc.TO puzzle #2: Across 1. 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.O Down 1. In the case where the lists are empty (all squares in the grid are black).A 2. The heading for the list of down words is “Down”. Words in each list must be output one-per-line in increasing order of the number of their corresponding deﬁnitions.) and the list of across words followed by the list of down words. the Across and Down headings should still appear.

ENTIRE 6.TO 12. or 0 if it’s an unnumbered white cell.DEA Down 1.SO 13.MEO 4.OR 18. and then iterate through n[][] setting up all of the crossword numbers.UPON 11.IES 19.A 2. Once for Across words.ONE 9. and . iterate through n[][] two more times. n[i][j] is the crossword number in the same cell.46 7. appending every character you come across to a temporary string.NEON 9. and any cell that has a black cell directly above or to the left of it is also numbered. or a black cell. When you ﬁnd such a cell. SORTING AND SEARCHING HINT: Keep two arrays. Any numbered cell on the top border or with a black cell directly above it is the beginning of a Down word.I 20. Take your input into c[][]. Any white cell that is on the upper or left border is numbered.NE 14.AS 18.ME 8. jth column.SA 17. Any numbered cell on the left border or with a black cell directly to the left is the beginning of an Across word. c[][] and n[][]. c[i][j] is the character in the ith row.US 10. and once for Down words. Make sure you iterate through row by row and not column by column.ERIN 15.IMPOSE 3.A BAB 5.ROD 16.DO 5. search c[][] across or down as applicable. Now.

The integers are to appear in the order in which they were contained in the input ﬁle.47 stopping when you encounter the right/bottom border or a black square. The input ﬁle may be arbitrarily long. separated by newlines. 5. Output The output for this program will be a sequence of ordered pairs.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. Make sure that you print out the Across and Down headers even when the entire puzzle consists of only black squares. The elements in each pair are to be separated by space characters. Sample Input 3 1 2 2 1 3 5 3 3 2 Sample Output 3 1 2 5 4 2 3 1 . The ﬁrst element of the pair must be an integer from the input ﬁle. along with the number of occurences of each. Input The input ﬁle will contain a sequence of integers (positive. The second element must be the number of times that that particular integer appeared in the input ﬁle. and/or zero). Output the number of the starting cell along with your temporary string. negative.

print one line. do a standard linear search for the object that has the same value.e. and increment its quantity. The ﬁrst line of each test case contains one integer n (n<100). there will be n integers per line. If the parity property can be established . SORTING AND SEARCHING HINT: Create a dynamic array of objects that hold a value and a quantity. 2. i. contains an even number of bits which are set. On the next n lines. If this is not possible either. Your job is to write a program that reads in a matrix and checks if it has the parity property. your program should check if the parity property can be established by changing only one bit. Here’s 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. Input will be terminated by a value of 0 for n. 2 and 2. If you can’t ﬁnd one. The sums of the columns are 2.3 Error Correction A boolean matrix has the parity property when each row and each column has an even sum. 0. then add a new object to the array. representing the size of the matrix. Input The input ﬁle will contain one or more test cases. For each number in the input. 5. the matrix should be classiﬁed as corrupt. print “OK”. 4 and 2.48 BAB 5. If the matrix already has the parity property. No other integers than 0 and 1 will occur in the matrix. Output For each matrix in the input ﬁle. If not.

49 by changing one bit. If no cells have odd sums.j)” where i is the row and j the column of the bit to be changed. then output ”Change bit (row. the matrix is corrupt.3) Corrupt Miguel A. 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. You can ﬁll these in as you take in the input.column)”. r[] and c[] where r[i] is the sum of row i. and c[i] is the sum of column i. then the matrix is OK. It isn’t necessary to store the actual matrix. . Search through each array and look for cells with odd sums. Revilla 1999-01-11 HINT: Keep to arrays. If one row and one column are odd. Otherwise. print “Change bit (i. Otherwise. print “Corrupt”.

SORTING AND SEARCHING .50 BAB 5.

example consider a string: “TOBENUMBERONEWEMEETAGAINANDAGAINUNDERBLUEI” This string has length 48. The length of the string is not greater than 100. Input is terminated by a line containing a single zero. at least act like you do. Now we can reverse each of these eight groups to get a new string: “UNEBOTNOREBMEEMEWENIAGATAGADNAEDNUNIIEULBR” Given the string and number of groups in it. The string contains only alpha numerals.1 Group Reverse Group reversing a string means reversing a string by groups.BAB 6 Other “ If you don’t know what you are talking about. your program will have to group reverse it. 51 . Input The input ﬁle contains at most 101 lines of inputs. ” For 6. We have divided into 8 groups of equal length and so the length of each group is 6. 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.

52 BAB 6. In each simulation. Since they were only preliminary. and downward at very fast speeds.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 oﬀensive missiles. laterally. Although it can be ﬁred to reach any initial elevation. the simulations tested only the CATCHER’s vertical movement capability. The CATCHER is supposed to be a remarkable defensive missile. it has no power to move higher than the last missile that it has intercepted. Sample Input 3 ABCEHSHSH 5 FA0ETASINAHGRI0NATWON0QA0NARI0 0 Output for Sample Input CBASHEHSH ATE0AFGHANISTAN0IRAQ0NOW0IRAN0 Problem-setter: Shahriar Manzoor Special Thanks: Derek Kisman HINT: 6. It can move forward. and it can intercept an oﬀensive missile without being damaged. 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 . the CATCHER was ﬁred at a sequence of oﬀensive missiles which were incoming at ﬁxed time intervals. OTHER Output For each line of input produce one line of output which contains the group reversed string. But it does have one major ﬂaw. The tests which the contractor completed were computer simulations of battleﬁeld and hostile attack conditions.

That maximum number appears after an identifying message. Input The input data for any test consists of a sequence of one or more nonnegative integers.) and the maximum number of incoming missiles that the CATCHER could possibly intercept for the test. all of which are less than or equal to 32.767. If your solution is based on an ineﬃcient algorithm. The last number in each sequence is -1. 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. etc. it is not considered to be a separate test. The end of data for the entire input is the number -1 as the ﬁrst value in a test. it may not execute in the allotted time. There must be at least one blank line between output for successive data sets. . the CATCHER is able to intercept it if and only if it satisﬁes one of these two conditions: The incoming missile is the ﬁrst missile to be intercepted in this test. which signiﬁes the end of data for that particular test and is not considered to represent a missile height. For any incoming missile in a test. The General Accounting Oﬃce wants to be sure that the simulation test results submitted by the military contractor are attainable. Output Output for each test consists of a test number (Test #1. -orThe missile was ﬁred after the last missile that was intercepted and it is not higher than the last missile which was intercepted. Note: The number of missiles for any given test is not limited. given the constraints of the CATCHER. You must write a program that takes input data representing the pattern of incoming missiles for several diﬀerent tests and outputs the maximum numbers of missiles that the CATCHER can intercept for those tests.53 sequence of missiles. representing the heights of the incoming missiles (the test pattern). Each incoming missile for a test run is represented in the sequence only once. Test #2.

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. The values array at [i] will hold the maximum number of missles that could be intercepted should the set of missles end with i. one for heights and one for ’values’. Output the hightest value in the value array. Value[x] will be the value of the ’best’ that you found + 1 or 1 if you found nothing.3 The Settlers of Catan . 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). 6.54 BAB 6. Loop through your height array using a variable x.

o o -. Each edge is given by the numbers of the two nodes connected by it. Compared to the original game. 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). o o -.o Input The input ﬁle will contain one or more test cases. the 1995 German game of the year. determining the longest road is not trivial (although human players usually see it immediately). . players attempt to dominate an island by building roads. though. Edges are undirected. The problem here is that the players usually build complex road networks and not just one linear path.o \ / o -.o / \ / \ o o -. The next m lines describe the m edges. and you are chosen to implement one of the game’s special rules: When the game ends.55 Within Settlers of Catan. we will solve a simpliﬁed problem here: You are given a set of nodes (cities) and a set of edges (road segments) of length 1 connecting the nodes. Nodes are numbered from 0 to n-1. the player who built the longest road gains two extra victory points.o o -. Nodes have degrees of three or less.o o \ / \ / o -. You are employed by a software company that just has decided to develop a computer version of this game. Therefore. settlements and cities across its uncharted wilderness. Example: The following network contains a road of length 12. Nodes may be visited more than once. The network is not neccessarily connected. The longest road is deﬁned as the longest path within the network that doesn’t use an edge twice.

Output For each test case.56 BAB 6. OTHER Input will be terminated by two values of 0 for n and m. Revilla 1999-01-11 . 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.

©Copyleft: Hayi Nukman (2011). .Sequel IKAtlah ilMU iTu denGAn meNGajarkannya. a Created with: L TEX.

Sign up to vote on this title

UsefulNot useful- Wen Derivatives
- A Contest of Contest_Yufei Zhao
- Wipro Class 2
- Arithmetic Progressions
- Data Sufficiency Number System
- fa10.pdf
- qs04
- GRE Math 강좌
- TCS Sample Question
- Discrete Maths_Module 1
- Wuhan2009 Final
- JMO
- Hash Tables
- card_vhdl.pdf
- Data Representation
- DMS
- Training Problems 2011
- 110216_apmops2010
- Presentation 3
- Division With Remainders
- Www.cs.Nyu.edu Courses Summer08 G22.1170-001 Hw02-Soln
- Topic Numbers, Subtopic-1
- Implementation RSA Java
- 2015 World Final Problem Set
- Learning Plan - Integers
- Untitled
- 7th-Math-Unit-1
- CProAss5
- proof qts c3 edexcel
- Telangana 8th class Mathematics Text book
- Buku_Latihan_Algoritma