Soal latihan algoritma

64
[Club Pemrograman Java] Buku Latihan Algoritma Author: Hayi Nukman STMIK AKAKOM Yogyakarta July 2011

Transcript of Soal latihan algoritma

Page 1: Soal latihan  algoritma

[Club Pemrograman Java]

Buku Latihan Algoritma

Author:Hayi Nukman

STMIK AKAKOMYogyakarta

July 2011

Page 2: Soal latihan  algoritma

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 berbedauntuk masing-masing case.

• Buat Program dari algoritma-algoritma tersebut (Java/C/C++).

• Kemudian buat catatan singkat mengenai Algoritma yang Anda Gu-nakan untuk menyelesaikan kasus tersebut.

• Post ke Blog anda, kemudian kirimkan link posting tersebut ke

email:[email protected](Bila perlu disertai dengan source code program dalam bentuk Attach-ment).

Contoh: UVA: 154 - Recycling

Recycling

Kerbside recycling has come to New Zealand, and every city fromAuckland to Invercargill has leapt on to the band wagon. The bins comein 5 different colours–red, orange, yellow, green and blue–and 5 wasteshave been identified for recycling–Plastic, Glass, Aluminium, Steel, andNewspaper. Obviously there has been no coordination between cities,so each city has allocated wastes to bins in an arbitrary fashion. Nowthat the government has solved the minor problems of today (such as

i

Page 3: Soal latihan  algoritma

ii

reorganising Health, Welfare and Education), they are looking around forfurther challenges. The Minister for Environmental Doodads wishes tointroduce the “Regularisation of Allocation of Solid Waste to Bin ColourBill” to Parliament, but in order to do so needs to determine an allocationof his own. Being a firm believer in democracy (well some of the timeanyway), 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, thatis would cause the smallest number of changes in the allocations of theother cities. Note that the sizes of the cities is not an issue, after all thisis a democracy with the slogan “One City, One Vote”.

Write a program that will read in a series of allocations of wastesto bins and determine which city’s allocation scheme should be chosen.Note that there will always be a clear winner.

Input and OutputInput will consist of a series of blocks. Each block will consist of a seriesof lines and each line will contain a series of allocations in the form shownin the example. There may be up to 100 cities in a block. Each blockwill be terminated by a line starting with ‘e’. The entire file will beterminated 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 adoptedas a national example.

Sample input:r/P,o/G,y/S,g/A,b/Nr/G,o/P,y/S,g/A,b/Nr/P,y/S,o/G,g/N,b/Ar/P,o/S,y/A,g/G,b/Ner/G,o/P,y/S,g/A,b/Nr/P,y/S,o/G,g/N,b/Ar/P,o/S,y/A,g/G,b/Nr/P,o/G,y/S,g/A,b/Necclesiastical#

Page 4: Soal latihan  algoritma

iii

Sample output14

Case review:

1’st Algorithm: Brute Force

For each city, iterate through every other city, and count the numberof differences. So, keep a counter, and if city[i]’s red bin != city[j]’sred bin, add one to the count.Output the city with the fewest differences.

Source:

Your Code here....

2nd Algorithm: Brute Force

Make an array of chars [100][5] where a[i][0] is the color of the plasticbin, a[i][1] is the color of the glass bin, and so on. Then compare eachcity brute force against all other cities, and return the most optimalone.

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, optimalisasialgoritma bisa belakangan.

Page 5: Soal latihan  algoritma

iv

• Algoritma kedua dan seterusnya boleh berupa optimalisasi dari algo-ritma pertama atau algoritma-algoritma sebelumnya.

Regards.Hayi Nukman (July 2011),

Created with: LaTEX.

Page 6: Soal latihan  algoritma

Daftar Isi

Recycling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

1 Easy 11.1 The Blocks Problem . . . . . . . . . . . . . . . . . . . . . . . 11.2 Greedy Gift Givers . . . . . . . . . . . . . . . . . . . . . . . . 41.3 Number Chains . . . . . . . . . . . . . . . . . . . . . . . . . . 61.4 The Bases Are Loaded . . . . . . . . . . . . . . . . . . . . . . 81.5 Combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2 Medium 112.1 Lining Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.2 The Tower of Babylon . . . . . . . . . . . . . . . . . . . . . . 122.3 Points in Figures: Rectangles . . . . . . . . . . . . . . . . . . 142.4 King . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.5 Number Maze . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3 Hard 233.1 Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.2 The Probable n-Ascendants . . . . . . . . . . . . . . . . . . . 253.3 Poker Hands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

4 Math 314.1 LCM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.2 Minimum Sum LCM . . . . . . . . . . . . . . . . . . . . . . . 324.3 Hendrie Sequence . . . . . . . . . . . . . . . . . . . . . . . . . 354.4 Modular Fibonacci . . . . . . . . . . . . . . . . . . . . . . . . 364.5 Polynomial coefficients . . . . . . . . . . . . . . . . . . . . . . 384.6 Pizza Cutting . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

v

Page 7: Soal latihan  algoritma

vi DAFTAR ISI

5 Sorting and Searching 435.1 Crossword Answers . . . . . . . . . . . . . . . . . . . . . . . . 435.2 The Department of Redundancy Department . . . . . . . . . . 475.3 Error Correction . . . . . . . . . . . . . . . . . . . . . . . . . 48

6 Other 516.1 Group Reverse . . . . . . . . . . . . . . . . . . . . . . . . . . 516.2 Testing the CATCHER . . . . . . . . . . . . . . . . . . . . . . 526.3 The Settlers of Catan . . . . . . . . . . . . . . . . . . . . . . . 54

Page 8: Soal latihan  algoritma

BAB 1

Easy

Go for the happy endings,because life doesn’t have any sequels.“ ”

1.1 The Blocks Problem

BackgroundMany areas of Computer Science use simple, abstract domains for bothanalytical and empirical studies. For example, an early AI study ofplanning and robotics (STRIPS) used a block world in which a robotarm performed tasks involving the manipulation of blocks.

In this problem you will model a simple block world under certainrules and constraints. Rather than determine how to achieve a specifiedstate, you will “program” a robotic arm to respond to a limited set ofcommands.

The Problem The problem is to parse a series of commands thatinstruct a robot arm in how to manipulate blocks that lie on a flat table.Initially there are n blocks on the table (numbered from 0 to n-1) withblock bi adjacent to block bi+1 for all 0 ≤ i < n − 1 as shown in thediagram below:

Figure: InitialBlocks World

The valid commands for the robot arm that manipulates blocks are:* move a onto b

1

Page 9: Soal latihan  algoritma

2 BAB 1. EASY

where a and b are block numbers, puts block a onto block b after return-ing any blocks that are stacked on top of blocks a and b to their initialpositions.

* move a over bwhere a and b are block numbers, puts block a onto the top of the stackcontaining block b, after returning any blocks that are stacked on top ofblock a to their initial positions.

* pile a onto bwhere a and b are block numbers, moves the pile of blocks consisting ofblock a, and any blocks that are stacked above block a, onto block b. Allblocks on top of block b are moved to their initial positions prior to thepile taking place. The blocks stacked above block a retain their orderwhen moved.

* pile a over bwhere a and b are block numbers, puts the pile of blocks consisting ofblock a, and any blocks that are stacked above block a, onto the top ofthe stack containing block b. The blocks stacked above block a retaintheir original order when moved.

* quitterminates manipulations in the block world.

Any command in which a = b or in which a and b are in the samestack of blocks is an illegal command. All illegal commands should beignored and should have no affect on the configuration of blocks.

The InputThe input begins with an integer n on a line by itself representing thenumber 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 untilthe quit command is encountered.

You may assume that all commands will be of the form specifiedabove. There will be no syntactically incorrect commands.

The OutputThe output should consist of the final state of the blocks world. Eachoriginal block position numbered i ( 0 ≤ i < n where n is the number

Page 10: Soal latihan  algoritma

3

of blocks) should appear followed immediately by a colon. If there is atleast a block on it, the colon must be followed by one space, followedby a list of blocks that appear stacked in that position with each blocknumber separated from other block numbers by a space. Don’t put anytrailing spaces on a line.

There should be one line of output for each block position (i.e., n linesof output where n is the integer on the first line of input).

Sample Input

10move 9 onto 1move 8 over 1move 7 over 1move 6 over 1pile 8 over 6pile 8 over 5move 2 over 1move 4 over 9quit

Sample Output

0: 01: 1 9 2 42:3: 34:5: 5 8 7 66:7:8:9:

Miguel Revilla2000-04-06

HINT:

Page 11: Soal latihan  algoritma

4 BAB 1. EASY

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

1.2 Greedy Gift Givers

The ProblemThis problem involves determining, for a group of gift-giving friends, howmuch more each person gives than they receive (and vice versa for thosethat view gift-giving with cynicism).

In this problem each person sets aside some money for gift-giving anddivides this money evenly among all those to whom gifts are given.

However, in any group of friends, some people are more giving thanothers (or at least may have more acquaintances) and some people havemore money than others.

Given a group of friends, the money each person in the group spendson gifts, and a (sub)list of friends to whom each person gives gifts; youare to write a program that determines how much more (or less) eachperson in the group gives than they receive.

The InputThe input is a sequence of gift-giving groups. A group consists of severallines:

• 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 peopleto whom gifts are given, and the names of those to whom gifts aregiven.

All names are lower-case letters, there are no more than 10 people ina group, and no name is more than 12 characters in length. Money is anon-negative integer less than 2000.

Page 12: Soal latihan  algoritma

5

The input consists of one or more groups and is terminated by end-of-file.

The OutputFor each group of gift-givers, the name of each person in the group shouldbe 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 inwhich they first appear in the input.

The output for each group should be separated from other groups bya blank line. All gifts are integers. Each person gives the same integeramount of money to each friend to whom any money is given, and gives asmuch as possible. Any money not given is kept and is part of a person’s“net worth” printed in the output.

Sample Input5dave laura owen vick amrdave 200 3 laura owen vickowen 500 1 daveamr 150 2 vick owenlaura 0 2 amr vickvick 0 03liz steve daveliz 30 1 stevesteve 55 2 liz davedave 0 2 steve liz

Sample Output

dave 302laura 66owen -359vick 141amr -150

liz -3

Page 13: Soal latihan  algoritma

6 BAB 1. EASY

steve -24dave 27

HINT:

Just use some Object Oriented programming. one person class solvesall your problems:class person-----int ratio-----int money-----string name

make an array of them, and take all the information in. When itcomes time to take a person’s (a) friends in, just loop through yourlist 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 theirname.

1.3 Number Chains

Given a number, we can form a number chain by1. arranging its digits in descending order2. arranging its digits in ascending order3. subtracting the number obtained in (2) from the number obtained

(1) to form a new number4. and repeat these steps unless the new number has already appeared

in the chainNote that 0 is a permitted digit. The number of distinct numbers in thechain is the length of the chain. You are to write a program that readsnumbers and outputs the number chain and the length of that chain foreach number read.

Page 14: Soal latihan  algoritma

7

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 file contains at most5000 numbers.

The output consists of the number chains generated by the inputnumbers, followed by their lengths exactly in the format indicated below.After each number chain and chain length, including the last one, thereshould be a blank line. No chain will contain more than 1000 distinctnumbers.

Sample Input

12345678912344440

Sample Output

Original number was 123456789987654321 - 123456789 = 864197532987654321 - 123456789 = 864197532Chain length 2

Original number was 12344321 - 1234 = 30878730 - 378 = 83528532 - 2358 = 61747641 - 1467 = 6174Chain length 4

Original number was 444444 - 444 = 00 - 0 = 0Chain length 2

HINT

Page 15: Soal latihan  algoritma

8 BAB 1. EASY

For each number n in the chain, transfer it to an integer array wherea[i] is the ith digit of n. Sort the array ascending and convert theindividual digits back into a complete number. Then iterate throughthe 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. When-ever you generate a new n, search for it in p[]. If you don’t find it,add it in. If you do find it, then stop processing and print out thelength 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 specified in any base (2..16)to a whole number in any other base (2..16). “Digits” above 9 are repre-sented by single capital letters; e.g. 10 by A, 15 by F, etc.

InputEach input line will consist of three values. The first value will be apositive integer indicating the base of the number. The second value isa positive integer indicating the base we wish to convert to. The thirdvalue is the actual number (in the first base) that we wish to convert.This number will have letters representing any digits higher than 9 andmay contain invalid “digits”. It will not exceed 10 characters. Each ofthe input values on a single line will be separated by at least one space.

OutputProgram 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” followedby the new base. If the original number is invalid, output the statement

original Value is an illegal base original Base number

Page 16: Soal latihan  algoritma

9

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

Sample input2 10 101015 3 12615 11 A4C

Sample output10101 base 2 = 21 base 10126 is an illegal base 5 numberA4C base 15 = 1821 base 11

HINT:

Convert each number into base 10, and then convert it into the finalbase. Check for invalid characters, which may be things like lowercaseletters or punctuation. Basically, check that only the characters inthe set {0123456789ABCDEF} are used, and that the number is legalin the given base.

If you’re using Java, you can use Long.parseLong to do the baseconversion, and you can catch NumberFormatExceptions, which in-dicate that the number contains invalid characters.

Note that you must use longs as ints are too small for some of theinputs.

1.5 Combinations

Computing the exact number of ways that N things can be taken M ata time can be a great challenge when N and/or M become very large.Challenges are the stuff of contests. Therefore, you are to make just sucha computation given the following:

GIVEN:5 ≤ N ≤ 100, and 5 ≤ M ≤ 100, and M ≤ N

Compute the EXACT value of:

Page 17: Soal latihan  algoritma

10 BAB 1. EASY

C =N !

(N −M)!×M !

You may assume that the final value of C will fit in a 32-bit PascalLongInt 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 OutputThe input to this program will be one or more lines each containing zeroor more leading spaces, a value for N, one or more spaces, and a valuefor M. The last line of the input file will contain a dummy N, M pairwith both values equal to zero. Your program should terminate whenthis line is read.The output from this program should be in the form:

N things taken M at a time is C exactly.

Sample Input100 620 518 60 0

Sample Output100 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.

Page 18: Soal latihan  algoritma

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

ages at specific points scattered in a dangerous area. Furthermore, thepilot could only fly over the area once in a straight line, and she hadto fly over as many points as possible. All points were given by meansof integer coordinates in a two-dimensional space. The pilot wanted toknow the largest number of points from the given set that all lie on oneline. Can you write a program that calculates this number?

Your program has to be efficient!

InputThe input begins with a single positive integer on a line by itself indicat-ing 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 betweentwo consecutive inputs. The input consists of N pairs of integers, where1 < N < 700. Each pair of integers is separated by one blank and endedby a new-line character. The list of pairs is ended with an end-of-filecharacter. No pair will occur twice.

OutputFor each test case, the output must follow the description below. Theoutputs of two consecutive cases will be separated by a blank line. The

11

Page 19: Soal latihan  algoritma

12 BAB 2. MEDIUM

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

Sample Input1

1 12 23 39 1010 11

Sample Output3

HINT:

computational geometry, sorting, line gradients (slopes). Try anO(n2logn) algorithm.

2.2 The Tower of Babylon

Perhaps you have heard of the legend of the Tower of Babylon. Nowa-days many details of this tale have been forgotten. So now, in line withthe educational nature of this contest, we will tell you the whole story:

The babylonians had n types of blocks, and an unlimited supplyof blocks of each type. Each type-i block was a rectangular solid withlinear dimensions (xi, yi, zi) . A block could be reoriented so that anytwo of its three dimensions determined the dimensions of the base andthe other dimension was the height. They wanted to construct thetallest tower possible by stacking blocks. The problem was that, inbuilding a tower, one block could only be placed on top of another blockas long as the two base dimensions of the upper block were both strictlysmaller than the corresponding base dimensions of the lower block.This meant, for example, that blocks oriented to have equal-sized bases

Page 20: Soal latihan  algoritma

13

couldn’t be stacked.

Your job is to write a program that determines the height of thetallest tower the babylonians can build with a given set of blocks.

Input and OutputThe input file will contain one or more test cases. The first line ofeach test case contains an integer n, representing the number of dif-ferent blocks in the following data set. The maximum value for n is 30.Each of the next n lines contains three integers representing the valuesxi ,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 arenumbered sequentially starting from 1) and the height of the tallest pos-sible tower in the format "Case case: maximum height = height"

Sample Input110 20 3026 8 105 5 571 1 12 2 23 3 34 4 45 5 56 6 67 7 7531 41 5926 53 5897 93 2384 62 6433 83 270

Page 21: Soal latihan  algoritma

14 BAB 2. MEDIUM

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

HINT:

dynamic programming, floyd warshall, other graph, DP, LIS (non-standard).

wasley:There are two main ways to do this problem... either LongestIncreasing Subsequence, or finding the longest path in a DAG.

I prefer the latter, because you can use Floyd-Warshall withthe bounds of this problem, and that’s much easier that doingLIS.

Let the weight of edge (u,v) be the height of block u, if u fitson top of v, and -Inf otherwise.

Then, run Floyd-Warshall, but with max instead of min. Foran arbitrary graph this won’t work, but for DAG it’s just fine. Atthe end, maximize (a[u][v] + h[v]) across all (u,v) where h[v] isthe height of block v (because we didn’t 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, determinefor each point which figures (if any) contain the point.

InputThere will be n( ≤ 10) rectangles descriptions, one per line. The firstcharacter will designate the type of figure (“r” for rectangle). This char-acter will be followed by four real values designating the x-y coordinatesof the upper left and lower right corners.

Page 22: Soal latihan  algoritma

15

The end of the list will be signalled by a line containing an asteriskin column one.

The remaining lines will contain the x-y coordinates, one per line, ofthe points to be tested. The end of this list will be indicated by a pointwith coordinates 9999.9 9999.9; these values should not be included inthe output.

Points coinciding with a figure border are not considered inside.

OutputFor each point to be tested, write a message of the form:

Point i is contained in figure j

for each figure that contains that point. If the point is not con-tained in any figure, write a message of the form:

Point i is not contained in any figure

Points and figures should be numbered in the order in which theyappear in the input.

Sample Inputr 8.5 17.0 25.5 -8.5r 0.0 10.3 5.5 0.0r 2.5 12.5 12.5 2.5*2.0 2.04.7 5.36.9 11.220.0 20.017.6 3.2-5.2 -7.89999.9 9999.9

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

Page 23: Soal latihan  algoritma

16 BAB 2. MEDIUM

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

Diagrama of sample input figures and data pointsHINT:

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 rwith co-ordinates (x1, y1) and (x2, y2), i lies inside r if and onlyif:

(x > x1&&x < x2&&y < y1&&y > y2)

Make sure that you’re using strict inequalities, as per the problemdescription.

2.4 King

Page 24: Soal latihan  algoritma

17

Once, in one kingdom, there was a queen and that queen was expectinga baby. The queen prayed: “If my child was a son and if only he was asound king.” After nine months her child was born, and indeed, she gavebirth to a nice son.

Unfortunately, as it used to happen in royal families, the son was alittle retarded. After many years of study he was able just to add integernumbers and to compare whether the result is greater or less than a giveninteger number. In addition, the numbers had to be written in a sequenceand 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 makeeverything to enable his son to govern the kingdom after his death. Withregards to his son’s skills he decided that every problem the king had todecide about had to be presented in a form of a finite sequence of integernumbers and the decision about it would be done by stating an integerconstraint (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 tomake some decisions.

After the old king died, the young king began to reign. But very soon,a lot of people became very unsatisfied with his decisions and decidedto dethrone him. They tried to do it by proving that his decisions werewrong.

Therefore some conspirators presented to the young king a set ofproblems that he had to decide about. The set of problems was inthe form of subsequences Si = {asi , asi+1, . . . , asi+ni

} of a sequenceS = {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 subsequenceSi an integer constraint ki (i.e. asi + asi+1 + · · · + asi+ni

< ki orasi + asi+1 + · · · + asi+ni

> ki resp.) and declared these constraintsas his decisions.

After a while he realized that some of his decisions were wrong. Hecould not revoke the declared constraints but trying to save himself hedecided to fake the sequence that he was given. He ordered to his advisorsto find such a sequence S that would satisfy the constraints he set. Helpthe advisors of the king and write a program that decides whether sucha sequence exists or not.

InputThe input file consists of blocks of lines. Each block except the lastcorresponds to one set of problems and king’s decisions about them. In

Page 25: Soal latihan  algoritma

18 BAB 2. MEDIUM

the first 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 ofsubsequences Si. Next m lines contain particular decisions coded in theform of quadruples si, ni, oi, ki, where oi represents operator > (codedas gt) or operator < (coded as lt) respectively. The symbols si, ni andki have the meaning described above. The last block consists of just oneline containing 0.

Output

The output file contains the lines corresponding to the blocks in the inputfile. A line contains text successful conspiracy when such a sequencedoes not exist. Otherwise it contains text lamentable kingdom. Thereis no line in the output file corresponding to the last “null” block of theinput file.

Sample Input

4 21 2 gt 02 2 lt 21 21 0 gt 01 0 lt 00

Sample Output

lamentable kingdomsuccessful conspiracy

HINT:

Page 26: Soal latihan  algoritma

19

math, other graph, graph theory, difference constraints, Bellman-Ford.

This is a constraint satisfaction problem that can be solvedwith negative cycle detection.

A system of difference constraints is a series of constraints of theform:

x1 − x2 ≤ C

These systems can be solved by creating a graph with a vertex foreach variable, and an edge from x2 to x1 with weight C for eachconstraint. There exists a solution that satisfies all of the constraintsiff the graph does not contain a negative weight cycle.

However, the constraints given in this problem are not of thisform. They contain multiple variables, are sums rather than addi-tions, and have strict inequalities. Luckily, we can convert them.

Let a[i] be the sum of the first i variables in the sequence (a[0]= 0). Since all of the constraints relate contiguous subsequences, wecan rewrite the constraint

xk + xk+1 + ...+ xk+h < / > C

asa[k + h]− a[k − 1] < / > C

Now, to change the strict inequalities into non-strict inequalities, notethat, when working with integers:

a[k + h]− a[k − 1] < C

is the same asa[k + h]− a[k − 1] ≤ C − 1

And in the same vein:a[k + h]− a[k − 1] > Cis the same asa[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.

Page 27: Soal latihan  algoritma

20 BAB 2. MEDIUM

2.5 Number Maze

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

ProblemYour task is to find the minimum cost value to go from the top-left cornerto the bottom-right corner of a given number maze of size NxM where1 ≤ N , M ≤ 999. Note that the solution for the given example is 24.

InputThe input file contains several mazes. The first input line contains apositive integer defining the number of mazes that follow. Each maze isdefined by: one line with the number of rows, N; one line with the numberof columns, M; and N lines, one per each row of the maze, containing themaze numbers separated by spaces. Output

For each maze, output one line with the required minimum value.

Sample Input2450 3 1 2 97 3 4 9 9

Page 28: Soal latihan  algoritma

21

1 7 5 5 32 3 4 2 5160 1 2 3 4 5

Sample Output2415University of Porto / 2003 ACM Programming Contest / Round 2 /2003/09/24

HINT

graph theory, shortest paths, Dijkstra (on a sparse graph), arraypriority queue, see CLRS exercise 24.3-6:

The idea behind this problem is to find a faster way of doingDijkstra 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 accomplishedby using 10 queues. The idea works as such:

When you want to get the next node, search all of the queues inorder until you come to one that isn’t empty. Take the top node fromthis one. When you add a node to the queues, add it to the one thatis c queues away from the one you are currently at, where c is thecost of traversing that node.

For example, in the first test case:• The starting node has cost 0, so we put it onto queue 0. We

dequeue this node, and look at it’s neighbours. They have costs 3and 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 neight-bours. They have costs 1 and 3, so they go in queues 4 and 6respectively.

So you make your way around the queues in a circle, and you keeptaking from one queue until either it is empty, or the next queue inthe circle has a node at the front that has shorter distance.

Page 29: Soal latihan  algoritma

22 BAB 2. MEDIUM

Page 30: Soal latihan  algoritma

BAB 3

Hard

Think smarter, not harder“ ”3.1 Data Flow

In the latest Lab of IIUC, it requires to send huge amount of data fromthe local server to the terminal server. The lab setup is not yet ready. Itrequires to write a router program for the best path of data. The problemis all links of the network has a fixed capacity and cannot flow more thanthat amount of data. Also it takes certain amount of time to send oneunit data through the link. To avoid the collision at a time only one dataunit can travel i.e. at any instant more than one unit of data cannottravel parallel through the network. This may be time consuming but itcertainly gives no collision. Each node has sufficient buffering capabilityso that data can be temporarily stored there. IIUC management wantsthe shortest possible time to send all the data from the local server tothe final one.

23

Page 31: Soal latihan  algoritma

24 BAB 3. HARD

For example, in the above network if anyone wants to send 20 unitdata from A to D, he will send 10 unit data through AD link and then10 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 timewill be given. The links are bidirectional and there will be at most onelink between two network nodes. In next line there will be two positiveintegers D, K where D is the amount of data to be transferred from 1stto N’th 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 allthe 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. KamruzzamanMember of Elite Problemsetters’ Panel

Page 32: Soal latihan  algoritma

25

HINT: dijkstra, max flow, other graph

This is a minimum-cost maximum flow problem. Basically, it’s thecombination of shortest path and maximum flow. The general ideais not too difficult. You do Edmonds-Karp to get the maximum flow,but you replace the BFS with a weighted shortest path algorithm.

Dijkstra is the best choice, except that the graph will have neg-ative costs after you reverse edges. You can do Bellman-Ford, butunfortunately that’s too slow for this problem (unless you’re luckyin C perhaps). Luckily, there exists a compromise. You can runBellman-Ford once at the beginning of the algorithm to set the graphup in such a way that Dijkstra will work from that point on. In thisproblem, because there are no negative costs to begin with, you don’tneed Bellman-Ford at all, and you can use Dijkstra to initialize thegraph, but it doesn’t matter much runtime-wise.

I suggest reading the following to understand how this ”graphinitialization” part works. Read the subsection ”Successive ShortestPath 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 oneindividual is determined by a pair of genes (a gene is a part of achromosome). When a pair of genes presents different information forone characteristic, the dominance of one gene over the other naturallyinfluences the way an individual externally presents that characteristic.

Page 33: Soal latihan  algoritma

26 BAB 3. HARD

In the case of total dominance, a dominant gene imposes the externalappearance of its information over the other gene of the pair. The infor-mation of a recessive gene (the dominated gene) is only externally shownif there is no dominant gene in the pair. The information of a dominantgene is represented by a capital letter, while the information of a reces-sive gene is represented by a small letter. One individual that possesses apair of genes with equal information for the same characteristic is calledhomozigotic, otherwise it is called heterozigotic.

In the guinee-pigs, the gene for the black colour (B) is dominant overthe gene for the white colour (w). The descendants’ genetic types (com-position of the pair of genes) of two parents are obtained by generatingthe different possible combinations of the 4 genes of the parents. Eachascendant contributes with only one gene to the pair of genes of the de-scendant. For instance, one heterozigotic guinee-pig (Bw) presents thesame colour of one black homozigotic guinee-pig (BB). The descendantsof two black homozigotic guinee-pigs (BB) have 100% probability of alsobeing black homozigotic individuals. An analogous situation occurs withthe descendants of two white homozigotic guinee-pigs (ww), i.e., theyhave 100% probability of also being white homozigotic individuals. Thedescendants of one black homozigotic guinee-pig (BB) and one whitehomozigotic guinee-pig (ww) have 100% probability of being black het-erozigotic individuals. The following figure illustrates this description.

Imagine that you don’t know, for a particular guinee-pig, who were

Page 34: Soal latihan  algoritma

27

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

InputThe input will contain several test cases, each of them as described below.Consecutive test cases are separated by a single blank line.

The first line of the input contains the genes of the guinee-pig forwhom you want to know the probable n-ascendants. The second linecontains the value of n, i.e., the level of ascendant generation that youwant to study.

OutputFor each test case, the output must follow the description below. Theoutputs of two consecutive cases will be separated by a blank line.

The output is a list of lines, each one containing the concatenatedgenes of each member of the possible pair of n-ascendants, followed bythe corresponding probability, truncated to 2 fractional digits. The con-catenation of the 2 pair of n-ascendant genes must ensure that the resul-tant string is the biggest one, considering BBBB > BBBw > BBwB >... > wwwB > wwww. The output must be sorted in descending orderby value of the concatenation of the 2 pair of n-ascendant genes. Beforeprinting any floating point value add 10-11to avoid round off error.

Sample InputBw1

ww8

Sample OutputBBBw 20.0%BBww 40.0%

Page 35: Soal latihan  algoritma

28 BAB 3. HARD

BwBw 20.0%Bwww 20.0%

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

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 ofclubs, diamonds, hearts, or spades (denoted C, D, H, and S in the inputdata). 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 valuesare ordered as given above, with 2 being the lowest and ace the highestvalue.

A poker hand consists of 5 cards dealt from the deck. Poker handsare ranked by the following partial order from lowest to highest

• High Card: Hands which do not fit any higher category are rankedby the value of their highest card. If the highest cards have thesame 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 whichboth contain a pair are ranked by the value of the cards forming thepair. If these values are the same, the hands are ranked by thevalues of the cards not forming the pair, in decreasing order.

• Two Pairs: The hand contains 2 different pairs. Hands which bothcontain 2 pairs are ranked by the value of their highest pair. Handswith the same highest pair are ranked by the value of their otherpair. If these values are the same the hands are ranked by the valueof the remaining card.

Page 36: Soal latihan  algoritma

29

• Three of a Kind: Three of the cards in the hand have the samevalue. Hands which both contain three of a kind are ranked by thevalue of the 3 cards.

• Straight: Hand contains 5 cards with consecutive values. Handswhich both contain a straight are ranked by their highest card.

• Flush: Hand contains 5 cards of the same suit. Hands which areboth flushes are ranked using the rules for High Card.

• Full House: 3 cards of the same value, with the remaining 2 cardsforming a pair. Ranked by the value of the 3 cards.

• Four of a kind: 4 cards with the same value. Ranked by the valueof the 4 cards.

• Straight flush: 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 indicatewhich, if either, has a higher rank.

InputThe input file contains several lines, each containing the designation of10 cards: the first 5 cards are the hand for the player named ”Black” andthe next 5 cards are the hand for the player named ”White”.

OutputFor each line of input, print a line containing one of the following threelines:

Black wins.White wins.Tie.

Sample Input2H 3D 5S 9C KD 2C 3H 4S 8C AH2H 4S 4C 2D 4H 2S 8S AS QS 3S2H 3D 5S 9C KD 2C 3H 4S 8C KH2H 3D 5S 9C KD 2D 3H 5C 9S KH

Page 37: Soal latihan  algoritma

30 BAB 3. HARD

Sample OutputWhite wins.Black wins.Black wins.Tie.

(The Decider Contest, Source: Waterloo ACM Programming Contest)HINT: adhoc

• Sort both players’ hands. It’ll make the comparisons a lot easier

• Check for hands by decreasing value, i.e. straight flush, thenfour of a kind, etc. all the way down to high card. Checking fourfour of a kind, then three, then two, is a lot easier than the otherway around

Page 38: Soal latihan  algoritma

BAB 4

Math

I couldn’t repair your brakes, so I just made your horn louder.“ ”4.1 LCM

All of you know about LCM (Least Common Multiple). For exampleLCM of 4 and 6 is 12. LCM can also be defined for more than 2 integers.LCM of 2, 3, 5 is 30. In the same way we can define LCM of first Nintegers. The LCM of first 6 numbers is 60.As you will see LCM will increase rapidly with N. So we are not interestedin the exact value of the LCM but we want to know the last nonzero digitof that. And you have to find that effeciently.

InputEach line contains one nonzero positive integer which is not greater than1000000. Last line will contain zero indicating the end of input. Thisline should not be processed. You will need to process maximum 1000lines of input.

OutputFor each line of input, print in a line the last nonzero digit of LCM offirst 1 to N integers.

Sample Input35

31

Page 39: Soal latihan  algoritma

32 BAB 4. MATH

100

Output for Sample Input662

Problemsetter: Md. Kamruzzaman, Member of Elite Problemsetters’PanelSpecial 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 inter-section 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 num-bers.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 you’ve used j as afactor in your LCM so far. When you factorize i+1, check if the countof each factor, j, is greater than c[j]. If it is, multiply your current LCMby j until the count is satisfied.Now, the LCM grows very quickly, so we don’t want to actually storethe entire LCM in a[]. Instead, we store the last 7 or so digits before thefinal string of zeros. So, if our LCM was 182158203800000000, we wouldstore ”1582038” in a[]. This can be accomplished by the following code:while(a[i] % 10 == 0)--- a[i] /= 10a[i] %= 10000000We keep 7 digits because the largest number we might multiply a[i] by is6 digits long.

4.2 Minimum Sum LCM

Page 40: Soal latihan  algoritma

33

LCM (Least Common Multiple) of a set of integers is defined as theminimum number, which is a multiple of all integers of that set. It isinteresting to note that any positive integer can be expressed as the LCMof a set of positive integers. For example 12 can be expressed as the LCMof 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 haveto find out a set of at least two positive integers whose LCM is N. Asinfinite such sequences are possible, you have to pick the sequence whosesummation of elements is minimum. We will be quite happy if you justprint the summation of the elements of this set. So, for N = 12, youshould print 4+3 = 7 as LCM of 4 and 3 is 12 and 7 is the minimumpossible summation.

InputThe input file contains at most 100 test cases. Each test case consists ofa positive integer N ( 1≤N≤231 - 1).

Input is terminated by a case where N = 0. This case should not beprocessed. There can be at most 100 test cases.

OutputOutput of each test case should consist of a line starting with ‘Case #: ’where # is the test case number. It should be followed by the summationas specified in the problem statement. Look at the output for sampleinput for details.

Sample Input121050

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

Page 41: Soal latihan  algoritma

34 BAB 4. MATH

Problem setter: Md. KamruzzamanSpecial Thanks: Shahriar ManzoorMiguel Revilla 2004-12-10

HINT:This is a prime factorization problem with a lot of picky cases.The first thing to see is that the prim factorization of a number is almostthe minimum sum LCM set. I say almost because you have to keepcopies of the same factor multipled together.For example, say N = 36. The prime factorization is 22 × 32. Obviouslythe minimum set isn’t 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 find the prime factorization, keep copies of thesame term together, and return the sum of the products (so 4 + 9 = 13in the above example).However, there are some issues. First there’s N = 1, and N = 231− 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,isn’t truly a set. However, by the problem definition you must have atleast two numbers in your set.For N = 231− 1, you must output 231. This is a problem if you’re usingunsigned integers, of course. But I wouldn’t bother changing to signedintegers or longs. Just hardcode this case.The other issue involves numbers that are powers of a single factor.So for instance 51, or 210. You can’t 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, here’s how you can do it. Weknow our limit is 231, 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 eachprime that it’s divisible by (as many times as you can). Keep track ofthese primes as they are (obviously) factors of N.Once you’ve gone through all the primes <=

√N , there will be one of

two cases. Either N = 1, in which case you’re done, or N > 1, in whichcase N now equals the last factor of (the original) N. This is because youcan have no more than one prime factor greater than the square root ofthe number. So if N > 1, record N as another factor.

Page 42: Soal latihan  algoritma

35

4.3 Hendrie Sequence

The Hendrie Sequence “H” is a self-describing sequence defined 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 resulting sequence is still H(without its first element).

Thus, the first 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 elementof H.

InputEach 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 ofcourse should not be processed.

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

Sample Input47448068568370132090880

Sample Output20316

Page 43: Soal latihan  algoritma

36 BAB 4. MATH

Problem setter: Derek Kisman, University of Waterloo, CanadaHINT:

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(i−2) (excepting the first blockwhich has length 1). Also, the ith block consists of (i-2) pieces fromprior 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 defined in terms of the block before it, we can writea recursive function that simplifies the problem down until it reachesa known value (say, the first 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 nbelongs to.n− 2k is how far along the block n is. We add up the lengths of thesubblocks, i × 2(k−i−1) for i from 1 to k until the cumulative sum isgreater than or equal to (n − 2k). The index i at which we stop isthe number of the subblock that n belongs to.We can now simplify n down to 2(k−i−1)+(n−2k−1)%(2(k−i−1))+1,and recurse on this new value. Note that (k − i− 1) can be < 0, inwhich case the first 2(k−i−1) should be set to 0, and the latter shouldbe set to 1.Be wary of double precision as it isn’t quite good enough for thisproblem. I would suggest doing everything in longs to avoid roundingerrors. For instance, log(263−1)

log(2) gives 63, when then actual value isslightly less than 63.

4.4 Modular Fibonacci

Page 44: Soal latihan  algoritma

37

The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) are definedby the recurrence:F0 = 0F1 = 1Fi = Fi−1 + Fi−2 → for(i) > 1

Write a program which calculates Mn = Fn mod 2m for given pairof n and m. 0 ≤ n ≤ 2147483647 and 0 ≤ m < 20. Note that a mod bgives the remainder when a is divided by b.

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

Sample Input11 711 6

Sample Output8925

Arun KishoreHINT:This problem requires an O(log n) method to calculate an arbitrary Fi-bonacci number. The algorithm works off of the idea that you can dothe following matrix multiplication:[

Fn+1 Fn

Fn Fn−1

]=

[1 11 0

]and you will get the next set of Fibonacci numbers. Thus, we can derive:F2n = Fn × (Fn + 2Fn−1)F2n−1 = F 2

n + F 2n−1

depending on whether the number is even or odd. We can usethese formulas along with an algorithm that does O(logn) exponentia-tion to come up with the answer. Take mod m after every addition and

Page 45: Soal latihan  algoritma

38 BAB 4. MATH

multiplication to keep the numbers small, and use longs because youmay need to square numbers as large as 220, and 240 won’t fit in an int.

4.5 Polynomial coefficients

The ProblemThe problem is to calculate the coefficients in expansion of polynomial(x1 + x2 + ...+ xk)

n.

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

The OutputFor each input pair of lines the output line should consist one integer, thecoefficient by the monomial xn1

1 xn22 ...xnk

k in expansion of the polynomial(x1 + x2 + ...+ xk)

n.

Sample Input2 21 12 121 0 0 0 0 0 0 0 0 0 1 0

Sample Output22

Page 46: Soal latihan  algoritma

39

HINT:

Let n(k) be the power of the kth term in the monomial we’re askedto 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× xik

The only term we care about is where i = n(xk), so we can throughaway the rest. We keep breaking this down recursively until we endup with a product of Chooses, which we can then simplify into asimple final form:

n!

n1!× n2!× ...× nk!

4.6 Pizza Cutting

When someone calls Ivan lazy, he claims that it is his intelligence thathelps him to be so. If his intelligence allows him to do something at lessphysical effort, why should he exert more? He also claims that he alwaysuses his brain and tries to do some work at less effort; this is not hislaziness, rather this is his intellectual smartness.

Once Ivan was asked to cut a pizza into seven pieces to distribute itamong his friends. (Size of the pieces may not be the same. In fact, hispiece will be larger than the others.) He thought a bit, and came to theconclusion that he can cut it into seven pieces by only three straight cutsthrough the pizza with a pizza knife. Accordingly, he cut the pizza inthe following way (guess which one is Ivan’s piece):

Page 47: Soal latihan  algoritma

40 BAB 4. MATH

One of his friends, who never believed in Ivan’s smartness, was star-tled at this intelligence. He thought, if Ivan can do it, why can’t mycomputer? So he tried to do a similar (but not exactly as Ivan’s, for Ivanwill criticize him for stealing his idea) job with his computer. He wrotea program that took the number of straight cuts one makes through thepizza, and output a number representing the maximum number of pizzapieces it will produce.

Your job here is to write a similar program. It is ensured that Ivan’sfriend won’t criticize you for doing the same job he did.

InputThe input file will contain a single integer N (0 <= N <= 210000000) ineach line representing the number of straight line cuts one makes throughthe pizza. A negative number terminates the input.

OutputOutput the maximum number of pizza pieces the given number of cutscan produce. Each line should contain only one output integer withoutany leading or trailing space.

Sample Input510-100

Page 48: Soal latihan  algoritma

41

Sample Output1656

Rezaul Alam ChowdhuryHINT:

On the ith cut, you can cut through i pieces of pizza. Therefore thetotal number of cuts is the triangular number sequence. As you startwith one piece, you must add one to all the terms.So for each input n, output n×(n+1)

2+ 1.

Page 49: Soal latihan  algoritma

42 BAB 4. MATH

Page 50: Soal latihan  algoritma

BAB 5

Sorting and Searching

Being Stupid isn’t as easy as it may look.“ ”5.1 Crossword Answers

A crossword puzzle consists of a rectangular grid of black and whitesquares and two lists of definitions (or descriptions).

One list of definitions is for “words” to be written left to right acrosswhite squares in the rows and the other list is for words to be writtendown white squares in the columns. (A word is a sequence of alphabeticcharacters.)

To solve a crossword puzzle, one writes the words corresponding tothe definitions on the white squares of the grid.

The definitions correspond to the rectangular grid by means of se-quential integers on “eligible” white squares. White squares with blacksquares immediately to the left or above them are “eligible.” Whitesquares with no squares either immediately to the left or above are also“eligible.” No other squares are numbered. All of the squares on the firstrow are numbered.

The numbering starts with 1 and continues consecutively across whitesquares of the first row, then across the eligible white squares of the sec-ond row, then across the eligible white squares of the third row and so onacross all of the rest of the rows of the puzzle. The picture below illus-trates a rectangular crossword puzzle grid with appropriate numbering.

43

Page 51: Soal latihan  algoritma

44 BAB 5. SORTING AND SEARCHING

An “across” word for a definition is written on a sequence of whitesquares in a row starting on a numbered square that does not followanother white square in the same row.

The sequence of white squares for that word goes across the row ofthe numbered square, ending immediately before the next black squarein the row or in the rightmost square of the row.

A “down” word for a definition is written on a sequence of whitesquares in a column starting on a numbered square that does not followanother white square in the same column.

The sequence of white squares for that word goes down the column ofthe numbered square, ending immediately before the next black squarein 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 constitutethe solutions.

InputEach puzzle solution in the input starts with a line containing two integersr and c ( 1 ≤ r ≤ 10 and 1 ≤ c ≤ 10 ), where r (the first number) is thenumber of rows in the puzzle and c (the second number) is the numberof columns.

The r rows of input which follow each contain c characters (excludingthe end-of-line) which describe the solution. Each of those c charactersis 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 number0.

Page 52: Soal latihan  algoritma

45

OutputOutput for each puzzle consists of an identifier for the puzzle(puzzle #1:, puzzle #2:, etc.) and the list of across words followed bythe list of down words. Words in each list must be output one-per-linein increasing order of the number of their corresponding definitions.

The heading for the list of across words is “Across”. The heading forthe 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 Input2 2AT*O6 7AIM*DEN*ME*ONEUPON*TOSO*ERIN*SA*OR*IES*DEA0

Sample Outputpuzzle #1:Across1.AT3.O

Down1.A2.TO

puzzle #2:Across1.AIM4.DEN

Page 53: Soal latihan  algoritma

46 BAB 5. SORTING AND SEARCHING

7.ME8.ONE9.UPON11.TO12.SO13.ERIN15.SA17.OR18.IES19.DEA

Down1.A2.IMPOSE3.MEO4.DO5.ENTIRE6.NEON9.US10.NE14.ROD16.AS18.I20.A

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

Page 54: Soal latihan  algoritma

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 whenthe entire puzzle consists of only black squares.

5.2 The Department of RedundancyDepartment

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

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

OutputThe output for this program will be a sequence of ordered pairs, separatedby newlines. The first element of the pair must be an integer from theinput file. The second element must be the number of times that thatparticular integer appeared in the input file. The elements in each pairare to be separated by space characters. The integers are to appear inthe order in which they were contained in the input file.

Sample Input3 1 2 2 1 3 5 3 3 2

Sample Output3 41 22 35 1

Page 55: Soal latihan  algoritma

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 theobject that has the same value, and increment its quantity. If youcan’t find 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 columnhas an even sum, i.e. contains an even number of bits which are set.Here’s a 4 x 4 matrix which has the parity property:1 0 1 00 0 0 01 1 1 10 1 0 1The 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 checksif it has the parity property. If not, your program should check if theparity property can be established by changing only one bit. If this isnot possible either, the matrix should be classified as corrupt.

InputThe input file will contain one or more test cases. The first line of eachtest case contains one integer n (n<100), representing the size of thematrix. On the next n lines, there will be n integers per line. No otherintegers than 0 and 1 will occur in the matrix. Input will be terminatedby a value of 0 for n.

OutputFor each matrix in the input file, print one line. If the matrix already hasthe parity property, print “OK”. If the parity property can be established

Page 56: Soal latihan  algoritma

49

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

Sample Input41 0 1 00 0 0 01 1 1 10 1 0 141 0 1 00 0 1 01 1 1 10 1 0 141 0 1 00 1 1 01 1 1 10 1 0 10

Sample OutputOKChange bit (2,3)Corrupt

Miguel A. Revilla1999-01-11

HINT:Keep to arrays, r[] and c[] where r[i] is the sum of row i, and c[i] is thesum of column i. You can fill these in as you take in the input. It isn’tnecessary to store the actual matrix.Search through each array and look for cells with odd sums. If no cellshave odd sums, then the matrix is OK. If one row and one column areodd, then output ”Change bit (row,column)”. Otherwise, the matrix iscorrupt.

Page 57: Soal latihan  algoritma

50 BAB 5. SORTING AND SEARCHING

Page 58: Soal latihan  algoritma

BAB 6

Other

If you don’t know what you are talking about,at least act like you do.“ ”

6.1 Group Reverse

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

“TOBENUMBERONEWEMEETAGAINANDAGAINUNDERBLUEI”

This string has length 48. We have divided into 8 groups of equallength and so the length of each group is 6. Now we can reverse each ofthese eight groups to get a new string:

“UNEBOTNOREBMEEMEWENIAGATAGADNAEDNUNIIEULBR”

Given the string and number of groups in it, your program willhave to group reverse it.

InputThe input file contains at most 101 lines of inputs. Each line containsat integer G (G<10) which denotes the number of groups followed by astring whose length is a multiple of G. The length of the string is notgreater than 100. The string contains only alpha numerals. Input isterminated by a line containing a single zero.

51

Page 59: Soal latihan  algoritma

52 BAB 6. OTHER

OutputFor each line of input produce one line of output which contains thegroup reversed string.

Sample Input3 ABCEHSHSH5 FA0ETASINAHGRI0NATWON0QA0NARI00

Output for Sample InputCBASHEHSHATE0AFGHANISTAN0IRAQ0NOW0IRAN0

Problem-setter: Shahriar ManzoorSpecial Thanks: Derek Kisman

HINT:

6.2 Testing the CATCHER

A military contractor for the Department of Defense has just com-pleted a series of preliminary tests for a new defensive missile called theCATCHER which is capable of intercepting multiple incoming offensivemissiles. The CATCHER is supposed to be a remarkable defensive mis-sile. It can move forward, laterally, and downward at very fast speeds,and it can intercept an offensive missile without being damaged. But itdoes have one major flaw. Although it can be fired to reach any initialelevation, it has no power to move higher than the last missile that it hasintercepted.The tests which the contractor completed were computer simulations ofbattlefield and hostile attack conditions. Since they were only prelim-inary, the simulations tested only the CATCHER’s vertical movementcapability. In each simulation, the CATCHER was fired at a sequence ofoffensive missiles which were incoming at fixed time intervals. The onlyinformation available to the CATCHER for each incoming missile was itsheight at the point it could be intercepted and where it appeared in the

Page 60: Soal latihan  algoritma

53

sequence of missiles. Each incoming missile for a test run is representedin the sequence only once.The result of each test is reported as the sequence of incoming mis-siles and the total number of those missiles that are intercepted by theCATCHER in that test.The General Accounting Office wants to be sure that the simulation testresults submitted by the military contractor are attainable, given theconstraints of the CATCHER. You must write a program that takes in-put data representing the pattern of incoming missiles for several differenttests and outputs the maximum numbers of missiles that the CATCHERcan intercept for those tests. For any incoming missile in a test, theCATCHER is able to intercept it if and only if it satisfies one of thesetwo conditions:The incoming missile is the first missile to be intercepted in this test.-or-The missile was fired after the last missile that was intercepted and it isnot higher than the last missile which was intercepted.

Input

The input data for any test consists of a sequence of one or more non-negative integers, all of which are less than or equal to 32,767, repre-senting the heights of the incoming missiles (the test pattern). The lastnumber in each sequence is -1, which signifies the end of data for thatparticular test and is not considered to represent a missile height. Theend of data for the entire input is the number -1 as the first value in atest; 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 couldpossibly intercept for the test. That maximum number appears after anidentifying message. There must be at least one blank line betweenoutput for successive data sets.

Note: The number of missiles for any given test is not limited. If yoursolution is based on an inefficient algorithm, it may not execute in theallotted time.

Page 61: Soal latihan  algoritma

54 BAB 6. OTHER

Sample Input38920715530029917015865-1233421-1-1

Sample OutputTest #1:maximum possible interceptions: 6

Test #2:maximum possible interceptions: 2

HINT:

keep two arrays, one for heights and one for ’values’. The valuesarray at [i] will hold the maximum number of missles that could beintercepted should the set of missles end with i.Loop through your height array using a variable x, and for eachelement, loop from 0 to x-1 to find the ’best’ previously shot missle(ie the one with the highest value that is still at least as high as thecurrent). Value[x] will be the value of the ’best’ that you found + 1or 1 if you found nothing.Output the hightest value in the value array.

6.3 The Settlers of Catan

Page 62: Soal latihan  algoritma

55

Within Settlers of Catan, the 1995 German game of the year, playersattempt to dominate an island by building roads, settlements and citiesacross its uncharted wilderness.

You are employed by a software company that just has decided todevelop a computer version of this game, and you are chosen toimplement one of the game’s special rules:

When the game ends, the player who built the longest road gainstwo extra victory points.

The problem here is that the players usually build complex roadnetworks and not just one linear path. Therefore, determining thelongest road is not trivial (although human players usually see itimmediately).

Compared to the original game, we will solve a simplified problemhere: You are given a set of nodes (cities) and a set of edges (roadsegments) of length 1 connecting the nodes. The longest road is definedas the longest path within the network that doesn’t 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

InputThe input file will contain one or more test cases.

The first line of each test case contains two integers: the number ofnodes n ( 2 ≤ n ≤ 25) and the number of edges m ( 1 ≤ m ≤ 25). Thenext m lines describe the m edges. Each edge is given by the numbersof 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 networkis not neccessarily connected.

Page 63: Soal latihan  algoritma

56 BAB 6. OTHER

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

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

Sample Input3 20 11 215 160 21 22 33 43 54 65 76 87 87 98 109 1110 1211 1210 1312 140 0

Sample Output212

Miguel A. Revilla1999-01-11

Page 64: Soal latihan  algoritma

Sequel

IKAtlah ilMU iTu

denGAn meNGajarkannya.

©Copyleft: Hayi Nukman (2011),Created with: LaTEX.