Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition

Prepare better with Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition, a solutions manual that breaks down complex textbook problems.

Michael Davis
Contributor
4.5
41
5 months ago
Preview (16 of 499 Pages)
100%
Purchase to unlock

Page 1

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 1 preview image

Loading page image...

Thisfile contains the exercises, hints, and solutions for Chapter 1 of thebook ”Introduction to the Design and Analysis of Algorithms,” 3rd edition, byA. Levitin.The problems that might be challenging for at least some studentsare marked byB;those that might be difficult for a majority of students aremarked byIExercises 1.11. Do some research on al-Khorezmi (also al-Khwarizmi), the man fromwhose name the word “algorithm” is derived.In particular, you shouldlearn what the origins of the words “algorithm” and “algebra” have incommon.2. Given that the official purpose of the U.S. patent system is the promo-tion of the “useful arts,” do you think algorithms are patentable in thiscountry?Should they be?3. a. Write down driving directions for going from your school to your homewith the precision required from an algorithm’s description.b. Write down a recipe for cooking your favorite dish with the precisionrequired by an algorithm.4. Design an algorithm for computingbcfor any positive integer.Be-sides assignment and comparison, your algorithm may only use the fourbasic arithmetical operations.5. Design an algorithm tofind all the common elements in two sorted listsof numbers.For example, for the lists 2, 5, 5, 5 and 2, 2, 3, 5, 5, 7, theoutput should be 2, 5, 5. What is the maximum number of comparisonsyour algorithm makes if the lengths of the two given lists areandrespectively?6. a. Findgcd(31415, 14142) by applying Euclid’s algorithm.b.Estimate how many times faster it will be tofindgcd(31415, 14142)by Euclid’s algorithm compared with the algorithm based on checkingconsecutive integers frommin{ }down togcd( )7.BProve the equalitygcd( )=gcd( mod)for every pair of positiveintegersand.8. What does Euclid’s algorithm do for a pair of integers in which thefirstis smaller than the second? What is the maximum number of times thiscan happen during the algorithm’s execution on such an input?9. a. What is the minimum number of divisions made by Euclid’s algorithmamong all inputs1 10?1

Page 2

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 2 preview image

Loading page image...

Page 3

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 3 preview image

Loading page image...

b. What is the maximum number of divisions made by Euclid’s algorithmamong all inputs1 10?10. a. Euclid’s algorithm, as presented in Euclid’s treatise, uses subtractionsrather than integer divisions.Write pseudocode for this version of Euclid’salgorithm.b.IEuclid’s game(see [Bog]) starts with two unequal positive in-tegers on the board.Two players move in turn.On each move, a playerhas to write on the board a positive number equal to the difference of twonumbers already on the board; this number must be new, i.e., differentfrom all the numbers already on the board.The player who cannot moveloses the game.Should you choose to movefirst or second in this game?11. Theextended Euclid’s algorithmdetermines not only the greatestcommon divisorof two positive integersandbut also integers (notnecessarily positive)and, such that+=a.Look up a description of the extended Euclid’s algorithm (see, e.g.,[KnuI, p. 13]) and implement it in the language of your choice.b.Modify your program tofind integer solutions to the Diophantineequation+=with any set of integer coefficients,, and.12.BLocker doorsThere arelockers in a hallway, numbered sequentiallyfrom 1 to. Initially, all the locker doors are closed. You makepassesby the lockers, each time starting with locker #1.On theth pass,=12  , you toggle the door of everyth locker: if the door is closed, youopen it; if it is open, you close it. After the last pass, which locker doorsare open and which are closed? How many of them are open?2

Page 4

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 4 preview image

Loading page image...

Hints to Exercises 1.11. It is probably faster to do this by searching the Web, but your libraryshould be able to help, too.2. One canfind arguments supporting either view.There is a well establishedprinciple pertinent to the matter, though: scientific facts or mathematicalexpressions of them are not patentable.(Why do you think it is the case?)But should this preclude granting patents for all algorithms?3. You may assume that you are writing your algorithms for a human ratherthan a machine.Still, make sure that your descriptions do not containobvious ambiguities.Knuth provides an interesting comparison betweencooking recipes and algorithms [KnuI, p.6].4. There is a quite straightforward algorithm for this problem based on thedefinition ofbc.5. Try to design an algorithm that always makes less thancomparisons.6. a. Just follow Euclid’s algorithm as described in the text.b. Compare the number of divisions made by the two algorithms.7. Prove that ifdivides bothand(i.e.,=and=for somepositive integersand), then it also divides bothand=modand vice versaUse the formula=+(0  )and the fact thatifdivides two integersandit also divides+and(Why?)8. Perform one iteration of the algorithm for two arbitrarily chosen integers  9. The answer to part (a) can be given immediately; the answer to part(b) can be given by checking the algorithm’s performance on all pairs1   1010. a. Use the equalitygcd( ) = gcd( )for 0b. The key is tofigure out the total number of distinct integers that can bewritten on the board, starting with an initial pair where  1You should exploit a connection of this question to the question of part(a).Considering small examples, especially those with= 1and= 2should help, too.11.Of course, for some coefficients, the equation will have no solutions.12. Tracing the algorithm by hand for, say,= 10and studying its outcomeshould help answering both questions.3

Page 5

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 5 preview image

Loading page image...

Solutions to Exercises 1.11. Al-Khwarizmi (9th centuryC.E.) was a great Arabic scholar, most famousfor his algebra textbook.In fact, the word “algebra” is derived from theArabic title of this book while the word “algorithm” is derived from atranslation of Al-Khwarizmi’s last name (see, e.g., [KnuI, pp. 1-2], [Knu96,pp. 88-92, 114]).2. This legal issue has yet to be settled.The current legal state of affairsdistinguishes mathematical algorithms, which are not patentable, fromother algorithms, which may be patentable if implemented as computerprograms (e.g., [Cha00]).3. n/a4. A straightforward algorithm that does not rely on the availability of anapproximate value ofcan check the squares of consecutive positiveintegers until thefirst square exceedingis encountered.The answer willbe the number’s immediate predecessor.Note: A much faster algorithmfor solving this problem can be obtained by using Newton’s method (seeSections 11.4 and 12.4).5. Initialize the list of common elements to empty. Starting with thefirst ele-ments of the lists given, repeat the following until one of the lists becomesempty.Compare the current elements of the two lists: if they are equal,add this element to the list of common elements and move to the nextelements of both lists (if any); otherwise, move to the element followingthe smaller of the two involved in the comparison.The maximum number of comparisons, which is made by this algorithmon some lists with no common elements such as thefirstpositive oddnumbers and thefirstpositive even numbers, is equal to+16. a.gcd(3141514142) = gcd(141423131) = gcd(31311618) =gcd(16181513) = gcd(1513105) = gcd(1513105) = gcd(10543) =gcd(4319) = gcd(195) = gcd(54) = gcd(41) = gcd(10) = 1b. To answer the question, we need to compare the number of divisionsthe algorithms make on the input given. The number of divisions madeby Euclid’s algorithm is 11 (see part a).The number of divisions madeby the consecutive integer checking algorithm on each of its 14142 itera-tions is either 1 and 2; hence the total number of multiplications is be-tween 1·14142 and 2·14142.Therefore, Euclid’s algorithm will be between1·14142111300and 2·14142112600times faster.4

Page 6

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 6 preview image

Loading page image...

7. Let usfirst prove that ifdivides two integersandit also dividesboth+and.By definition of division, there exist integersandsuch that=and=Therefore±=±= (±)i.e.,divides both+andAlso note that ifdividesit also divides any integer multipleofIndeed, sincedivides =Hence=() = ()i.e.,dividesNow we can prove the assertion in question.For any pair of positiveintegersandifdivides bothand, it also divides bothand=mod=Similarly, ifdivides bothand=mod=it also divides both=+andThus, the two pairs( )and( )have the samefinite nonempty set of common divisors,including the largest element in the set, i.e.,gcd( ) = gcd( )8. For any input pair such that0  Euclid’s algorithm simplyswaps the numbers on thefirst iteration:gcd( ) = gcd( )becausemod=if  Such a swap can happen only once sincegcd( ) = gcd( mod)implies that thefirst number of the new pair()will be greater than its second number(mod)after every iterationof the algorithm.9. a. For any input pair1in whichis a multiple ofEuclid’salgorithm makes exactly one division; it is the smallest number possiblefor two positive numbers.b.The answer is 5 divisions, which is made by Euclid’s algorithm incomputinggcd(58)It is not too time consuming to get this answer byexamining the number of divisions made by the algorithm on all inputpairs1   10Note:A pertinent general result (see [KnuII, p.360]) is that for anyinput pair where0  the number of divisions required byEuclid’s algorithm to computegcd( )is at mostblog(3))cwhere= (1 +5)2.5

Page 7

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 7 preview image

Loading page image...

10. a. Here is a nonrecursive version:AlgorithmEuclid2( )//Computesgcd( )by Euclid’s algorithm based on subtractions//Input: Two nonnegative integersandnot both equal to 0//Output: The greatest common divisor ofandwhile6= 0doif  swap( )returnb. It is not too difficult to prove that the integers that can be written onthe board are the integers generated by the subtraction version of Euclid’salgorithm and only them.Although the order in which they appear onthe board may vary, their total number always stays the same: It is equaltogcd( )whereis the maximum of the initial numberswhichincludes two integers of the initial pair.Hence, the total number ofpossible moves isgcd( )2Consequently, ifgcd( )is odd,one should choose to gofirst; if it is even, one should choose to go second.11. n/a12. Since all the doors are initially closed, a door will be open after the lastpass if and only if it is toggled an odd number of times.Door(1)is toggled on pass(1)if and only ifdividesHence, the totalnumber of times dooris toggled is equal to the number of its divisors.Note that ifdividesi.e.=thendividestoo.Hence all thedivisors ofcan be paired (e.g., for= 12such pairs are 1 and 12, 2and 6, 3 and 4) unlessis a perfect square (e.g., for= 164 does nothave another divisor to be matched with).This implies thathas anodd number of divisors if and only if it is a perfect square, i.e.,=2Hence doors that are in the positions that are perfect squares and onlysuch doors will be open after the last pass.The total number of suchpositions not exceedingis equal tobc: these numbers are the squaresof the positive integers between 1 andbcinclusively.6

Page 8

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 8 preview image

Loading page image...

Exercises 1.21.Old World puzzleA peasantfinds himself on a riverbank with a wolf,a goat, and a head of cabbage.He needs to transport all three to theother side of the river in his boat. However, the boat has room for onlythe peasant himself and one other item (either the wolf, the goat, or thecabbage). In his absence, the wolf would eat the goat, and the goat wouldeat the cabbage.Solve this problem for the peasant or prove it has nosolution.(Note: The peasant is a vegetarian but does not like cabbageand hence can eat neither the goat nor the cabbage to help him solve theproblem. And it goes without saying that the wolf is a protected species.)2.New World puzzleThere are four people who want to cross a ricketybridge; they all begin on the same side. You have 17 minutes to get themall across to the other side. It is night, and they have oneflashlight. Amaximum of two people can cross the bridge at one time. Any party thatcrosses, either one or two people, must have theflashlight with them. Theflashlight must be walked back and forth; it cannot be thrown, for example.Person 1 takes 1 minute to cross the bridge, person 2 takes 2 minutes,person 3 takes 5 minutes, and person 4 takes 10 minutes.A pair mustwalk together at the rate of the slower person’s pace. (Note: According toa rumor on the Internet, interviewers at a well-known software companylocated near Seattle have given this problem to interviewees.)3. Which of the following formulas can be considered an algorithm for com-puting the area of a triangle whose side lengths are given positive numbers,, and?a.=p()()()where= (++)2b.=12sinwhereis the angle between sidesandc.=12whereis the height to base4. Write pseudocode for an algorithm forfinding real roots of equation2++= 0for arbitrary real coefficients and(You may assume theavailability of the square root function())5. Describe the standard algorithm forfinding the binary representation ofa positive decimal integera. in English.b. in pseudocode.6. Describe the algorithm used by your favorite ATM machine in dispensingcash.(You may give your description in either English or pseudocode,whichever youfind more convenient.)7

Page 9

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 9 preview image

Loading page image...

7. a. Can the problem of computing the numberbe solved exactly?b. How many instances does this problem have?c. Look up an algorithm for this problem on the Internet.8. Give an example of a problem other than computing the greatest commondivisor for which you know more than one algorithm.Which of them issimpler?Which is more efficient?9. Consider the following algorithm forfinding the distance between the twoclosest elements in an array of numbers.AlgorithmMinDistance([01])//Input: Array[0..1]of numbers//Output: Minimum distance between two of its elements← ∞for0to1dofor0to1doif6=and|[][]| |[][]|returnMake as many improvements as you can in this algorithmic solution to theproblem.If you need to, you may change the algorithm altogether; if not,improve the implementation given.10. One of the most influential books on problem solving, titledHow To SolveIt[Pol57], was written by the Hungarian-American mathematician GeorgePólya (1887—1985).Pólya summarized his ideas in a four-point summary.Find this summary on the Internet or, better yet, in his book, and compareit with the plan outlined in Section 1.2.What do they have in common?How are they different?8

Page 10

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 10 preview image

Loading page image...

Hints to Exercises 1.21. The peasant would have to make several trips across the river, startingwith the only one possible.2. Unlike the Old World puzzle of Problem 1, thefirst move solving thispuzzle is not obvious.3. The principal issue here is a possible ambiguity.4. Your algorithm should work correctly for all possible values of the coeffi-cients, including zeros.5. You almost certainly learned this algorithm in one of your introductoryprogramming courses.If this assumption is not true, you have a choicebetween designing such an algorithm on your own or looking it up.6. You may need to make afield trip to refresh your memory.7. Question (a) is difficult, though the answer to it–discovered in 1760sby the German mathematician Johann Lambert –is well-known.Bycomparison, question (b) is incomparably simpler.8. You probably know two or more different algorithms for sorting an arrayof numbers.9. You can: decrease the number of times the inner loop is executed, makethat loop run faster (at least for some inputs), or, more significantly, designa faster algorithm from scratch.10. n/a9

Page 11

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 11 preview image

Loading page image...

Solutions to Exercises 1.21. LetP,w,g, andcstand for the peasant, wolf, goat, and cabbage head,respectively.The following is one of the two principal sequences thatsolve the problem:PwgcP gw cgPw cPwgcwP gcPw cgw cP gPwgcNote: This problem is revisited later in the book (see Section 6.6).2. Let 1, 2, 5, 10 be labels representing the men of the problem,representtheflashlight’s location, and the number in the parenthesis be the totalamount of time elapsed.The following sequence of moves solves theproblem:(0)1,2,5,101,2(2)5,102(3)1,5,102,5,10(13)15,10(15)1,21,2,5,10(17)3. a. The formula can be considered an algorithm if we assume that we knowhow to compute the square root of an arbitrary positive number.b.The difficulty here lies in computingsinSince the formula saysnothing about how it has to be computed, it should not be considered analgorithm.This is true even if we assume, as we did for the square rootfunction, that we know how to compute the sine of a given angle. (Thereare several algorithms for doing this but only approximately, of course.)The problem is that the formula says nothing about how to compute angleeither.c. The formula says nothing about how to compute.4.AlgorithmQuadratic(  )//The algorithmfinds real roots of equation2++= 0//Input: Real coefficients  //Output: The real roots of the equation or a message about their absenceif6= 04if 021(+())2(())10

Page 12

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 12 preview image

Loading page image...

return1 2else if= 0return(2)else return ‘no real roots’else //= 0if6= 0returnelse //== 0if= 0returnall real numberselse returnno real rootsNote: See a more realistic algorithm for this problem in Section 11.4.5. a.Divide the given numberby 2:the remainder(0 or 1) will bethe next (from right to left) digit of the binary representation in question.Replaceby the quotient of the last division and repeat this operationuntilbecomes 0.b.AlgorithmBinary()//The algorithm implements the standard method forfinding//the binary expansion of a positive decimal integer//Input: A positive decimal integer//Output: The list110of’s binary digits0while6= 0mod 2b2c+ 16. n/a7. a., as an irrational number, can be computed only approximately.b.It is natural to consider, as an instance of this problem, computing’s value with a given level of accuracy, say, withcorrect decimal digits.With this interpretation, the problem has infinitely many instances.8. n/a9. The following improved version considers the same pair of elements onlyonce and avoids recomputing the same expression in the innermost loop:AlgorithmMinDistance2([01])//Input: An array[0..1] of numbers//Output: The minimum distancebetween two of its elements11

Page 13

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 13 preview image

Loading page image...

← ∞for0to2dofor+ 1to1do|[][]|if  returnA faster algorithm is based on the idea of presorting (see Section 6.1).10. Pólya’s general four-point approach is:1. Understand the problem2. Devise a plan3. Implement the plan4. Look back/check12

Page 14

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 14 preview image

Loading page image...

Exercises 1.31. Consider the algorithm for the sorting problem that sorts an array bycounting, for each of its elements, the number of smaller elements andthen uses this information to put the element in its appropriate positionin the sorted array:AlgorithmComparisonCountingSort([01],[01])//Sorts an array by comparison counting//Input: Array[01]of orderable values//Output: Array[01]of’s elements sorted in nondecreasing orderfor0to1do[]0for0to2dofor+ 1to1doif[] [][][] + 1else[][] + 1for0to1do[[]][]a. Apply this algorithm to sorting the list 60, 35, 81, 98, 14, 47.b. Is this algorithm stable?c. Is it in place?2. Name the algorithms for the searching problem that you already know.Give a good succinct description of each algorithm in English.(If youknow no such algorithms, use this opportunity to design one.)3. Design a simple algorithm for the string-matching problem.4.Königsberg bridgesThe Königsberg bridge puzzle is universally acceptedas the problem that gave birth to graph theory.It was solved by the greatSwiss-born mathematician Leonhard Euler (1707—1783).The problemasked whether one could, in a single stroll, cross all seven bridges of thecity of Königsberg exactly once and return to a starting point.Followingis a sketch of the river with its two islands and seven bridges:13

Page 15

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 15 preview image

Loading page image...

a. State the problem as a graph problem.b. Does this problem have a solution?If you believe it does, draw sucha stroll; if you believe it does not, explain why and indicate the small-est number of new bridges that would be required to make such a strollpossible.5.Icosian GameA century after Euler’s discovery (see Problem 4), an-other famous puzzle–this one invented by the renown Irish mathemati-cian Sir William Hamilton (1805-1865)–was presented to the world underthe name of the Icosian Game.The game was played on a circular woodenboard on which the following graph was carved:Find aHamiltonian circuit–a path that visits all the graph’s verticesexactly once before returning to the starting vertex–for this graph.6. Consider the following problem:Design an algorithm to determine thebest route for a subway passenger to take from one designated station toanother in a well-developed subway system similar to those in such citiesas Washington, D.C., and London, UK.a. The problem’s statement is somewhat vague, which is typical of real-life problems.In particular, what reasonable criterion can be used fordefining the “best” route?b. How would you model this problem by a graph?7. a. Rephrase the traveling salesman problem in combinatorial object terms.b. Rephrase the graph-coloring problem in combinatorial object terms.14

Page 16

Solution Manual For Introduction To The Design And Analysis Of Algorithms, 3rd Edition - Page 16 preview image

Loading page image...

8. Consider the following map:abcdefa. Explain how we can use the graph-coloring problem to color the mapso that no two neighboring regions are colored the same.b. Use your answer to part (a) to color the map with the smallest numberof colors.9. Design an algorithm for the following problem: Given a set ofpointsin the Cartesian plane, determine whether all of them lie on the samecircumference.10. Write a program that reads as its inputs the( )coordinates of theendpoints of two line segments11and22and determines whetherthe segments have a common point.15
Preview Mode

This document has 499 pages. Sign in to access the full document!

Study Now!

XY-Copilot AI
Unlimited Access
Secure Payment
Instant Access
24/7 Support
Document Chat

Document Details

Related Documents

View all