1、Publisher Greg TobinSenior Acquisitions Editor Michael HirschEditorial Assistant Lindsey TriebelMarketing Manager Michelle BrownMarketing Assistant Dana LopreatoDigital Asset Manager Marianne GrothComposition Windfall Software, using ZzTEXProofreaders Melanie Aswell, Debbie SidmanAccess the latest i
2、nformation about Addison-Wesley titles from our World Wide Web site: http:/www.aw- of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademarkclaim, the designa
3、tions have been printed in initial caps or all caps.Copyright 2006 by Pearson Education, Inc.For information on obtaining permission for use of material in this work, please submit a written requestto Pearson Education, Inc., Rights and Contract Department, 75 Arlington Street, Suite 300, Boston, MA
4、02116 or fax your request to (617) 848-7047.All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, ortransmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or any othermedia embodiments now known or hereafter to become kn
5、own, without the prior written permission ofthe publisher. Printed in the United States of America.12345678910PDF08 07 06 05CONTENTSPreface vChapter 1 Introduction 1Chapter 2 Algorithm Analysis 5Chapter 3 Lists, Stacks, and Queues 9Chapter 4 Trees 29Chapter 5 Hashing 41Chapter 6 Priority Queues (Hea
6、ps) 45Chapter 7 Sorting 53Chapter 8 The Disjoint Set 59Chapter 9 Graph Algorithms 63Chapter 10 Algorithm Design Techniques 77Chapter 11 Amortized Analysis 87Chapter 12 Advanced Data Structures and Implementation 91iiiPREFACEIncluded in this manual are answers to many of the exercises in the textbook
7、 Data Structures andAlgorithm Analysis in C+, third edition, published by Addison-Wesley. These answers reflect thestate of the book in the first printing of the third edition.Specifically omitted are general programming questions and any question whose solution ispointed to by a reference at the en
8、d of the chapter. Solutions vary in degree of completeness; generally,minor details are left to the reader. For clarity, the few code segments that are present are meant tobe pseudo-C+ rather than completely perfect code.Errors can be reported to weissfiu.edu.vCHAPTER 1Introduction1.4 The general wa
9、y to do this is to write a procedure with headingvoid processFile( String fileName );which opens fileName, does whatever processing is needed, and then closes it. If a line of the form#include SomeFileis detected, then the callprocessFile( SomeFile );is made recursively. Self-referential includes ca
10、n be detected by keeping a list of files for which a callto processFile has not yet terminated, and checking this list before making a new call to processFile.1.5 int ones( int n )if(n v(3);v0.setValue(“George Bush“, 400000.00);v1.setValue(“Bill Gates“, 2000000000.00);v2.setValue(“Dr. Phil“, 1300000
11、0.00);cout1, the number of multiplies used isfloorleftlog Nfloorright+b(N) 12.25 (a) A.(b) B.(c) The information given is not sufficient to determine an answer. We have only worst-case bounds.(d) Yes.2.26 (a) Recursion is unnecessary if there are two or fewer elements.(b) One way to do this is to no
12、te that if the first N 1elements have a majority, then the last elementcannot change this. Otherwise, the last element could be a majority. Thus if N is odd, ignore the lastelement. Run the algorithm as before. If no majority element emerges, then return the Nthelementas a candidate.(c) The running
13、time is O(N), and satisfies T(N)= T(N/2) + O(N).(d) One copy of the original needs to be saved. After this, the B array, and indeed the recursion canbe avoided by placing each Biin the A array. The difference is that the original recursive strategyimplies that O(log N) arrays are used; this guarante
14、es only two copies.2.27 Start from the top-right corner. With a comparison, either a match is found, we go left, or we godown. Therefore, the number of comparisons is linear.2.28 (a,c) Find the two largest numbers in the array.(b,d) Similar solutions; (b) is described here. The maximum difference is
15、 at least zero (i j), sothat can be the initial value of the answer to beat. At any point in the algorithm, we have the currentvalue j, and the current low point i.Ifaj ai is larger than the current best, update the best8 Chapter 2 Algorithm Analysisdifference. If aj is less than ai, reset the curre
16、nt low point to i. Start with i at index 0, j at index0. j just scans the array, so the running time is O(N).2.29 Otherwise, we could perform operations in parallel by cleverly encoding several integers into one.For instance, if A = 001, B = 101, C = 111, D = 100, we could add A and B at the same ti
17、me as Cand D by adding 00A00C + 00B00D. We could extend this to add N pairs of numbers at once inunit cost.2.31 No. If low = 1, high = 2, then mid = 1, and the recursive call does not make progress.2.33 No. As in Exercise 2.31, no progress is made.2.34 See my textbook Algorithms, Data Structures and
18、 Problem Solving with C+ for an explanation.CHAPTER 3Lists, Stacks,and Queues3.1 template void printLots(list L, list P)typename list :const_iterator pIter ;typename list :const_iterator lIter ;int start = 0;lIter = L.begin();for (pIter=P.begin(); pIter != P.end() pIter+)while (start next;afterp = p
19、-next; / both p and afterp assumed not NULLp-next = afterp- next;beforep -next = afterp;afterp-next = p;910 Chapter 3 Lists, Stacks, and Queues(b) Here is the code for doubly linked lists:/ p and afterp are cells to be switched. Error checks as beforeNode *beforep, *afterp;beforep = p-prev;afterp =
20、p-next;p-next = afterp-next;beforep-next = afterp;afterp-next = p;p-next-prev = p;p-prev = afterp;afterp-prev = beforep;3.3 template Iterator find(Iterator start, Iterator end, const Objectwhile ( iter != end return iter;3.4 / Assumes both input lists are sortedtemplate list intersection( const list
21、 typename list: const_iterator iterL1 = L1.begin();typename list: const_iterator iterL2= L2.begin();while(iterL1 != L1.end() iterL1+;iterL2+;else if (*iterL1 list listUnion( const list typename list: const_iterator iterL1 = L1.begin();typename list: const_iterator iterL2= L2.begin();while(iterL1 !=
22、L1.end() iterL1+;iterL2+;else if (*iterL1 N/2, the potato shouldbe passed in the reverse direction. This requires a doubly linked list. The worst case running timeis clearly O(N min(M, N), although when the heuristics are used, and M and N are comparable,the algorithm might be significantly faster.
23、If M = 1, the algorithm is clearly linear.#include #include using namespace std;int main()int i,j, n, m, mPrime, numLeft;list L;list:iterator iter;/Initializationcoutnm;numLeft = n;12 Chapter 3 Lists, Stacks, and QueuesmPrime=m%n;for(I=1;I=0 Object return *current;const_iterator( const Vector friend
24、 class Vector;(b) class iterator : public const_iteratorpublic:/iterator( )/ Force use of the safe constructorObject const Object iterator ;(c) iterator begin( ) return iterator(*this , const_iterator begin( ) const return const_iterator(*this, iterator end( ) return iterator(*this, const_iterator e
25、nd( ) const return const_iterator(*this, 3.11 template struct NodeObject data;Node * next;Node ( const Objecttemplate class singleListpublic:singleList( ) init(); singleList()eraseList(head);singleList( const singleList init();*this = rhs;16 Chapter 3 Lists, Stacks, and Queuesbool add(Object x)if (c
26、ontains(x)return false;elseNode *ptr = new Node(x);ptr-next = head-next;head-next = ptr;theSize+;return true;bool remove(Object x)if (!contains(x)return false;elseNode*ptr = head-next;Node*trailer;while(ptr-data != x) trailer = ptr;ptr=ptr-next;trailer-next = ptr-next;delete ptr;theSize-;return true
27、;int size() return theSize;void print()Node *ptr = head-next;while (ptr != NULL)coutdatanext;cout * ptr = head-next;while (ptr != NULL)if (x = ptr-data)return true;elseptr = ptr- next;return false;void init()theSize = 0;head = new Node;head- next = NULL;void eraseList(Node * h)Node *ptr= h;Node *nex
28、tPtr;while(ptr != NULL)nextPtr = ptr-next;delete ptr;ptr= nextPtr;private:Node *head;int theSize;3.12 template struct NodeObject data;Node * next;Node ( const Object18 Chapter 3 Lists, Stacks, and Queuestemplate class singleListpublic:singleList( ) init(); singleList()eraseList(head);singleList( con
29、st singleList init();*this = rhs;bool add(Object x)if (contains(x)return false;elseNode *ptr = head-next;Node* trailer = head;while(ptr trailer-next = new Node (x);trailer-next-next = ptr;theSize+;return true;bool remove(Object x)if (!contains(x)return false;elseNode*ptr = head-next;Node*trailer;whi
30、le(ptr-data != x) trailer = ptr;Solutions 19ptr=ptr-next;trailer-next = ptr-next;delete ptr;theSize-;return true;int size() return theSize;void print()Node *ptr = head-next;while (ptr != NULL)coutdatanext;cout * ptr = head-next;while (ptr != NULL elseptr = ptr- next;return false;void init()theSize =
31、 0;head = new Node;head- next = NULL;void eraseList(Node * h)Node *ptr= h;Node *nextPtr;while(ptr != NULL)20 Chapter 3 Lists, Stacks, and QueuesnextPtr = ptr-next;delete ptr;ptr= nextPtr;private:Node *head;int theSize;3.13 Add the following code to the const_iterator class. Add the same code with it
32、erator replacingconst_iterator to the iterator class.const_iterator return *this;const_iterator operator- ( int )const_iterator old = *this;-( *this );return old;3.14 const_iterator for(inti=0;inext;return advanced;3.15 void splice (iterator itr, List if (itr.theList != this)throw IteratorMismatchEx
33、ception ();Node *p = iter.current;theSize += lst.size();p-prev-next = lst.head-next;lst.head-next-prev = p-prev;lst.tail-prev-next = p;p-prev = lst-tail-prev;lst.init();Solutions 213.16 The class const_reverse_iterator is almost identical to const_iterator while reverse_iterator isalmost identical t
34、o iterator. Redefine + to be and vice versa for both the pre and post operatorsfor both classes as well as changing all variables of type const_iterator to const_reverse_iteratorand changing iterator to reverse_iterator. Add two new members in list for rbegin() and rend()./ In List addconst_reverse_
35、iterator rbegin() constreturn const_reverse_iterator itr( tail);const_reverse_iterator rend() constconst_reverse_iterator itr(head);reverse_iterator rbegin()return reverse_iterator itr( tail);reverse_iterator rend()reverse_iterator itr(head);3.18 Add a boolean data member to the node class that is t
36、rue if the node is active; and false if it is “stale.”The erase method changes this data member to false; iterator methods verify that the node is notstale.3.19 Without head or tail nodes the operations of inserting and deleting from the end becomes a O(N)operation where the N is the number of eleme
37、nts in the list. The algorithm must walk down thelist before inserting at the end. With the head node insert needs a special case to account for whensomething is inserted before the first node.3.20 (a) The advantages are that it is simpler to code, and there is a possible saving if deleted keys ares
38、ubsequently reinserted (in the same place). The disadvantage is that it uses more space, becauseeach cell needs an extra bit (which is typically a byte), and unused cells are not freed.3.22 The following function evaluates a postfix expression, using +, , , / and ending in =. It requiresspaces betwe
39、en all operators and = and uses the stack, string and math.h libraries. It only recognizes0 in input as 0.0.double evalPostFix( )stack s;string token;double a, b, result;cin token;while (token0 != =)result = atof (token.c_str();if (result != 0.0 )s.push(result);22 Chapter 3 Lists, Stacks, and Queues
40、else if (token = “0.0“)s.push(result);elseswitch (token0)case +:a=s.top(); s.pop(); b = s.top();s.pop(); s.push(a+b); break;case -:a=s.top(); s.pop(); b = s.top();s.pop(); s.push(a-b); break;case *:a=s.top(); s.pop(); b = s.top();s.pop(); s.push(a*b); break;case /:a=s.top(); s.pop(); b = s.top();s.p
41、op(); s.push(a/b); break;case :a=s.top(); s.pop(); b = s.top();s.pop(); s.push(exp(a*log(b); break;cin token;return s.top();3.23 (a, b) This function will read in from standard input an infix expression of single lower casecharacters and the operators, +, , / , , and (, ), and output a postfix expre
42、ssion.void inToPostfix()stack s;char token;cin token;while (token != =)if (token = a while (!s.empty()cout s;string token;string a, b;cintoken;while (token0 != =)if (token0 = a return s.top(); /Converts postfix to infix3.24 Two stacks can be implemented in an y array by having one grow from the low
43、end of the array up,and the other from the high end down.3.25 (a) Let E be our extended stack. We will implement E with two stacks. One stack, which well callS, is used to keep track of the push and pop operations, and the other M, keeps track of the minimum.To implement E.push (x), we perform S.pus
44、h (x).Ifx is smaller than or equal to the top element instack M, then we also perform M.push (x). To implement E.pop( ) we perform S.pop().Ifx is equalto the top element in stack M, then we also M.pop().E.findMin( ) is performed by examining thetop of M. All these operations are clearly O (1).24 Cha
45、pter 3 Lists, Stacks, and Queues(b) This result follows from a theorem in Chapter 7 that shows that sorting must take Omega1(N log N)time. O (N) operations in the repertoire, including deleteMin, would be sufficient to sort.3.26 Three stacks can be implemented by having one grow from the bottom up,
46、another from the topdown and a third somewhere in the middle growing in some (arbitrary) direction. If the third stackcollides with either of the other two, it needs to be moved. A reasonable strategy is to move it so thatits center (at the time of the move) is halfway between the tops of the other
47、two stacks.3.27 Stack space will not run out because only 49 calls will be stacked. However the running time isexponential, as shown in Chapter 2, and thus the routine will not terminate in a reasonable amountof time.3.28 This requires a doubly linked list with pointers to the head and the tail In f
48、act it can be implementedwith a list by just renaming the list operations.template class dequepublic:deque() l();void push (Object obj) l.push_front(obj);Object pop (); Object obj=l.front(); l.pop_front(); return obj;void inject(Object obj); l.push_back(obj);Object eject(); pop_back(obj);private:lis
49、t l; /3.29 Reversal of a singly linked list can be done recursively using a stack, but this requires O (N) extraspace. The following solution is similar to strategies employed in garbage collection algorithms (firstrepresents the first node in the non-empty node in the non-empty list). At the top of the while loopthe list fro