Soal latihan algoritma

21,943 views
21,709 views

Published on

Published in: Business, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
21,943
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
405
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Soal latihan algoritma

  1. 1. [Club Pemrograman Java]Buku Latihan Algoritma Author: Hayi Nukman STMIK AKAKOM Yogyakarta July 2011
  2. 2. Petunjuk “ An algorithm must be seen to be believed. ” Buku ini terdiri dari enam bagian yang masing-masing berisi beberapasoal/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 Gu- nakan untuk menyelesaikan kasus tersebut. • Post ke Blog anda, kemudian kirimkan link posting tersebut ke hayi.nkm@gmail.com email: (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 from Auckland to Invercargill has leapt on to the band wagon. The bins come in 5 different colours–red, orange, yellow, green and blue–and 5 wastes have been identified 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
  3. 3. 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 firm 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 file 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 #
  4. 4. iiiSample output14 Case review:1’st Algorithm: Brute Force For each city, iterate through every other city, and count the number of differences. So, keep a counter, and if city[i]’s red bin != city[j]’s red bin, add one to the count. Output the city with the fewest 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 plastic bin, a[i][1] is the color of the glass bin, and so on. Then compare each city brute force against all other cities, and return the most optimal one.Source: Your Code here ....dan seterusnya. Catatan: • Review sebaiknya menggunakan Bahasa Inggris (tidak diharuskan). • Boleh lebih dari 3 cara. • Utamakan bagaimana penyelesaian kasus terlebih dahulu, optimalisasi algoritma bisa belakangan.
  5. 5. iv • Algoritma kedua dan seterusnya boleh berupa optimalisasi dari algo- ritma pertama atau algoritma-algoritma sebelumnya. Regards. Hayi Nukman (July 2011), a Created with: L TEX.
  6. 6. Daftar Isi Recycling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i1 Easy 1 1.1 The Blocks Problem . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Greedy Gift Givers . . . . . . . . . . . . . . . . . . . . . . . . 4 1.3 Number Chains . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.4 The Bases Are Loaded . . . . . . . . . . . . . . . . . . . . . . 8 1.5 Combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Medium 11 2.1 Lining Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 The Tower of Babylon . . . . . . . . . . . . . . . . . . . . . . 12 2.3 Points in Figures: Rectangles . . . . . . . . . . . . . . . . . . 14 2.4 King . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.5 Number Maze . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 Hard 23 3.1 Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.2 The Probable n-Ascendants . . . . . . . . . . . . . . . . . . . 25 3.3 Poker Hands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 Math 31 4.1 LCM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 4.2 Minimum Sum LCM . . . . . . . . . . . . . . . . . . . . . . . 32 4.3 Hendrie Sequence . . . . . . . . . . . . . . . . . . . . . . . . . 35 4.4 Modular Fibonacci . . . . . . . . . . . . . . . . . . . . . . . . 36 4.5 Polynomial coefficients . . . . . . . . . . . . . . . . . . . . . . 38 4.6 Pizza Cutting . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 v
  7. 7. vi DAFTAR ISI5 Sorting and Searching 43 5.1 Crossword Answers . . . . . . . . . . . . . . . . . . . . . . . . 43 5.2 The Department of Redundancy Department . . . . . . . . . . 47 5.3 Error Correction . . . . . . . . . . . . . . . . . . . . . . . . . 486 Other 51 6.1 Group Reverse . . . . . . . . . . . . . . . . . . . . . . . . . . 51 6.2 Testing the CATCHER . . . . . . . . . . . . . . . . . . . . . . 52 6.3 The Settlers of Catan . . . . . . . . . . . . . . . . . . . . . . . 54
  8. 8. 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 specified 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 flat 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
  9. 9. 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 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 affect on the configuration 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 specified above. There will be no syntactically incorrect commands. The Output The output should consist of the final state of the blocks world. Each original block position numbered i ( 0 ≤ i < n where n is the number
  10. 10. 3of 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 Input10move 9 onto 1move 8 over 1move 7 over 1move 6 over 1pile 8 over 6pile 8 over 5move 2 over 1move 4 over 9quitSample Output 0: 0 1: 1 9 2 4 2: 3: 3 4: 5: 5 8 7 6 6: 7: 8: 9: Miguel Revilla 2000-04-06HINT:
  11. 11. 4 BAB 1. EASY Use a two dimensional array where a[i][j] is the jth block in the ith stack. a[i][0] = i for all i, and a[i][j] = −1 for all j > 0. Then just implement the four functions carefully.1.2 Greedy Gift Givers The Problem This problem involves determining, for a group of gift-giving friends, how much more each person gives than they receive (and vice versa for those that view gift-giving with cynicism). In this problem each person sets aside some money for gift-giving and divides this money evenly among all those to whom gifts are given. However, in any group of friends, some people are more giving than others (or at least may have more acquaintances) and some people have more money than others. Given a group of friends, the money each person in the group spends on gifts, and a (sub)list of friends to whom each person gives gifts; you are to write a program that determines how much more (or less) each person in the group gives than they receive. The Input The input is a sequence of gift-giving groups. A group consists of several lines: • the number of people in the group, • a list of the names of each person in the group, • a line for each person in the group consisting of the name of the person, the amount of money spent on gifts, the number of people to whom gifts are given, and the names of those to whom gifts are given. All names are lower-case letters, there are no more than 10 people in a group, and no name is more than 12 characters in length. Money is a non-negative integer less than 2000.
  12. 12. 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 lizSample Outputdave 302laura 66owen -359vick 141amr -150liz -3
  13. 13. 6 BAB 1. EASY steve -24 dave 27 HINT: Just use some Object Oriented programming. one person class solves all your problems: class person -----int ratio -----int money -----string name make an array of them, and take all the information in. When it comes time to take a person’s (a) friends in, just loop through your list of people (p) and: person(a).ratio -= person(a).money/friends(a) person(p).ratio += person(a).money/friends(a) go through the people array once more, outputting the ratio and their name.1.3 Number Chains Given a number, we can form a number chain by 1. arranging its digits in descending order 2. arranging its digits in ascending order 3. subtracting the number obtained in (2) from the number obtained (1) to form a new number 4. and repeat these steps unless the new number has already appeared in the chain Note that 0 is a permitted digit. The number of distinct numbers in the chain is the length of the chain. You are to write a program that reads numbers and outputs the number chain and the length of that chain for each number read.
  14. 14. 7Input and OutputThe 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 Input12345678912344440Sample OutputOriginal number was 123456789987654321 - 123456789 = 864197532987654321 - 123456789 = 864197532Chain length 2Original number was 12344321 - 1234 = 30878730 - 378 = 83528532 - 2358 = 61747641 - 1467 = 6174Chain length 4Original number was 444444 - 444 = 00 - 0 = 0Chain length 2HINT
  15. 15. 8 BAB 1. EASY For each number n in the chain, transfer it to an integer array where a[i] is the ith digit of n. Sort the array ascending and convert the individual digits back into a complete number. Then iterate through the array backwards and convert the digits into another number. Subtract the former from the latter to generate your next n. Keep an array p[] that holds all values previously reached. 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 the length of the chain (which should be the number of elements in p[] +/- 1 depending on how you implemented it).1.4 The Bases Are Loaded Write a program to convert a whole number 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. Input Each input line will consist of three values. The first value will be a positive integer indicating the base of the number. The second value is a positive integer indicating the base we wish to convert to. The third value is the actual number (in the first base) that we wish to convert. This number will have letters representing any digits higher than 9 and may contain invalid “digits”. It will not exceed 10 characters. Each of the input values on a single line will be separated by at least one space. Output Program output consists of the original number followed by the string “base”, followed by the original base number, followed by the string “=” followed by the converted number followed by the string “base” followed by the new base. If the original number is invalid, output the statement original Value is an illegal base original Base number
  16. 16. 9 where original Value is replaced by the value to be converted and original Base is replaced by the original base value. Sample input 2 10 10101 5 3 126 15 11 A4C Sample output 10101 base 2 = 21 base 10 126 is an illegal base 5 number A4C base 15 = 1821 base 11 HINT: Convert each number into base 10, and then convert it into the final base. Check for invalid characters, which may be things like lowercase letters or punctuation. Basically, check that only the characters in the set {0123456789ABCDEF} are used, and that the number is legal in the given base. If you’re using Java, you can use Long.parseLong to do the base conversion, 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 the inputs.1.5 Combinations Computing the exact number of ways that N things can be taken M at a time can be a great challenge when N and/or M become very large. Challenges are the stuff of contests. Therefore, you are to make just such a computation given the following: GIVEN: 5 ≤ N ≤ 100, and 5 ≤ M ≤ 100, and M ≤ N Compute the EXACT value of:
  17. 17. 10 BAB 1. EASY N! C= (N − M )! × M ! You may assume that the final value of C will fit in a 32-bit Pascal LongInt or a C long. For the record, the exact value of 100! is: 93,326,215,443,944,152,681,699,238,856,266,700,490, 715,968,264,381,621,468,592,963,895,217,599,993,229, 915,608,941,463,976,156,518,286,253,697,920,827,223, 758,251,185,210,916,864,000,000,000,000,000,000,000,000 Input and Output The input to this program will be one or more lines each containing zero or more leading spaces, a value for N, one or more spaces, and a value for M. The last line of the input file will contain a dummy N, M pair with both values equal to zero. Your program should terminate when this line is read. The output from this program should be in the form: N things taken M at a time is C exactly. Sample Input 100 6 20 5 18 6 0 0 Sample Output 100 things taken 6 at a time is 1192052400 exactly. 20 things taken 5 at a time is 15504 exactly. 18 things taken 6 at a time is 18564 exactly.
  18. 18. 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, the pilot could only fly over the area once in a straight line, and she had to fly over as many points as possible. All points were given by means of integer coordinates in a two-dimensional space. The pilot wanted to know the largest number of points from the given set that all lie on one line. Can you write a program that calculates this number? Your program has to be efficient! Input The 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 between two consecutive inputs. The input consists of N pairs of integers, where 1 < N < 700. Each pair of integers is separated by one blank and ended by a new-line character. The list of pairs is ended with an end-of-file character. No pair will occur twice. Output For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line. The 11
  19. 19. 12 BAB 2. MEDIUM output consists of one integer representing the largest number of points that all lie on one line. Sample Input 1 1 1 2 2 3 3 9 10 10 11 Sample Output 3 HINT: computational geometry, sorting, line gradients (slopes). Try an O(n2 logn) algorithm.2.2 The Tower of Babylon Perhaps you have heard of the legend of the Tower of Babylon. Nowa- days many details of this tale have been forgotten. So now, in line with the educational nature of this contest, we will tell you the whole story: The babylonians had n types of blocks, and an unlimited supply of blocks of each type. Each type-i block was a rectangular solid with linear dimensions (xi , yi , zi ) . A block could be reoriented so that any two of its three dimensions determined the dimensions of the base and the other dimension was the height. They wanted to construct the tallest tower possible by stacking blocks. The problem was that, in building a tower, one block could only be placed on top of another block as long as the two base dimensions of the upper block were both strictly smaller than the corresponding base dimensions of the lower block. This meant, for example, that blocks oriented to have equal-sized bases
  20. 20. 13couldn’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
  21. 21. 14 BAB 2. MEDIUM Sample Output Case 1: maximum height = 40 Case 2: maximum height = 21 Case 3: maximum height = 28 Case 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 Longest Increasing Subsequence, or finding the longest path in a DAG. I prefer the latter, because you can use Floyd-Warshall with the bounds of this problem, and that’s much easier that doing LIS. Let the weight of edge (u,v) be the height of block u, if u fits on top of v, and -Inf otherwise. Then, run Floyd-Warshall, but with max instead of min. For an arbitrary graph this won’t work, but for DAG it’s just fine. At the end, maximize (a[u][v] + h[v]) across all (u,v) where h[v] is the 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, determine for each point which figures (if any) contain the point. Input There will be n( ≤ 10) rectangles descriptions, one per line. The first character will designate the type of figure (“r” for rectangle). This char- acter will be followed by four real values designating the x-y coordinates of the upper left and lower right corners.
  22. 22. 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 jfor 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 figurePoints 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.9Sample OutputPoint 1 is contained in figure 2Point 2 is contained in figure 2
  23. 23. 16 BAB 2. MEDIUM Point 2 is contained in figure 3 Point 3 is contained in figure 3 Point 4 is not contained in any figure Point 5 is contained in figure 1 Point 6 is not contained in any figure Diagrama of sample input figures and data points HINT: 2D geometry, geometry, point in rectangle. Keep an array of rectangle objects (just a package of the co-ords). For each point i with co-ordinates x and y, and each rectangle r with co-ordinates (x1 , y1 ) and (x2 , y2 ), i lies inside r if and only if: (x > x1 &&x < x2 &&y < y1 &&y > y2 ) Make sure that you’re using strict inequalities, as per the problem description.2.4 King
  24. 24. 17Once, 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
  25. 25. 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 of subsequences Si. Next m lines contain particular decisions coded in the form of quadruples si, ni, oi, ki, where oi represents operator > (coded as gt) or operator < (coded as lt) respectively. The symbols si, ni and ki have the meaning described above. The last block consists of just one line containing 0. Output The output file contains the lines corresponding to the blocks in the input file. A line contains text successful conspiracy when such a sequence does not exist. Otherwise it contains text lamentable kingdom. There is no line in the output file corresponding to the last “null” block of the input file. Sample Input 4 2 1 2 gt 0 2 2 lt 2 1 2 1 0 gt 0 1 0 lt 0 0 Sample Output lamentable kingdom successful conspiracy HINT:
  26. 26. 19math, 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 ≤ CThese 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 < / > Cas a[k + h] − a[k − 1] < / > CNow, to change the strict inequalities into non-strict inequalities, notethat, when working with integers: a[k + h] − a[k − 1] < Cis the same as a[k + h] − a[k − 1] ≤ C − 1And in the same vein: a[k + h] − a[k − 1] > C is the same as a[k − 1] − a[k + h] ≤ −(C + 1) Now, all you have to do is create the graph, and run Bellman-Ford(or so) to detect a negative weight cycle.
  27. 27. 20 BAB 2. MEDIUM2.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 maze can be traversed following any orthogonal direction (i.e., north, south, east and west). Considering that each cell represents a cost, then finding the minimum cost to travel the maze from one entry point to an exit point may pose you a reasonable challenge. Problem Your task is to find the minimum cost value to go from the top-left corner to the bottom-right corner of a given number maze of size NxM where 1 ≤ N , M ≤ 999. Note that the solution for the given example is 24. Input The input file contains several mazes. The first input line contains a positive integer defining the number of mazes that follow. Each maze is defined by: one line with the number of rows, N; one line with the number of columns, M; and N lines, one per each row of the maze, containing the maze numbers separated by spaces. Output For each maze, output one line with the required minimum value. Sample Input 2 4 5 0 3 1 2 9 7 3 4 9 9
  28. 28. 211 7 5 5 32 3 4 2 5160 1 2 3 4 5Sample Output2415University of Porto / 2003 ACM Programming Contest / Round 2 /2003/09/24HINT graph theory, shortest paths, Dijkstra (on a sparse graph), array priority queue, see CLRS exercise 24.3-6: The idea behind this problem is to find a faster way of doing Dijkstra than O(E log V), given this special type of graph (that is, one in which all weights are less than 10). This can be accomplished by using 10 queues. The idea works as such: When you want to get the next node, search all of the queues in order until you come to one that isn’t empty. Take the top node from this one. When you add a node to the queues, add it to the one that is c queues away from the one you are currently at, where c is the cost of traversing that node. For example, in the 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 3 and 7, so they go in queues (0+3)%10 and (0+7)%10 respectively. • Next, we take the node from queue 3 and examine its neight- bours. They have costs 1 and 3, so they go in queues 4 and 6 respectively. So you make your way around the queues in a circle, and you keep taking from one queue until either it is empty, or the next queue in the circle has a node at the front that has shorter distance.
  29. 29. 22 BAB 2. MEDIUM
  30. 30. 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 from the local server to the terminal server. The lab setup is not yet ready. It requires to write a router program for the best path of data. The problem is all links of the network has a fixed capacity and cannot flow more than that amount of data. Also it takes certain amount of time to send one unit data through the link. To avoid the collision at a time only one data unit can travel i.e. at any instant more than one unit of data cannot travel parallel through the network. This may be time consuming but it certainly gives no collision. Each node has sufficient buffering capability so that data can be temporarily stored there. IIUC management wants the shortest possible time to send all the data from the local server to the final one. 23
  31. 31. 24 BAB 3. HARD For example, in the above network if anyone wants to send 20 unit data from A to D, he will send 10 unit data through AD link and then 10 unit data through AB-BD link which will take 10+70=80 unit time. Input Each input starts with two positive integers N (2 N 100), M (1 M 5000). In next few lines the link and corresponding propagation time will be given. The links are bidirectional and there will be at most one link between two network nodes. In next line there will be two positive integers D, K where D is the amount of data to be transferred from 1st to 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 all the data. If it is not possible to send all the data, print ”Impossible.”. The time can be as large as 1015. Sample Input and Output Problemsetter: Md. Kamruzzaman Member of Elite Problemsetters’ Panel
  32. 32. 25 HINT: dijkstra, max flow, other graph This is a minimum-cost maximum flow problem. Basically, it’s the combination of shortest path and maximum flow. The general idea is 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, but unfortunately that’s too slow for this problem (unless you’re lucky in C perhaps). Luckily, there exists a compromise. You can run Bellman-Ford once at the beginning of the algorithm to set the graph up in such a way that Dijkstra will work from that point on. In this problem, because there are no negative costs to begin with, you don’t need Bellman-Ford at all, and you can use Dijkstra to initialize the graph, but it doesn’t matter much runtime-wise. I suggest reading the following to understand how this ”graph initialization” part works. Read the subsection ”Successive Shortest Path Algorithm”: http://www.topcoder.com/tc?module=Staticd1=tutorials d2=minimumCostFlow23.2 The Probable n-Ascendants In the biological autosomic inheritance, each characteristic of one individual is determined by a pair of genes (a gene is a part of a chromosome). When a pair of genes presents different information for one characteristic, the dominance of one gene over the other naturally influences the way an individual externally presents that characteristic.
  33. 33. 26 BAB 3. HARD In the case of total dominance, a dominant gene imposes the external appearance of its information over the other gene of the pair. The infor- mation of a recessive gene (the dominated gene) is only externally shown if there is no dominant gene in the pair. The information of a dominant gene is represented by a capital letter, while the information of a reces- sive gene is represented by a small letter. One individual that possesses a pair of genes with equal information for the same characteristic is called homozigotic, otherwise it is called heterozigotic. In the guinee-pigs, the gene for the black colour (B) is dominant over the gene for the white colour (w). The descendants’ genetic types (com- position of the pair of genes) of two parents are obtained by generating the different possible combinations of the 4 genes of the parents. Each ascendant contributes with only one gene to the pair of genes of the de- scendant. For instance, one heterozigotic guinee-pig (Bw) presents the same colour of one black homozigotic guinee-pig (BB). The descendants of two black homozigotic guinee-pigs (BB) have 100% probability of also being black homozigotic individuals. An analogous situation occurs with the descendants of two white homozigotic guinee-pigs (ww), i.e., they have 100% probability of also being white homozigotic individuals. The descendants of one black homozigotic guinee-pig (BB) and one white homozigotic guinee-pig (ww) have 100% probability of being black het- erozigotic individuals. The following figure illustrates this description. Imagine that you don’t know, for a particular guinee-pig, who were
  34. 34. 27its 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 InputBw1ww8Sample OutputBBBw 20.0%BBww 40.0%
  35. 35. 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/243.3 Poker Hands A poker deck contains 52 cards - each card has a suit which is one of clubs, diamonds, hearts, or spades (denoted C, D, H, and S in the input data). Each card also has a value which is one of 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace (denoted 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, A). For scoring purposes, the suits are unordered while the values are ordered as given above, with 2 being the lowest and ace the highest value. A poker hand consists of 5 cards dealt from the deck. Poker hands are ranked by the following partial order from lowest to highest • High Card: Hands which do not fit any higher category are ranked by the value of their highest card. If the highest cards have the same value, the hands are ranked by the next highest, and so on. • Pair: 2 of the 5 cards in the hand have the same value. Hands which both contain a pair are ranked by the value of the cards forming the pair. If these values are the same, the hands are ranked by the values of the cards not forming the pair, in decreasing order. • Two Pairs: The hand contains 2 different pairs. Hands which both contain 2 pairs are ranked by the value of their highest pair. Hands with the same highest pair are ranked by the value of their other pair. If these values are the same the hands are ranked by the value of the remaining card.
  36. 36. 29 • Three of a Kind: Three of the cards in the hand have the same value. Hands which both contain three of a kind are ranked by the value of the 3 cards. • Straight: Hand contains 5 cards with consecutive values. Hands which both contain a straight are ranked by their highest card. • Flush: Hand contains 5 cards of the same suit. Hands which are both flushes are ranked using the rules for High Card. • Full House: 3 cards of the same value, with the remaining 2 cards forming a pair. Ranked by the value of the 3 cards. • Four of a kind: 4 cards with the same value. Ranked by the value of the 4 cards. • Straight 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
  37. 37. 30 BAB 3. HARD Sample Output White wins. Black wins. Black wins. Tie. (The Decider Contest, Source: Waterloo ACM Programming Contest) HINT: adhoc • Sort both players’ hands. It’ll make the comparisons a lot easier • Check for hands by decreasing value, i.e. straight flush, then four of a kind, etc. all the way down to high card. Checking four four of a kind, then three, then two, is a lot easier than the other way around
  38. 38. BAB 4 Math“ I couldn’t repair your brakes, so I just made your horn louder. ”4.1 LCMAll 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
  39. 39. 32 BAB 4. MATH 10 0 Output for Sample Input 6 6 2 Problemsetter: Md. Kamruzzaman, Member of Elite Problemsetters’ Panel Special thanks to: Mohammad Sajjad Hossain HINT: Let P(n) be the multiset of prime factors of n. So, P(60) = 2, 2, 3, 5. The LCM of a set of numbers a1 , a2 , a3 , ..., an is the product of the 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 a factor in your LCM so far. When you factorize i+1, check if the count of each factor, j, is greater than c[j]. If it is, multiply your current LCM by j until the count is satisfied. Now, the LCM grows very quickly, so we don’t want to actually store the entire LCM in a[]. Instead, we store the last 7 or so digits before the final string of zeros. So, if our LCM was 182158203800000000, we would store ”1582038” in a[]. This can be accomplished by the following code: while(a[i] % 10 == 0) --- a[i] /= 10 a[i] %= 10000000 We keep 7 digits because the largest number we might multiply a[i] by is 6 digits long.4.2 Minimum Sum LCM
  40. 40. 33LCM (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 Input121050Sample OutputCase 1: 7Case 2: 7Case 3: 6
  41. 41. 34 BAB 4. MATH Problem setter: Md. Kamruzzaman Special Thanks: Shahriar Manzoor Miguel Revilla 2004-12-10 HINT: This is a prime factorization problem with a lot of picky cases. The first thing to see is that the prim factorization of a number is almost the minimum sum LCM set. I say almost because you have to keep copies of the same factor multipled together. For example, say N = 36. The prime factorization is 22 × 32 . Obviously the minimum set 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 the same term together, and return the sum of the products (so 4 + 9 = 13 in the above example). However, there are some issues. First there’s N = 1, and N = 23 1 − 1. For N = 1, you must output 2. This is a little bit counterituitive, because the set 1,1 contains two of the same number, and therefore, isn’t truly a set. However, by the problem definition you must have at least two numbers in your set. For N = 23 1 − 1, you must output 23 1. This is a problem if you’re using unsigned integers, of course. But I wouldn’t bother changing to signed integers or longs. Just hardcode this case. The other issue involves numbers that are powers of a single factor. So for instance 51 , or 21 0. You 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. We√ know our limit is 23 1, so we can generate all the primes up to 231 ∼ 216 = using the Sieve of Eratosthenes, and use these to factor N. Scan through the list of primes from 2 to sqrt(N), and divide N by each prime that it’s divisible by (as many times as you can). Keep track of these 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 which case N now equals the last factor of (the original) N. This is because you can have no more than one prime factor greater than the square root of the number. So if N 1, record N as another factor.
  42. 42. 354.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 element of H. Input Each test case consists of a single line containing the integer n ( 0 n 263 ) . Input is terminated with a line containing the number ‘0’ which of course should not be processed. Output For each test case, output the nth element of H on a single line. Sample Input 4 7 44 806856837013209088 0 Sample Output 2 0 3 16
  43. 43. 36 BAB 4. MATH Problem setter: Derek Kisman, University of Waterloo, Canada HINT: The sequence, strategically broken up into blocks, looks like this: 0 | 1 | 0 2 | 1 00 3 | 02 11 000 4 | 1003 0202 111 0000 5 | We note that the ith block has length 2(i−2) (excepting the first block which has length 1). Also, the ith block consists of (i-2) pieces from prior blocks, and then the number i-1. For example, the 6th block has: 1 0 0 3 (1 copy of block 4) 02 02 (2 copies of block 3) 111 (3 copies of block 2) 0000 (4 copies of block 1) 5 (the number (6-1)) As every block is defined in terms of the block before it, we can write a recursive function that simplifies the problem down until it reaches a 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 n belongs to. n − 2k is how far along the block n is. We add up the lengths of the subblocks, i × 2(k−i−1) for i from 1 to k until the cumulative sum is greater than or equal to (n − 2k ). The index i at which we stop is the number of the subblock that n belongs to. We can now simplify n down to 2(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, in which case the first 2(k−i−1) should be set to 0, and the latter should be set to 1. Be wary of double precision as it isn’t quite good enough for this problem. I would suggest doing everything in longs to avoid rounding errors. For instance, log(2 −1) gives 63, when then actual value is 63 log(2) slightly less than 63.4.4 Modular Fibonacci
  44. 44. 37The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) are definedby the recurrence:F0 = 0F1 = 1Fi = Fi−1 + Fi−2 → f or(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 6Sample 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 1 1 = Fn Fn−1 1 0and you will get the next set of Fibonacci numbers. Thus, we can derive:F2n = Fn × (Fn + 2Fn−1 ) 2 2F2n−1 = Fn + Fn−1depending on whether the number is even or odd. We can usethese formulas along with an algorithm that does O(log n) exponentia-tion to come up with the answer. Take mod m after every addition and
  45. 45. 38 BAB 4. MATH multiplication to keep the numbers small, and use longs because you may need to square numbers as large as 220 , and 240 won’t fit in an int.4.5 Polynomial coefficients The Problem The problem is to calculate the coefficients in expansion of polynomial (x1 + x2 + ... + xk )n . The Input The input will consist of a set of pairs of lines. The first line of the pair consists 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 the variables. The second line in each pair consists of k non-negative integers n1 , ..., nk , where n1 + ... + nk = n. The Output For each input pair of lines the output line should consist one integer, the coefficient by the monomial xn1 xn2 ...xnk in expansion of the polynomial 1 2 k (x1 + x2 + ... + xk )n . Sample Input 2 2 1 1 2 12 1 0 0 0 0 0 0 0 0 0 1 0 Sample Output 2 2
  46. 46. 39 HINT: Let n(k) be the power of the kth term in the monomial we’re asked to examine. Given the polynomial (x1 + x2 + ... + xl )n , we can break it up using the binomial theorem: ((x1 + ... + xk − 1) + xk )n ∑ k (nCi) × (x1 + ... + xk − 1)n − i × xi k i=1 The only term we care about is where i = n(xk), so we can through away the rest. We keep breaking this down recursively until we end up with a product of Chooses, which we can then simplify into a simple final form: n! n1 ! × n2 ! × ... × nk !4.6 Pizza Cutting When someone calls Ivan lazy, he claims that it is his intelligence that helps him to be so. If his intelligence allows him to do something at less physical effort, why should he exert more? He also claims that he always uses his brain and tries to do some work at less effort; this is not his laziness, rather this is his intellectual smartness. Once Ivan was asked to cut a pizza into seven pieces to distribute it among his friends. (Size of the pieces may not be the same. In fact, his piece will be larger than the others.) He thought a bit, and came to the conclusion that he can cut it into seven pieces by only three straight cuts through the pizza with a pizza knife. Accordingly, he cut the pizza in the following way (guess which one is Ivan’s piece):
  47. 47. 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 my computer? So he tried to do a similar (but not exactly as Ivan’s, for Ivan will criticize him for stealing his idea) job with his computer. He wrote a program that took the number of straight cuts one makes through the pizza, and output a number representing the maximum number of pizza pieces it will produce. Your job here is to write a similar program. It is ensured that Ivan’s friend won’t criticize you for doing the same job he did. Input The input file will contain a single integer N (0 = N = 210000000) in each line representing the number of straight line cuts one makes through the pizza. A negative number terminates the input. Output Output the maximum number of pizza pieces the given number of cuts can produce. Each line should contain only one output integer without any leading or trailing space. Sample Input 5 10 -100
  48. 48. 41Sample Output1656 Rezaul Alam ChowdhuryHINT: On the ith cut, you can cut through i pieces of pizza. Therefore the total number of cuts is the triangular number sequence. As you start with one piece, you must add one to all the terms. So for each input n, output n×(n+1) + 1. 2
  49. 49. 42 BAB 4. MATH
  50. 50. 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 white squares and two lists of definitions (or descriptions). One list of definitions is for “words” to be written left to right across white squares in the rows and the other list is for words to be written down white squares in the columns. (A word is a sequence of alphabetic characters.) To solve a crossword puzzle, one writes the words corresponding to the 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 black squares immediately to the left or above them are “eligible.” White squares with no squares either immediately to the left or above are also “eligible.” No other squares are numbered. All of the squares on the first row are numbered. The numbering starts with 1 and continues consecutively across white squares 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 on across all of the rest of the rows of the puzzle. The picture below illus- trates a rectangular crossword puzzle grid with appropriate numbering. 43
  51. 51. 44 BAB 5. SORTING AND SEARCHING An “across” word for a definition is written on a sequence of white squares in a row starting on a numbered square that does not follow another white square in the same row. The sequence of white squares for that word goes across the row of the numbered square, ending immediately before the next black square in the row or in the rightmost square of the row. A “down” word for a definition is written on a sequence of white squares in a column starting on a numbered square that does not follow another white square in the same column. The sequence of white squares for that word goes down the column of the numbered square, ending immediately before the next black square in the column or in the bottom square of the column. Every white square in a correctly solved puzzle contains a letter. You must write a program that takes several solved crossword puzzles as input and outputs the lists of across and down words which constitute the solutions. Input Each puzzle solution in the input starts with a line containing two integers r and c ( 1 ≤ r ≤ 10 and 1 ≤ c ≤ 10 ), where r (the first number) is the number of rows in the puzzle and c (the second number) is the number of columns. The r rows of input which follow each contain c characters (excluding the end-of-line) which describe the solution. Each of those c characters is an alphabetic character which is part of a word or the character “*”, which indicates a black square. The end of input is indicated by a line consisting of the single number 0.
  52. 52. 45OutputOutput 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*DEA0Sample Outputpuzzle #1:Across 1.AT 3.ODown 1.A 2.TOpuzzle #2:Across 1.AIM 4.DEN
  53. 53. 46 BAB 5. SORTING AND SEARCHING 7.ME 8.ONE 9.UPON 11.TO 12.SO 13.ERIN 15.SA 17.OR 18.IES 19.DEA Down 1.A 2.IMPOSE 3.MEO 4.DO 5.ENTIRE 6.NEON 9.US 10.NE 14.ROD 16.AS 18.I 20.A HINT: Keep two arrays, c[][] and n[][]. c[i][j] is the character in the ith row, jth column. n[i][j] is the crossword number in the same cell, or 0 if it’s an unnumbered white cell, or a black cell. Take your input into c[][], and then iterate through n[][] setting up all of the crossword numbers. Any white cell that is on the upper or left border is numbered, and any cell that has a black cell directly above or to the left of it is also numbered. Make sure you iterate through row by row and not column by column. Now, iterate through n[][] two more times. Once for Across words, and once for Down words. Any numbered cell on the left border or with a black cell directly to the left is the beginning of an Across word. Any numbered cell on the top border or with a black cell directly above it is the beginning of a Down word. When you find such a cell, search c[][] across or down as applicable, appending every character you come across to a temporary string, and
  54. 54. 47 stopping when you encounter the right/bottom border or a black square. Output the number of the starting cell along with your temporary string. Make sure that you print out the Across and Down headers even when the entire puzzle consists of only black squares.5.2 The Department of 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. Input The input file will contain a sequence of integers (positive, negative, and/or zero). The input file may be arbitrarily long. Output The output for this program will be a sequence of ordered pairs, separated by newlines. The first element of the pair must be an integer from the input file. The second element must be the number of times that that particular integer appeared in the input file. The elements in each pair are to be separated by space characters. The integers are to appear in the order in which they were contained in the input file. Sample Input 3 1 2 2 1 3 5 3 3 2 Sample Output 3 4 1 2 2 3 5 1
  55. 55. 48 BAB 5. SORTING AND SEARCHING HINT: Create a dynamic array of objects that hold a value and a quantity. For each number in the input, do a standard linear search for the object that has the same value, and increment its quantity. If you can’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 column has 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 0 0 0 0 0 1 1 1 1 0 1 0 1 The sums of the rows are 2, 0, 4 and 2. The sums of the columns are 2, 2, 2 and 2. Your job is to write a program that reads in a matrix and checks if it has the parity property. If not, your program should check if the parity property can be established by changing only one bit. If this is not possible either, the matrix should be classified as corrupt. Input The input file will contain one or more test cases. The first line of each test case contains one integer n (n100), representing the size of the matrix. On the next n lines, there will be n integers per line. No other integers than 0 and 1 will occur in the matrix. Input will be terminated by a value of 0 for n. Output For each matrix in the input file, print one line. If the matrix already has the parity property, print “OK”. If the parity property can be established
  56. 56. 49by 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 10Sample OutputOKChange bit (2,3)Corrupt Miguel A. Revilla 1999-01-11HINT: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.
  57. 57. 50 BAB 5. SORTING AND SEARCHING
  58. 58. 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. For example consider a string: “TOBENUMBERONEWEMEETAGAINANDAGAINUNDERBLUEI” This string has length 48. We have divided into 8 groups of equal length and so the length of each group is 6. Now we can reverse each of these eight groups to get a new string: “UNEBOTNOREBMEEMEWENIAGATAGADNAEDNUNIIEULBR” Given the string and number of groups in it, your program will have to group reverse it. Input The input file contains at most 101 lines of inputs. Each line contains at integer G (G10) which denotes the number of groups followed by a string whose length is a multiple of G. The length of the string is not greater than 100. The string contains only alpha numerals. Input is terminated by a line containing a single zero. 51
  59. 59. 52 BAB 6. OTHER Output For each line of input produce one line of output which contains the group reversed string. Sample Input 3 ABCEHSHSH 5 FA0ETASINAHGRI0NATWON0QA0NARI0 0 Output for Sample Input CBASHEHSH ATE0AFGHANISTAN0IRAQ0NOW0IRAN0 Problem-setter: Shahriar Manzoor Special Thanks: Derek Kisman HINT:6.2 Testing the CATCHER A military contractor for the Department of Defense has just com- pleted a series of preliminary tests for a new defensive missile called the CATCHER which is capable of intercepting multiple incoming offensive missiles. 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 it does have one major flaw. Although it can be fired to reach any initial elevation, it has no power to move higher than the last missile that it has intercepted. The tests which the contractor completed were computer simulations of battlefield and hostile attack conditions. Since they were only prelim- inary, the simulations tested only the CATCHER’s vertical movement capability. In each simulation, the CATCHER was fired at a sequence of offensive missiles which were incoming at fixed time intervals. The only information available to the CATCHER for each incoming missile was its height at the point it could be intercepted and where it appeared in the
  60. 60. 53sequence 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.InputThe 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.OutputOutput 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.
  61. 61. 54 BAB 6. OTHER Sample Input 389 207 155 300 299 170 158 65 -1 23 34 21 -1 -1 Sample Output Test #1: maximum possible interceptions: 6 Test #2: maximum possible interceptions: 2 HINT: keep two arrays, one for heights and one for ’values’. The values array at [i] will hold the maximum number of missles that could be intercepted should the set of missles end with i. Loop through your height array using a variable x, and for each element, loop from 0 to x-1 to find the ’best’ previously shot missle (ie the one with the highest value that is still at least as high as the current). Value[x] will be the value of the ’best’ that you found + 1 or 1 if you found nothing. Output the hightest value in the value array.6.3 The Settlers of Catan
  62. 62. 55Within 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 -- oInputThe 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.
  63. 63. 56 BAB 6. OTHER Input will be terminated by two values of 0 for n and m. Output For each test case, print the length of the longest road on a single line. Sample Input 3 2 0 1 1 2 15 16 0 2 1 2 2 3 3 4 3 5 4 6 5 7 6 8 7 8 7 9 8 10 9 11 10 12 11 12 10 13 12 14 0 0 Sample Output 2 12 Miguel A. Revilla 1999-01-11
  64. 64. Sequel IKAtlah ilMU iTudenGAn meNGajarkannya. ©Copyleft: Hayi Nukman (2011), a Created with: L TEX.

×