Mark Allen Weiss 数据结构与算法分析 课后习题答案9
《数据结构》第九章习题参考答案
《数据结构》第九章习题参考答案《数据结构》第九章习题参考答案一、判断题(在正确说法的题后括号中打“√”,错误说法的题后括号中打“×”)1、快速排序是一种稳定的排序方法。
(×)2、在任何情况下,归并排序都比简单插入排序快。
(×)3、当待排序的元素很大时,为了交换元素的位置,移动元素要占用较多的时间,这是影响时间复杂度的主要因素。
(√)4、内排序要求数据一定要以顺序方式存储。
(×)5、直接选择排序算法在最好情况下的时间复杂度为O(n)。
( ×)6、快速排序总比简单排序快。
( ×)二、单项选择题1.在已知待排序文件已基本有序的前提下,效率最高的排序方法是(A)。
A.直接插入排序B.直接选择排序C.快速排序D.归并排序2.下列排序方法中,哪一个是稳定的排序方法?(B)A.直接选择排序B.折半插入排序C.希尔排序D.快速排序3、比较次数与排序的初始状态无关的排序方法是( B)。
A.直接插入排序B.起泡排序(时间复杂度O(n2))C.快速排序D.简单选择排序4、对一组数据(84,47,25,15,21)排序,数据的排列次序在排序的过程中的变化为(1)84 47 25 15 21 (2)15 47 25 84 21 (3)15 21 25 84 47 (4)15 21 25 47 84 则采用的排序是( A)。
A. 选择B. 冒泡C. 快速D. 插入5、快速排序方法在(D)情况下最不利于发挥其长处。
A. 要排序的数据量太大B. 要排序的数据中含有多个相同值C. 要排序的数据个数为奇数D. 要排序的数据已基本有序6、用某种排序方法对线性表{25,84,21,47,15,27,68,35,20}进行排序,各趟排序结束时的结果为:(基准)20,21,15,25,84,27,68,35,47(25)15,20,21,25,47,27,68,35,84(左20右47)15,20,21,25,35,27,47,68,84(左35右68)15,20,21,25,27,35,47,68,84 ;则采用的排序方法为(C)。
数据结构与算法分析课后题答案
Chapter 5:Hashing5.1(a)On the assumption that we add collisions to the end of the list (which is the easier way if a hash table is being built by hand),the separate chaining hash table that results is shown here.4371132361734344419996791989123456789(b)96794371198913236173434441990123456789-25-w w w .k h d a w .com课后答案网(c)96794371132361734344198941990123456789(d)1989cannot be inserted into the table because hash 2(1989)=6,and the alternative locations 5,1,7,and 3are already taken.The table at this point is as follows:4371132361739679434441991234567895.2When rehashing,we choose a table size that is roughly twice as large and prime.In our case,the appropriate new table size is 19,with hash function h (x ) = x (mod 19).(a)Scanning down the separate chaining hash table,the new locations are 4371in list 1,1323in list 12,6173in list 17,4344in list 12,4199in list 0,9679in list 8,and 1989in list 13.(b)The new locations are 9679in bucket 8,4371in bucket 1,1989in bucket 13,1323in bucket 12,6173in bucket 17,4344in bucket 14because both 12and 13are already occu-pied,and 4199in bucket 0.-26-w ww .k h d a w.com课后答案网(c)The new locations are 9679in bucket 8,4371in bucket 1,1989in bucket 13,1323in bucket 12,6173in bucket 17,4344in bucket 16because both 12and 13are already occu-pied,and 4199in bucket 0.(d)The new locations are 9679in bucket 8,4371in bucket 1,1989in bucket 13,1323in bucket 12,6173in bucket 17,4344in bucket 15because 12is already occupied,and 4199in bucket 0.5.4We must be careful not to rehash too often.Let p be the threshold (fraction of table size)atwhich we rehash to a smaller table.Then if the new table has size N ,it contains 2pN ele-ments.This table will require rehashing after either 2N − 2pN insertions or pN deletions.Balancing these costs suggests that a good choice is p = 2/ 3.For instance,suppose we have a table of size 300.If we rehash at 200elements,then the new table size is N = 150,and we can do either 100insertions or 100deletions until a new rehash is required.If we know that insertions are more frequent than deletions,then we might choose p to be somewhat larger.If p is too close to 1.0,however,then a sequence of a small number of deletions followed by insertions can cause frequent rehashing.In the worst case,if p = 1.0,then alternating deletions and insertions both require rehashing.5.5(a)Since each table slot is eventually probed,if the table is not empty,the collision can beresolved.(b)This seems to eliminate primary clustering but not secondary clustering because all ele-ments that hash to some location willtry the same collision resolution sequence.(c,d)The running time is probably similar to quadratic probing.The advantage here is thatthe insertion can’t fail unless the table is full.(e)A method of generating numbers that are not random (or even pseudorandom)is given in the references.An alternative is to use the method in Exercise 2.7.5.6Separate chaining hashing requires the use of pointers,which costs some memory,and thestandard method of implementing calls on memory allocation routines,which typically are expensive.Linear probing is easily implemented,but performance degrades severely as the load factor increases because of primary clustering.Quadratic probing is only slightly more difficult to implement and gives good performance in practice.An insertion can fail if the table is half empty,but this is not likely.Even if it were,such an insertion would be so expensive that it wouldn’t matter and would almost certainly point up a weakness in the hash function.Double hashing eliminates primary and secondary clustering,but the compu-tation of a second hash function can be costly.Gonnet and Baeza-Yates [8]compare several hashing strategies;their results suggest that quadratic probing is the fastest method.5.7Sorting the MN records and eliminating duplicates would require O (MN log MN )timeusing a standard sorting algorithm.If terms are merged by using a hash function,then the merging time is constant per term for a total of O (MN ).If the output polynomial is small and has only O (M + N )terms,then it is easy to sort it in O ((M + N )log (M + N ))time,which is less than O (MN ).Thus the total is O (MN ).This bound is better because the model is less restrictive:Hashing is performing operations on the keys rather than just com-parison between the keys.A similar bound can be obtained by using bucket sort instead of a standard sorting algorithm.Operations such as hashing are much more expensive than comparisons in practice,so this bound might not be an improvement.On the other hand,if the output polynomial is expected to have only O (M + N )terms,then using a hash table saves a huge amount of space,since under these conditions,the hash table needs only-27-w w w .k h d a w .c o m课后答案网O (M + N )space.Another method of implementing these operations is to use a search tree instead of a hash table;a balanced tree is required because elements are inserted in the tree with too much order.A splay tree might be particularly well suited for this type of a problem because it does well with sequential paring the different ways of solving the problem is a good programming assignment.5.8The table size would be roughly 60,000entries.Each entry holds 8bytes,for a total of 480,000bytes.5.9(a)This statement is true.(b)If a word hashes to a location with value 1,there is no guarantee that the word is in the dictionary.It is possible that it just hashes to the same value as some other word in the dic-tionary.In our case,the table is approximately 10%full (30,000words in a table of 300,007),so there is a 10%chance that a word that is not in the dictionary happens to hash out to a location with value 1.(c)300,007bits is 37,501bytes on most machines.(d)As discussed in part (b),the algorithm will fail to detect one in ten misspellings on aver-age.(e)A 20-page document would have about 60misspellings.This algorithm would be expected to detect 54.A table three times as large would still fit in about 100K bytes and reduce the expected number of errors to two.This is good enough for many applications,especially since spelling detection is a very inexact science.Many misspelled words (espe-cially short ones)are still words.For instance,typing them instead of then is a misspelling that won’t be detected by any algorithm.5.10To each hash table slot,we can add an extra field that we’ll call WhereOnStack, and we cankeep an extra stack.When an insertion is first performed into a slot,we push the address (or number)of the slot onto the stack and set the WhereOnStack field to point to the top of the stack.When we access a hash table slot,we check that WhereOnStack points to a valid part of the stack and that the entry in the (middle of the)stack that is pointed to by the WhereOn-Stack field has that hash table slot as an address.5.14(2)000000100000101100101011(2)01010001011000010110111101111111(3)100101101001101110011110(3)1011110110111110(2)110011111101101111110000000001010011100101110111-28-w w w .k hd a w.c o m 课后答案网。
Mark Allen Weiss 数据结构与算法分析 课后习题答案8
8.1 We assume that unions operated on the roots of the trees containing the arguments. Also, in case of ties, the second tree is made a child of the first. Arbitrary union and union by height give the same answer (shown as the first tree) for this problem. Union by size gives the second tree. 1 2 6 4 5 7 3 10 11 12 8 2 8.4 In both cases, have nodes 16 and 17 point directly to the root. Claim: A tree of height H has at least 2H nodes. The proof is by induction. A tree of height 0 clearly has at least 1 node, and a tree of height 1 clearly has at least 2. Let T be the tree of height H with fewest nodes. Thus at the time of T ’s last union, it must have been a tree of height H −1, since otherwise T would have been smaller at that time than it is now and still would have been of height H , which is impossible by assumption of T ’s minimality. Since T ’s height was updated, it must have been as a result of a union with another tree of height H −1. By the induction hypothesis, we know that at the time of the union, T had at least 2H −1 nodes, as did the tree attached to it, for a total of 2H nodes, proving the claim. Thus an N -node tree has depth at most log N . All answers are O (M ) because in all cases α(M , N ) = 1. Assuming that the graph has only nine vertices, then the union/find tree that is formed is shown here. The edge (4,6) does not result in a union because at the time it is examined, 4 and 6 are already in the same component. The connected components are {1,2,3,4,6} and 4 5 7 10 11 12 13 14 15 16 17
数据结构与算法分析 C++版答案
Data Structures and Algorithm 习题答案Preface ii1 Data Structures and Algorithms 12 Mathematical Preliminaries 53 Algorithm Analysis 174 Lists, Stacks, and Queues 235 Binary Trees 326 General Trees 407 Internal Sorting 468 File Processing and External Sorting 54 9Searching 5810 Indexing 6411 Graphs 6912 Lists and Arrays Revisited 7613 Advanced Tree Structures 82iii Contents14 Analysis Techniques 8815 Limits to Computation 94PrefaceContained herein are the solutions to all exercises from the textbook A Practical Introduction to Data Structures and Algorithm Analysis, 2nd edition.For most of the problems requiring an algorithm I have given actual code. Ina few cases I have presented pseudocode. Please be aware that the code presented in this manual has not actually been compiled and tested. While I believe the algorithmsto be essentially correct, there may be errors in syntax as well as semantics. Most importantly, these solutions provide a guide to the instructor as to the intendedanswer, rather than usable programs.1Data Structures and AlgorithmsInstructor’s note: Unlike the other chapters, many of the questions in this chapter are not really suitable for graded work. The questions are mainly intended to get students thinking about data structures issues.1.1This question does not have a specific right answer, provided the student keeps to the spirit of the question. Students may have trouble with the concept of “operations.”1.2This exercise asks the student to expand on their concept of an integer representation.A good answer is described by Project 4.5, where a singly-linkedlist is suggested. The most straightforward implementation stores each digitin its own list node, with digits stored in reverse order. Addition and multiplicationare implemented by what amounts to grade-school arithmetic. Foraddition, simply march down in parallel through the two lists representingthe operands, at each digit appending to a new list the appropriate partial sum and bringing forward a carry bit as necessary. For multiplication, combine the addition function with a new function that multiplies a single digitby an integer. Exponentiation can be done either by repeated multiplication (not really practical) or by the traditional Θ(log n)-time algorithm based on the binary representation of the exponent. Discovering this faster algorithm will be beyond the reach of most students, so should not be required.1.3A sample ADT for character strings might look as follows (with the normal interpretation of the function names assumed).Chap. 1 Data Structures and Algorithms// Concatenate two stringsString strcat(String s1, String s2);// Return the length of a stringint length(String s1);// Extract a substring, starting at ‘start’,// and of length ‘length’String extract(String s1, int start, int length);// Get the first characterchar first(String s1);// Compare two strings: the normal C++ strcmp function.Some// convention should be indicated for how to interpretthe// return value. In C++, this is 1for s1<s2; 0 for s1=s2;// and 1 for s1>s2.int strcmp(String s1, String s2)// Copy a stringint strcpy(String source, String destination)1.4The answer to this question is provided by the ADT for lists given in Chapter 4.1.5One’s compliment stores the binary representation of positive numbers, and stores the binary representation of a negative number with the bits inverted. Two’s compliment is the same, except that a negative number has its bits inverted and then one is added (for reasons of efficiency in hardware implementation).This representation is the physical implementation of an ADT。
数据结构与算法课后习题解答
数据结构与算法课后习题解答数据结构与算法课后习题解答第一章绪论(参考答案)1.3 (1) O(n)(2) (2) O(n)(3) (3) O(n)(4) (4) O(n1/2)(5) (5) 执行程序段的过程中,x,y值变化如下:循环次数x y0(初始)91 1001 92 1002 93 100。
9 100 10010 101 10011 9112。
20 9921 91 98。
30 101 9831 91 97到y=0时,要执行10*100次,可记为O(10*y)=O(n)数据结构与算法课后习题解答1.5 2100 , (2/3)n , log2n , n1/2 , n3/2 , (3/2)n , nlog2n , 2 n , n! , n n第二章线性表(参考答案)在以下习题解答中,假定使用如下类型定义:(1)顺序存储结构:#define ***** 1024typedef int ElemType;// 实际上,ElemTypetypedef struct{ ElemType data[*****];int last; // last}sequenlist;(2*next;}linklist;(3)链式存储结构(双链表)typedef struct node{ElemType data;struct node *prior,*next;数据结构与算法课后习题解答}dlinklist;(4)静态链表typedef struct{ElemType data;int next;}node;node sa[*****];2.1 la,往往简称为“链表la”。
是副产品)2.2 23voidelenum个元素,且递增有序,本算法将x插入到向量A中,并保持向量的{ int i=0,j;while (ielenum A[i]=x) i++; // 查找插入位置for (j= elenum-1;jj--) A[j+1]=A[j];// 向后移动元素A[i]=x; // 插入元素数据结构与算法课后习题解答} // 算法结束24void rightrotate(ElemType A[],int n,k)// 以向量作存储结构,本算法将向量中的n个元素循环右移k位,且只用一个辅助空间。
数据结构与算法分析习题与参考答案
大学《数据结构与算法分析》课程习题及参考答案模拟试卷一一、单选题(每题2分,共20分)1. 以下数据结构中哪一个是线性结构?()A. 有向图B.队列C. 线索二叉树D. B树2. 在一个单链表HL中,若要在当前由指针p指向的结点后面插入一个由q指向的结点,则执行如下()语句序列。
A. p=q; p_>n ext=q;B. p_>n ext=q; q_>n ext=p;C. p_>n ext=q _>n ext; p=q;D. q_>n ext=p->n ext; p_>n ext=q;3. 以下哪一个不是队列的基本运算?()A. 在队列第i个元素之后插入一个元素B. 从队头删除一个元素C.判断一个队列是否为空D. 读取队头元素的值4. 字符A、B、C依次进入一个栈,按出栈的先后顺序组成不同的字符串,至多可以组成()个不同的字符串?A. 14B.5C.6D.8由权值分别为3,8,6,2的叶子生成一棵哈夫曼树,它的带权路径长度为()5.A. 11B.35C. 19D. 536.A. E、G F、 A C D BB. E、A、G C F、B、DC. E、A、C、B D G FD. E、G A、C D F、B7.A. A 、B、 C D E、G FB. E 、A、G C F、B、DC. E 、A、C B、D G FE. B D C '、AF、G E以下6-8题基于图1。
该二叉树结点的前序遍历的序列为该二叉树结点的中序遍历的序列为(8.该二叉树的按层遍历的序列为()9.下面关于图的存储的叙述中正确的是 ()。
A .用邻接表法存储图,占用的存储空间大小只与图中边数有关,而与结点个数无关B .用邻接表法存储图,占用的存储空间大小与图中边数和结点个数都有关 C. 用邻接矩阵法存储图,占用的存储空间大小与图中结点个数和边数都有关 D .用邻接矩阵法存储图,占用的存储空间大小只与图中边数有关,而与结点个数无关10. 设有关键码序列(q , g , m z , a , n , p , x , h),下面哪一个序列是从上述序列出发建 堆的结果?()A. a , g , h , m n , p , q , x , zB. a ,g , m h , q , n , p , x , zC. g, m, q , a , n , p , x , h , z D. h,g , m p , a , n , q , x , z二、填空题(每空1分,共26分)1.数据的物理结构被分为 、、 和四种。
数据结构与算法分析-C++版答案
Data Structures and Algorithm 习题答案Preface ii1 Data Structures and Algorithms 12 Mathematical Preliminaries 53 Algorithm Analysis 174 Lists, Stacks, and Queues 235 Binary Trees 326 General Trees 407 Internal Sorting 468 File Processing and External Sorting 54 9Searching 5810 Indexing 6411 Graphs 6912 Lists and Arrays Revisited 7613 Advanced Tree Structures 82iii Contents14 Analysis Techniques 8815 Limits to Computation 94PrefaceContained herein are the solutions to all exercises from the textbook A Practical Introduction to Data Structures and Algorithm Analysis, 2nd edition.For most of the problems requiring an algorithm I have given actual code. Ina few cases I have presented pseudocode. Please be aware that the code presented in this manual has not actually been compiled and tested. While I believe the algorithmsto be essentially correct, there may be errors in syntax as well as semantics. Most importantly, these solutions provide a guide to the instructor as to the intendedanswer, rather than usable programs.1Data Structures and AlgorithmsInstructor’s note: Unlike the other chapters, many of the questions in this chapter are not really suitable for graded work. The questions are mainly intended to get students thinking about data structures issues.1.1This question does not have a specific right answer, provided the student keeps to the spirit of the question. Students may have trouble with the concept of “operations.”1.2This exercise asks the student to expand on their concept of an integer representation.A good answer is described by Project 4.5, where a singly-linkedlist is suggested. The most straightforward implementation stores each digitin its own list node, with digits stored in reverse order. Addition and multiplicationare implemented by what amounts to grade-school arithmetic. Foraddition, simply march down in parallel through the two lists representingthe operands, at each digit appending to a new list the appropriate partial sum and bringing forward a carry bit as necessary. For multiplication, combine the addition function with a new function that multiplies a single digitby an integer. Exponentiation can be done either by repeated multiplication (not re ally practical) or by the traditional Θ(log n)-time algorithm based on the binary representation of the exponent. Discovering this faster algorithm will be beyond the reach of most students, so should not be required.1.3A sample ADT for character strings might look as follows (with the normal interpretation of the function names assumed).Chap. 1 Data Structures and Algorithms// Concatenate two stringsString strcat(String s1, String s2);// Return the length of a stringint length(String s1);// Extract a substring, starting at ‘start’,// and of length ‘length’String extract(String s1, int start, int length);// Get the first characterchar first(String s1);// Compare two strings: the normal C++ strcmp function.Some// convention should be indicated for how to interpretthe// return value. In C++, this is 1for s1<s2; 0 for s1=s2;// and 1 for s1>s2.int strcmp(String s1, String s2)// Copy a stringint strcpy(String source, String destination)1.4The answer to this question is provided by the ADT for lists given in Chapter 4.1.5One’s compliment stores the binary representation of positive numbers, and stores the binary representation of a negative number with the bits inverted. Two’s compliment is the same, except that a negative number has its bits inverted and then one is added (for reasons of efficiency in hardware implementation).This representation is the physical implementation of an ADTdefined by the normal arithmetic operations, declarations, and other support given by the programming language for integers.1.6An ADT for two-dimensional arrays might look as follows.Matrix add(Matrix M1, Matrix M2);Matrix multiply(Matrix M1, Matrix M2);Matrix transpose(Matrix M1);void setvalue(Matrix M1, int row, int col, int val);int getvalue(Matrix M1, int row, int col);List getrow(Matrix M1, int row);One implementation for the sparse matrix is described in Section 12.3 Another implementationis a hash table whose search key is a concatenation of the matrix coordinates.1.7Every problem certainly does not have an algorithm. As discussed in Chapter 15, there are a number of reasons why this might be the case. Some problems don’t have a sufficiently clear definition. Some problems, such as the halting problem, are non-computable. For some problems, such as one typically studied by artificial intelligence researchers, we simply don’t know a solution.1.8We must assume that by “algorithm” we mean something composed of steps areof a nature that they can be performed by a computer. If so, than any algorithm can be expressed in C++. In particular, if an algorithm can be expressed in any other computer programming language, then it can be expressed in C++, since all (sufficiently general) computer programming languages compute the same set of functions.1.9The primitive operations are (1) adding new words to the dictionary and (2) searching the dictionary for a given word. Typically, dictionary access involves some sort of pre-processing of the word to arrive at the “root” of the word.A twenty page document (single spaced) is likely to contain about 20,000 words. A user may be willing to wait a few seconds between individual “hits” of mis-spelled words, or perhaps up to a minute for the whole document to be processed. This means that a check for an individual word can take about 10-20 ms. Users will typically insert individual words into the dictionary interactively, so this process cantake a couple of seconds. Thus, search must be much more efficient than insertion.1.10The user should be able to find a city based on a variety of attributes (name, location,perhaps characteristics such as population size). The user should also be able to insertand delete cities. These are the fundamental operations of any database system: search, insertion and deletion.A reasonable database has a time constraint that will satisfy the patience of a typicaluser. For an insert, delete, or exact match query, a few seconds is satisfactory. If thedatabase is meant to support range queries and mass deletions, the entire operation may be allowed to take longer, perhaps on the order of a minute. However, the time spent to process individual cities within the range must be appropriately reduced. Inpractice, the data representation will need to be such that it accommodates efficient processing to meet these time constraints. In particular, it may be necessary to supportoperations that process range queries efficiently by processing all cities in the range as a batch, rather than as a series of operations on individual cities.1.11Students at this level are likely already familiar with binary search. Thus, they should typically respond with sequential search and binary search. Binary search should be described as better since it typically needs to make fewer comparisons (and thus is likely to be much faster).1.12The answer to this question is discussed in Chapter 8. Typical measures of cost will be number of comparisons and number of swaps. Tests should include running timings on sorted, reverse sorted, and random lists of various sizes.Chap. 1 Data Structures and Algorithms1.13The first part is easy with the hint, but the second part is rather difficult to do withouta stack.a) bool checkstring(string S) {int count = 0;for (int i=0; i<length(S); i++)if (S[i] == ’(’) count++;if (S[i] == ’)’) {if (count == 0) return FALSE;count--;}}if (count == 0) return TRUE;else return FALSE;}b) int checkstring(String Str) {Stack S;int count = 0;for (int i=0; i<length(S); i++)if (S[i] == ’(’)S.push(i);if (S[i] == ’)’) {if (S.isEmpty()) return i;S.pop();}}if (S.isEmpty()) return -1;else return S.pop();}1.14Answers to this question are discussed in Section 7.2.1.15This is somewhat different from writing sorting algorithms for a computer, since person’s “working space” is typically limited, as is their ability to physically manipulatethe pieces of paper. Nonetheless, many of the common sorting algorithms have their analogs to solutions for this problem. Most typical answers will be insertion sort, variations on mergesort, and variations on binsort.1.16Answers to this question are discussed in Chapter 8.2Mathematical Preliminaries2.1(a) Not reflexive if the set has any members. One could argue it is symmetric, antisymmetric, and transitive, since no element violate any ofthe rules.(b)Not reflexive (for any female). Not symmetric (consider a brother and sister). Not antisymmetric (consider two brothers). Transitive (for any3 brothers).(c)Not reflexive. Not symmetric, and is antisymmetric. Not transitive(only goes one level).(d)Not reflexive (for nearly all numbers). Symmetric since a+ b= b+ a,so not antisymmetric. Transitive, but vacuously so (there can be nodistinct a, b,and cwhere aRband bRc).(e)Reflexive. Symmetric, so not antisymmetric. Transitive (but sort of vacuous).(f)Reflexive – check all the cases. Since it is only true when x= y,itis technically symmetric and antisymmetric, but rather vacuous. Likewise,it is technically transitive, but vacuous.2.2In general, prove that something is an equivalence relation by proving that it is reflexive, symmetric, and transitive.(a)This is an equivalence that effectively splits the integers into odd andeven sets. It is reflexive (x+ xis even for any integer x), symmetric(since x+ y= y+ x) and transitive (since you are always adding twoodd or even numbers for any satisfactory a, b,and c).(b)This is not an equivalence. To begin with, it is not reflexive for any integer.(c)This is an equivalence that divides the non-zero rational numbers into positive and negative. It is reflexive since x˙x>0. It is symmetric sincexy˙= yx˙. It is transitive since any two members of the given class satisfy the relationship.5Chap. 2 Mathematical Preliminaries(d)This is not an equivalance relation since it is not symmetric. For example,a=1and b=2.(e)This is an eqivalance relation that divides the rationals based on their fractional values. It is reflexive since for all a, a.a=0. It is symmetricsince if a.b=xthen b.a=.x. It is transitive since any two rationalswith the same fractional value will yeild an integer.(f)This is not an equivalance relation since it is not transitive. For example, 4.2=2and 2.0=2,but 4.0=4.2.3A relation is a partial ordering if it is antisymmetric and transitive.(a)Not a partial ordering because it is not transitive.(b)Is a partial ordering bacause it is antisymmetric (if ais an ancestor ofb, then bcannot be an ancestor of a) and transitive (since the ancestorof an ancestor is an ancestor).(c)Is a partial ordering bacause it is antisymmetric (if ais older than b,then bcannot be older than a) and transitive (since if ais older than band bis older than c, ais older than c).(d)Not a partial ordering, since it is not antisymmetric for any pair of sisters.Not a partial ordering because it is not antisymmetric.(f)This is a partial ordering. It is antisymmetric (no violations exist) and transitive (no violations exist).2.4A total ordering can be viewed as a permuation of the elements. Since there are n!permuations of nelements, there must be n!total orderings.2.5This proposed ADT is inspired by the list ADT of Chapter 4.void clear();void insert(int);void remove(int);void sizeof();bool isEmpty();bool isInSet(int);2.6This proposed ADT is inspired by the list ADT of Chapter 4. Note that while it is similiar to the operations proposed for Question 2.5, the behaviour is somewhat different.void clear();void insert(int);void remove(int);void sizeof();bool isEmpty();// Return the number of elements with a given valueintcountInBag(int);2.7The list class ADT from Chapter 4 is a sequence.2.8long ifact(int n) { // make n <= 12 so n! for long intlong fact = 1;Assert((n >= 0) && (n <= 12), "Input out of range");for (int i=1; i<= n; i++)fact = fact * i;return fact;}2.9void rpermute(int *array, int n) {swap(array, n-1, Random(n));rpermute(array, n-1);}2.10(a) Most people will find the recursive form natural and easy to understand. The iterative version requires careful examination to understand whatit does, or to have confidence that it works as claimed.(b)Fibr is so much slower than Fibi because Fibr re-computes thebulk of the series twice to get the two values to add. What is muchworse, the recursive calls to compute the subexpressions also re-computethe bulk of the series, and do so recursively. The result is an exponential explosion. In contrast, Fibicomputes each value in the seriesexactly once, and so its running time is proportional to n.2.11// Array curr[i] indicates current position of ring i.void GenTOH(int n, POLE goal, POLE t1, POLE t2,POLE* curr) {if (curr[n] == goal) // Get top n-1 rings set upGenTOH(n-1, goal, t1, t2, curr);else {if (curr[n] == t1) swap(t1, t2); // Get names right// Now, ring n is on pole t2. Put others on t1.GenTOH(n-1, t1, goal, t2, curr);move(t2, goal);GenTOH(n-1, goal, t1, t2, curr); // Move n-1 back}}2.12At each step of the way, the reduction toward the base case is only half asfar as the previous time. In theory, this series approaches, but never reaches, 0, so it will go on forever. In practice, the value should become computationally indistinguishable from zero, and terminate. However, this is terrible programming practice.Chap. 2 Mathematical Preliminaries2.13void allpermute(int array[], int n, int currpos) {if (currpos == (n-1)} {printout(array);return;}for (int i=currpos; i<n; i++) {swap(array, currpos, i);allpermute(array, n, currpos+1);swap(array, currpos, i); // Put back for next pass}}2.14In the following, function bitposition(n, i) returns the value (0 or1) at the ith bit position of integer value n. The idea is the print out the elements at the indicated bit positions within the set. If we do this for values in the range 0 to 2n.1, we will get the entire powerset.void powerset(int n) {for (int i=0; i<ipow(2, n); i++) {for (int j=0; j<n; j++)if (bitposition(n, j) == 1) cout << j << " ";cout << endl;}2.15 Proof: Assume that there is a largest prime number. Call it Pn,the nth largest prime number, and label all of the primes in order P1 =2, P2 =3,and so on. Now, consider the number Cformed by multiplying all of the nprime numbers together. The value C+1is not divisible by any of the nprime numbers. C+1is a prime number larger than Pn, a contradiction.Thus, we conclude that there is no largest prime number. .2.16Note: This problem is harder than most sophomore level students can handle.√Proof: The proof is by contradiction. Assume that 2is rational. By definition, there exist integers pand qsuch that√p2=,qwhere pand qhave no common factors (that is, the fraction p/qis in lowestterms). By squaring both sides and doing some simple algebraic manipulation, we get2p2=2q22= pSince p2 must be even, p must be even. Thus,222q=4(p)222q=2(p)2This implies that q2 is also even. Thus, pand qare both even, which contra√dicts the requirement that pand qhave no common factors. Thus, 2mustbe irrational. .2.17The leftmost summation sums the integers from 1 to n. The second summation merely reverses this order, summing the numbers from n.1+1=ndown to n.n+1=1. The third summation has a variable substitution ofi.1for i, with a corresponding substitution in the summation bounds. Thus, it is also the summation of n.0=n.(n.1)=1.2.18 Proof:(a) Base case.For n=1, 12 = [2(1)3 +3(1)2 +1]/6=1. Thus, the formula is correct for the base case. (b) Induction Hypothesis.n.12(n.1)3 +3(n.1)2 +(n.1)i2 =.6i=1(c) Induction Step.nn.1i2 i2 +n2=i=1 i=12(n.1)3 +3(n.1)2 +(n.2=+n62n3 .6n2 +6n.2+3n2 .6n+3+n.1 2=+n62n3 +3n2 +n=.6Thus, the theorem is proved by mathematical induction. .2.19 Proof:(a) Base case.For n=1, 1/2=1.1/2=1/2. Thus, the formula iscorrect for the base case.(b) Induction Hypothesis.n.111=1.2in.1 2i=1Chap. 2 Mathematical Preliminaries(c) Induction Step.nn.11 11=+iin222i=1 i=111=1.+n.1 n221=1..n2Thus, the theorem is proved by mathematical induction. .2.20 Proof:(a) Base case. For n=0, 20 =21 .1=1. Thus, the formula is correctfor the base case.(b) Induction Hypothesis.n.12i=2n.1.i=0(c) Induction Step.nn.12i=2i+2ni=0 i=0n=2n.1+2n+1 .1=2.Thus, the theorem is proved by mathematical induction. .2.21 The closed form solution is 3n+1.3, which I deduced by noting that 3F (n).2n+1 .3F(n)=2F(n)=3. Now, to verify that this is correct, use mathematicalinduction as follows.For the base case, F(1)=3=32.3 .n.1The induction hypothesis is that =(3n.3)/2.i=1So,nn.13i=3i+3ni=1 i=13n.3n= +32n+1 .33= .2Thus, the theorem is proved by mathematical induction.n2.22 Theorem 2.1 (2i)=n2 +n.i=1(a) Proof: We know from Example 2.3 that the sum of the first noddnumbers is n2.The ith even number is simply one greater than the ith odd number. Since we are adding nsuch numbers, the sum must be n greater, or n2 +n. .(b) Proof: Base case: n=1yields 2=12 +1, which is true.Induction Hypothesis:n.12i=(n.1)2 +(n.1).i=1Induction Step: The sum of the first neven numbers is simply the sum of the first n.1even numbers plus the nth even number.nn.12i=( 2i)+2ni=1 i=1=(n.1)2 +(n.1)+2n=(n2 .2n+1)+(n.1)+2n= n2 .n+2n= n2 +n.nThus, by mathematical induction, 2i=n2 +n. .i=12.23 Proof:52Base case. For n=1,Fib(1) = 1 <3.For n=2,Fib(2) = 1 <(5).3Thus, the formula is correct for the base case. Induction Hypothesis. For all positive integers i<n,5 iFib(i)<().3Induction Step. Fib(n)=Fib(n.1)+Fib(n.2)and, by the InductionHypothesis, Fib(n.1)<(5)n.1 and Fib(n.2)<(5)n.2.So,3355 n.2Fib(n) < ()n.1 +()3355 5 n.2<()n.2 +()333Chap. 2 Mathematical Preliminaries85 n.2= ()3355 n.2<()2()33n5= .3Thus, the theorem is proved by mathematical induction. .2.24 Proof:12(1+1)23 =(a) Base case. For n=1, 1=1. Thus, the formula is correct4for the base case.(b) Induction Hypothesis.n.122(n1)ni3 = .4i=0(c) Induction Step. n2(n.1)n2i33=+n4i=02n4 .2n3 +n3=+n4n4 +2n3 +n2=4n2(n2 +2n+2)=2n2(n+1)=4Thus, the theorem is proved by mathematical induction..2.25(a) Proof: By contradiction. Assume that the theorem is false. Then, each pigeonhole contains at most 1 pigeon. Since there are nholes, there isroom for only npigeons. This contradicts the fact that a total of n+1pigeons are within the nholes. Thus, the theorem must be correct. .(b) Proof:i. Base case.For one pigeon hole and two pigeons, there must betwo pigeons in the hole.ii. Induction Hypothesis.For npigeons in n.1holes, some holemust contain at least two pigeons.iii. Induction Step. Consider the case where n+1pigeons are in nholes. Eliminate one hole at random. If it contains one pigeon, eliminate it as well, and by the induction hypothesis some otherhole must contain at least two pigeons. If it contains no pigeons, then again by the induction hypothesis some other hole must contain at least two pigeons (with an extra pigeon yet to be placed). Ifit contains more than one pigeon, then it fits the requirements of the theorem directly..2.26 (a)When we add the nth line, we create nnew regions. But, we startwith one region even when there are no lines. Thus, the recurrence is F(n)=F(n.1)+n+1.(b) This is equivalent to the summation F(n)=1+ i=1 ni.(c) This is close to a summation we already know (equation 2.1).2.27 Base case: T(n.1)=1=1(1+1)/2.Induction hypothesis: T(n.1)=(n.1)(n)/2.Induction step:T(n)= T(n.1)+n=(n1)(n)/2+n= n(n+1)/2.Thus, the theorem is proved by mathematical induction.2.28 If we expand the recurrence, we getT(n)=2T(n.1)+1=2(2T(n.2)+1)+1)=4T(n.2+2+1.Expanding again yieldsT(n)=8T(n.3)+4+2+1.From this, we can deduce a pattern and hypothesize that the recurrence is equivalent tonT(n)= .12i=2n.1.i=0To prove this formula is in fact the proper closed form solution, we use mathematical induction.Base case: T(1)=21 .1=1.Chap. 2 Mathematical PreliminariesInduction hypothesis: T(n.1)=2n.1 .1.Induction step:T(n)=2T(n.1)+1= 2(2n.1 .1) + 1=2n.1.Thus, as proved by mathematical induction, this formula is indeed the correct closed form solution for the recurrence.2.29 (a)The probability is 0.5 for each choice.(b)The average number of “1” bits is n/2, since each position has 0.5probability of being “1.”(c)The leftmost “1” will be the leftmost bit (call it position 0) with probability 0.5; in position 1 with probability 0.25, and so on. The numberof positions we must examine is 1 in the case where the leftmost “1” isin position 0; 2 when it is in position 1, and so on. Thus, the expectedcost is the value of the summationni.i=1The closed form for this summation is 2 .n+2, or just less than two.2nThus, we expect to visit on average just less than two positions. (Students at this point will probably not be able to solve this summation,and it is not given in the book.)2.30There are at least two ways to approach this problem. One is to estimate the volume directly. The second is to generate volume as a function of weight. This is especially easy if using the metric system, assuming that the human body is roughly the density of water. So a 50 Kilo person has a volumeslightly less than 50 liters; a 160 pound person has a volume slightly less than 20 gallons.2.31(a) Image representations vary considerably, so the answer will vary as a result. One example answer is: Consider VGA standard size, full-color(24 bit) images, which is 3 ×640 ×480, or just less than 1 Mbyte perimage. The full database requires some 30-35 CDs.(b)Since we needed 30-35 CDs before, compressing by a factor of 10 isnot sufficient to get the database onto one CD.[Note that if the student picked a smaller format, such as estimating the size of a “typical” gif image, the result might well fit onto a sin gle CD.](I saw this problem in John Bentley’s Programming Pearls.) Approach 1:The model is Depth X Width X Flow where Depth and Width are in milesand Flow is in miles/day. The Mississippi river at its mouth is about 1/4 mile wide and 100 feet (1/50 mile) deep, with a flow of around 15 miles/hour =360 miles/day. Thus, the flow is about 2 cubic miles/day.Approach 2: What goes out must equal what goes in. The model is Area XRainfall where Area is in square miles and Rainfall is in (linear) miles/day. The Mississipi watershed is about 1000 X 1000 miles, and the average rainfalis about 40 inches/year ≈.1 inches/day ≈.000002 miles/day (2 X 10.6).Thus, the flow is about 2 cubic miles/day.2.33Note that the student should NOT be providing answers that look like theywere done using a calculator. This is supposed to be an exercise in estimation! The amount of the mortgage is irrelevant, since this is a question about rates. However, to give some numbers to help you visualize the problem, pick a$100,000 mortgage. The up-front charge would be $1,000, and the savingswould be 1/4% each payment over the life of the mortgage. The monthlycharge will be on the remaining principle, being the highest at first and gradually reducing over time. But, that has little effect for the first few years.At the grossest approximation, you paid 1% to start and will save 1/4% each year, requiring 4 years. To be more precise, 8% of $100,000 is $8,000, while7 3/4% is $7,750 (for the first year), with a little less interest paid (and therefore saved) in following years. This will require a payback period of slightlyover 4 years to save $1000. If the money had been invested, then in 5 yearsthe investment would be worth about $1300 (at 5would be close to 5 1/2years.2.34Disk drive seek time is somewhere around 10 milliseconds or a little lessin 2000. RAM memory requires around 50 nanoseconds – much less thana microsecond. Given that there are about 30 million seconds in a year, a machine capable of executing at 100 MIPS would execute about 3 billionbillion (3 .1018) instructions in a year.2.35Typical books have around 500 pages/inch of thickness, so one million pages requires 2000 inches or 150-200 feet of bookshelf. This would be in excess of50 typical shelves, or 10-20 bookshelves. It is within the realm of possibility that an individual home has this many books, but it is rather unusual.2.36A typical page has around 400 words (best way to derive this is to estimatethe number of words/line and lines/page), and the book has around 500 pages,so the total is around 200,000 words.16Chap. 2 Mathematical Preliminaries2.37An hour has 3600 seconds, so one million seconds is a bit less than 300 hours.A good estimater will notice that 3600 is about 10% greater than 3333, so the actual number of hours is about 10% less than 300, or close to 270. (The real value is just under 278). Of course, this is just over 11 days.2.38Well over 100,000, depending on what you wish to classify as a city or town. The real question is what technique the student uses.2.39(a) The time required is 1 minute for the first mile, then 60/59 minutesfor the second mile, and so on until the last mile requires 60/1=60minutes. The result is the following summation.60 6060/i=60 1/i=60H60.i=1 i=1(b)This is actually quite easy. The man will never reach his destination,since his speed approaches zero as he approaches the end of the journey.。
数据结构与算法设计课后习题及答案详解
第一章1.数据结构研究的主要内容包括逻辑结构、存储结构和算法。
2.数据元素是数据的基本单位,数据项是数据的最小标示单位。
3.根据数据元素之间关系的不同,数据的逻辑结构可以分为集合、树形、线性、图状。
4.常见的数据存储结构有四种类型:顺序、链式、索引、散列。
5.可以从正确性、可读性、健壮性、高效性四方面评价算法的质量。
6.在一般情况下,一个算法的时间复杂度是问题规模的函数。
7.常见时间复杂度有:常数阶O(1)、线性阶O(n)、对数阶O(log2 n)、平方阶O(n²)和指数阶O(2ⁿ)。
通常认为,具有常数阶量级的算法是好算法,而具有指数阶量级的算法是差算法。
8.时间复杂度排序由大到小(n+2)!>2ⁿ+²>(n+2)4次方>nlog2 n>100000.问答题:1.什么叫数据元素?数据元素是数据的基本单位,是数据这个集合的个体,也称为元素、结点、顶点、记录。
2.什么叫数据逻辑结构?什么叫数据存储结构?数据逻辑结构:指数据元素之间存在的固有的逻辑结构。
数据存储结构:数据元素及其关系在计算机内的表示。
3.什么叫抽象数据类型?抽象数据类型是指数据元素集合以及定义在该集合上的一组操作。
4.数据元素之间的关系在计算机中有几种表示方法?顺序、链式、索引、散列。
5.数据的逻辑结构与数据的存储结构之间存在着怎样的关系?相辅相成,不可分割。
6.什么叫算法?算法的性质有哪些?算法:求解问题的一系列步骤的集合。
可行性、有容性、确定性、有输入、有输出。
7.评价一个算法的好坏应该从哪几方面入手?正确性、可读性、健壮性、高效性。
第二章1.线性表中,第一个元素没有直接前驱,最后一个元素没有直接后继。
2.线性表常用的两种存储结构分别是顺序存储结构和链式存储结构。
3.在长度为n的顺序表中,插入一个新元素平均需要移动表中的n/2个元素,删除一个元素平均需要移动(n-1)/2个元素。
4.在长度为n的顺序表的表头插入一个新元素的时间复杂度为O(n),在表尾插入一个新元素的时间复杂度为O(1)。
算法与数据结构课后答案9-11章
算法与数据结构课后答案9-11章第9章集合一、基础知识题9.1 若对长度均为n 的有序的顺序表和无序的顺序表分别进行顺序查找,试在下列三种情况下分别讨论二者在等概率情况下平均查找长度是否相同?(1)查找不成功,即表中没有和关键字K 相等的记录;(2)查找成功,且表中只有一个和关键字K 相等的记录;(3)查找成功,且表中有多个和关键字K 相等的记录,要求计算有多少个和关键字K 相等的记录。
【解答】(1)平均查找长度不相同。
前者在n+1个位置均可能失败,后者失败时的查找长度都是n+1。
(2)平均查找长度相同。
在n 个位置上均可能成功。
(3)平均查找长度不相同。
前者在某个位置上(1<=i<=n)查找成功时,和关键字K 相等的记录是连续的,而后者要查找完顺序表的全部记录。
9.2 在查找和排序算法中,监视哨的作用是什么?【解答】监视哨的作用是免去查找过程中每次都要检测整个表是否查找完毕,提高了查找效率。
9.3 用分块查找法,有2000项的表分成多少块最理想?每块的理想长度是多少?若每块长度为25 ,平均查找长度是多少?【解答】分成45块,每块的理想长度为45(最后一块长20)。
若每块长25,则平均查找长度为ASL=(80+1)/2+(25+1)/2=53.5(顺序查找确定块),或ASL=19(折半查找确定块)。
9.4 用不同的输入顺序输入n 个关键字,可能构造出的二叉排序树具有多少种不同形态? 【解答】 9.5 证明若二叉排序树中的一个结点存在两个孩子,则它的中序后继结点没有左孩子,中序前驱结点没有右孩子。
【证明】根据中序遍历的定义,该结点的中序后继是其右子树上按中序遍历的第一个结点,即右子树上值最小的结点:叶子结点或仅有右子树的结点,没有左孩子;而其中序前驱是其左子树上按中序遍历的最后个结点,即左子树上值最大的结点:叶子结点或仅有左子树的结点,没有右孩子。
命题得证。
9.6 对于一个高度为h 的A VL 树,其最少结点数是多少?反之,对于一个有n 个结点的A VL 树,其最大高度是多少? 最小高度是多少?【解答】设以N h 表示深度为h 的A VL 树中含有的最少结点数。
数据结构与算法设计课后习题及答案详解
第一章1.数据结构研究的主要内容包括逻辑结构、存储结构和算法。
2.数据元素是数据的基本单位,数据项是数据的最小标示单位。
3.根据数据元素之间关系的不同,数据的逻辑结构可以分为集合、树形、线性、图状。
4.常见的数据存储结构有四种类型:顺序、链式、索引、散列。
5.可以从正确性、可读性、健壮性、高效性四方面评价算法的质量。
6.在一般情况下,一个算法的时间复杂度是问题规模的函数。
7.常见时间复杂度有:常数阶O(1)、线性阶O(n)、对数阶O(log2 n)、平方阶O(n²)和指数阶O(2ⁿ)。
通常认为,具有常数阶量级的算法是好算法,而具有指数阶量级的算法是差算法。
8.时间复杂度排序由大到小(n+2)!>2ⁿ+²>(n+2)4次方>nlog2 n>100000.问答题:1.什么叫数据元素?数据元素是数据的基本单位,是数据这个集合的个体,也称为元素、结点、顶点、记录。
2.什么叫数据逻辑结构?什么叫数据存储结构?数据逻辑结构:指数据元素之间存在的固有的逻辑结构。
数据存储结构:数据元素及其关系在计算机内的表示。
3.什么叫抽象数据类型?抽象数据类型是指数据元素集合以及定义在该集合上的一组操作。
4.数据元素之间的关系在计算机中有几种表示方法?顺序、链式、索引、散列。
5.数据的逻辑结构与数据的存储结构之间存在着怎样的关系?相辅相成,不可分割。
6.什么叫算法?算法的性质有哪些?算法:求解问题的一系列步骤的集合。
可行性、有容性、确定性、有输入、有输出。
7.评价一个算法的好坏应该从哪几方面入手?正确性、可读性、健壮性、高效性。
第二章1.线性表中,第一个元素没有直接前驱,最后一个元素没有直接后继。
2.线性表常用的两种存储结构分别是顺序存储结构和链式存储结构。
3.在长度为n的顺序表中,插入一个新元素平均需要移动表中的n/2个元素,删除一个元素平均需要移动(n-1)/2个元素。
4.在长度为n的顺序表的表头插入一个新元素的时间复杂度为O(n),在表尾插入一个新元素的时间复杂度为O(1)。
数据结构与算法分析—c语言描述 课后答案
Solutions Manual
Mark Allen Weiss Florida International University
Preface Included in this manual are answers to most of the exercises in the textbook Data Structures and Algorithm Analysis in C, second edition, published by Addison-Wesley. These answers reflect the state of the book in the first printing. Specifically omitted are likely programming assignments and any question whose solution is pointed to by a reference at the end of the chapter. Solutions vary in degree of completeness; generally, minor details are left to the reader. For clarity, programs are meant to be pseudo-C rather than completely perfect code. Errors can be reported to weiss@fi. Thanks to Grigori Schwarz and Brian Harvey for pointing out errors in previous incarnations of this manual.
Mark Allen Weiss 数据结构与算法分析 课后习题答案2
Chapter 2:Algorithm Analysis2.12/N ,37,√ N ,N ,N log log N ,N log N ,N log (N 2),N log 2N ,N 1.5,N 2,N 2log N ,N 3,2N / 2,2N .N log N and N log (N 2)grow at the same rate.2.2(a)True.(b)False.A counterexample is T 1(N ) = 2N ,T 2(N ) = N ,and f (N ) = N .(c)False.A counterexample is T 1(N ) = N 2,T 2(N ) = N ,and f (N ) = N 2.(d)False.The same counterexample as in part (c)applies.2.3We claim that N log N is the slower growing function.To see this,suppose otherwise.Then,N ε/ √ log N would grow slower than log N .Taking logs of both sides,we find that,under this assumption,ε/ √ log N log N grows slower than log log N .But the first expres-sion simplifies to ε√ logN .If L = log N ,then we are claiming that ε√ L grows slower than log L ,or equivalently,that ε2L grows slower than log 2 L .But we know that log 2 L = ο (L ),so the original assumption is false,proving the claim.2.4Clearly,log k 1N = ο(log k 2N )if k 1 < k 2,so we need to worry only about positive integers.The claim is clearly true for k = 0and k = 1.Suppose it is true for k < i .Then,by L’Hospital’s rule,N →∞lim N log i N ______ = N →∞lim i N log i −1N _______The second limit is zero by the inductive hypothesis,proving the claim.2.5Let f (N ) = 1when N is even,and N when N is odd.Likewise,let g (N ) = 1when N is odd,and N when N is even.Then the ratio f (N ) / g (N )oscillates between 0and ∞.2.6For all these programs,the following analysis will agree with a simulation:(I)The running time is O (N ).(II)The running time is O (N 2).(III)The running time is O (N 3).(IV)The running time is O (N 2).(V) j can be as large as i 2,which could be as large as N 2.k can be as large as j ,which is N 2.The running time is thus proportional to N .N 2.N 2,which is O (N 5).(VI)The if statement is executed at most N 3times,by previous arguments,but it is true only O (N 2)times (because it is true exactly i times for each i ).Thus the innermost loop is only executed O (N 2)times.Each time through,it takes O ( j 2) = O (N 2)time,for a total of O (N 4).This is an example where multiplying loop sizes can occasionally give an overesti-mate.2.7(a)It should be clear that all algorithms generate only legal permutations.The first two algorithms have tests to guarantee no duplicates;the third algorithm works by shuffling an array that initially has no duplicates,so none can occur.It is also clear that the first two algorithms are completely random,and that each permutation is equally likely.The third algorithm,due to R.Floyd,is not as obvious;the correctness can be proved by induction.SeeJ.Bentley,"Programming Pearls,"Communications of the ACM 30(1987),754-757.Note that if the second line of algorithm 3is replaced with the statementSwap(A[i],A[RandInt(0,N-1)]);then not all permutations are equally likely.To see this,notice that for N = 3,there are 27equally likely ways of performing the three swaps,depending on the three random integers.Since there are only 6permutations,and 6does not evenly divide27,each permutation cannot possibly be equally represented.(b)For the first algorithm,the time to decide if a random number to be placed in A [i ]has not been used earlier is O (i ).The expected number of random numbers that need to be tried is N / (N − i ).This is obtained as follows:i of the N numbers would be duplicates.Thus the probability of success is (N − i ) / N .Thus the expected number of independent trials is N / (N − i ).The time bound is thusi =0ΣN −1N −i Ni ____ < i =0ΣN −1N −i N 2____ < N 2i =0ΣN −1N −i 1____ < N 2j =1ΣN j 1__ = O (N 2log N )The second algorithm saves a factor of i for each random number,and thus reduces the time bound to O (N log N )on average.The third algorithm is clearly linear.(c,d)The running times should agree with the preceding analysis if the machine has enough memory.If not,the third algorithm will not seem linear because of a drastic increase for large N .(e)The worst-case running time of algorithms I and II cannot be bounded because there is always a finite probability that the program will not terminate by some given time T .The algorithm does,however,terminate with probability 1.The worst-case running time of the third algorithm is linear -its running time does not depend on the sequence of random numbers.2.8Algorithm 1would take about 5days for N = 10,000,14.2years for N = 100,000and 140centuries for N = 1,000,000.Algorithm 2would take about 3hours for N = 100,000and about 2weeks for N = 1,000,000.Algorithm 3would use 1⁄12minutes for N = 1,000,000.These calculations assume a machine with enough memory to hold the array.Algorithm 4solves a problem of size 1,000,000in 3seconds.2.9(a)O (N 2).(b)O (N log N ).2.10(c)The algorithm is linear.2.11Use a variation of binary search to get an O (log N )solution (assuming the array is preread).2.13(a)Test to see if N is an odd number (or 2)and is not divisible by 3,5,7,...,√N .(b)O (√ N ),assuming that all divisions count for one unit of time.(c)B = O (log N ).(d)O (2B / 2).(e)If a 20-bit number can be tested in time T ,then a 40-bit number would require about T 2time.(f)B is the better measure because it more accurately represents the size of the input.2.14The running time is proportional to N times the sum of the reciprocals of the primes lessthan N .This is O (N log log N ).See Knuth,Volume2,page394.2.15Compute X 2,X 4,X 8,X 10,X 20,X 40,X 60,and X 62.2.16Maintain an array PowersOfX that can befilled in a for loop.The array will contain X ,X 2,X 4,up to X 2 log N .The binary representation of N (which can be obtained by testing even or odd and then dividing by2,until all bits are examined)can be used to multiply the appropriate entries of the array.2.17For N =0or N =1,the number of multiplies is zero.If b (N )is the number of ones in thebinary representation of N ,then if N >1,the number of multiplies used islog N + b (N )−12.18(a)A .(b)B .(c)The information given is not sufficient to determine an answer.We have only worst-case bounds.(d)Yes.2.19(a)Recursion is unnecessary if there are two or fewer elements.(b)One way to do this is to note that if thefirst N −1elements have a majority,then the lastelement cannot change this.Otherwise,the last element could be a majority.Thus if N is odd,ignore the last element.Run the algorithm as before.If no majority element emerges, then return the N th element as a candidate.(c)The running 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 recur-sion can be avoided by placing each B i in the A array.The difference is that the original recursive strategy implies that O (log N )arrays are used;this guarantees only two copies. 2.20Otherwise,we could perform operations in parallel by cleverly encoding several integersinto one.For instance,if A=001,B=101,C=111,D=100,we could add A and B at the same time as C and D by adding00A00C+00B00D.We could extend this to add N pairs of numbers at once in unit cost.2.22No.If Low =1,High =2,then Mid =1,and the recursive call does not make progress. 2.24No.As in Exercise2.22,no progress is made.。
数据结构课后习题答案第九章 查找
第九章9.1 若对大小均为n的有序顺序表和无序顺序表分别进行顺序查找,试在下列三种情况下分别讨论两者在等概率时平均查找长度是否相同?(1)查找不成功,即表中没有关键字等于给的值K的记录;(2)查找成功,且表中只有一个关键字等于给定值K的记录;(3)查找成功,且表中有若干关键字等于给定值K的记录,要求找出所有这些记录。
答:(1)相同,有序n+1; 无序n+1(2)相同,有序12n+;无序12n+(3)不相同,对于有序表,找到了第一个与K相同的元素后,只要再找到与K 不同的元素,即可停止查找;对于无序表,则要一直查找到最后一个元素。
9.3 画出对长度为10的有序表进行折半查找的判定树,并分别求其等概率时查找成功和查找不成功的ASL。
查找成功:ASL=1/10(1*1+2*2+3*4+4*3)=2.92.设顺序表中关键字是递增有序的,试写一顺序查找算法,将哨兵设在表的高下标端。
然后求出等概率情况下查找成功与失败时的ASL。
【分析】因为顺序表中关键字是递增有序的,所以从低下标端开始顺序查找,若当前的关键码比要查找的关键码大,说明查找失败,终止查找。
【解答】(1)算法int seqsearch(SeqList R,KeyType K){int i;R[n]=K; // 设置哨兵i=0;while (R[i].key<K)i++;if (R[i].key==K)return i% n;elsereturn 0;}(2)查找长度成功情况:ASL succ=(1+2+3+……+n)/n=(n+1)/2失败情况:K<R[0].key时,比较1次,就终止查找;R[0].key<K< R[1].key时,比较2次,就终止查找;R[1].key<K< R[2].key时,比较3次,就终止查找;…R[n-2].key<K< R[n-1].key时,比较n次,就终止查找;R[n-1].key<K时,比较n+1次,就终止查找;所以ASL unsucc=((1+2+3+……+n+(n+1))/(n+1)=(n+2)/2。
数据结构第九章查找习题解答
第九章查找 习题解答9.5 画出对长度为10的有序表进行折半查找的判定树,并求其等概率时查找成功的平均查找长度。
解:求得的判定树如下: 57109643182ASL 成功=(1+2*2+4*3+3*4)/10 =2.99.9 已知如下所示长度为12的表(Jan,Feb,Mar,Apr,May,June,July,Aug,Sep,Oct,Nov,Dec )(1)试按表中元素的顺序依次插入一查初始为空的二叉排序树,画出插入完成之后的二叉排序树,并求其在等概率的情况下查找成功的平均查找长度。
(2)若对表中元素先进行排序构成有序表,求在等概率的情况下对此有序表进行折半查找时查找成功的平均查找长度。
解:(1)求得的二叉排序树如下图所示:JanFeb MarApr Aug Dec June July MaySeptOctNov在等概率情况下查找成功的平均查找长度为:ASL 成功=(1+2*2+3*3+4*3+5*2+6*1)/12=42/12=3.5(2)分析:对表中元素进行排序后,其实就变成了对长度为12的有序表进行折半查找了,那么在等概率的情况下的平均查找长度只要根据折半查找的判定树就很容易求出。
长度为12的有序表进行折半查找的判定树如下图所示:681211754193210所以可求出:ASL 成功=(1+2*2+4*3+5*4)/12=37/129.19 选取哈希函数H(k)=(3k) MOD 11。
用开放定址法处理冲突,di=i((7k)MOD 10+1)(i=1,2,3,…)。
试在0~10的散列地址空间中对关键字序列(22,41,53,46,30,13,01,67)造哈希表,并求等概率情况下查找成功时的平均查找长度。
解:因为H(22)=0;H(41)=2;H(53)=5;H(46)=6;H(30)=2;H 1(30)=3;H(13)=6;H 1(13)=8;H(01)=3;H 1(01)=0;H 2(01)=8;H 3(01)=5;H 4(01)=2;H 5(01)=10H(67)=3;H 1(67)=2;H 2(67)=1所以:构造的哈希表如下图所示:并求得等概率情况下查找成功的平均查找长度为:ASL 成功=(1*4+2*2+3+6)/8=17/89.21 在地址空间为0~16的散列区中,对以下关键字序列构造两哈希表: (Jan,Feb,Mar,Apr,May,June,July,Aug,Sep,Oct,Nov,Dec )(1)用线性探测开放定址法处理冲突;(2)用链地址法处理。
数据结构与算法分析课后习题答案
数据结构与算法分析课后习题答案第一章:基本概念一、题目:什么是数据结构与算法?数据结构是指数据在计算机中存储和组织的方式,如栈、队列、链表、树等;而算法是一系列解决问题的清晰规范的指令步骤。
数据结构和算法是计算机科学的核心内容。
二、题目:数据结构的分类有哪些?数据结构可以分为以下几类:1. 线性结构:包括线性表、栈、队列等,数据元素之间存在一对一的关系。
2. 树形结构:包括二叉树、AVL树、B树等,数据元素之间存在一对多的关系。
3. 图形结构:包括有向图、无向图等,数据元素之间存在多对多的关系。
4. 文件结构:包括顺序文件、索引文件等,是硬件和软件相结合的数据组织形式。
第二章:算法分析一、题目:什么是时间复杂度?时间复杂度是描述算法执行时间与问题规模之间的增长关系,通常用大O记法表示。
例如,O(n)表示算法的执行时间与问题规模n成正比,O(n^2)表示算法的执行时间与问题规模n的平方成正比。
二、题目:主定理是什么?主定理(Master Theorem)是用于估计分治算法时间复杂度的定理。
它的公式为:T(n) = a * T(n/b) + f(n)其中,a是子问题的个数,n/b是每个子问题的规模,f(n)表示将一个问题分解成子问题和合并子问题的所需时间。
根据主定理的不同情况,可以得到算法的时间复杂度的上界。
第三章:基本数据结构一、题目:什么是数组?数组是一种线性数据结构,它由一系列具有相同数据类型的元素组成,通过索引访问。
数组具有随机访问、连续存储等特点,但插入和删除元素的效率较低。
二、题目:栈和队列有什么区别?栈和队列都是线性数据结构,栈的特点是“先进后出”,即最后压入栈的元素最先弹出;而队列的特点是“先进先出”,即最先入队列的元素最先出队列。
第四章:高级数据结构一、题目:什么是二叉树?二叉树是一种特殊的树形结构,每个节点最多有两个子节点。
二叉树具有左子树、右子树的区分,常见的有完全二叉树、平衡二叉树等。
数据结构与算法分析-C++版答案
数据结构与算法分析-C++版答案Data Structures and Algorithm 习题答案Preface ii1 Data Structures and Algorithms 12 Mathematical Preliminaries 53 Algorithm Analysis 174 Lists, Stacks, and Queues 235 Binary Trees 326 General Trees 407 Internal Sorting 468 File Processing and External Sorting 54 9Searching 5810 Indexing 6411 Graphs 6912 Lists and Arrays Revisited 7613 Advanced Tree Structures 82iii Contents14 Analysis Techniques 8815 Limits to Computation 94PrefaceContained herein are the solutions to all exercises from the textbook A Practical Introduction to Data Structures and Algorithm Analysis, 2nd edition.For most of the problems requiring an algorithm I have given actual code. Ina few cases I have presented pseudocode. Please be aware that the code presented in this manual has not actually been compiled and tested. While I believe the algorithmsto be essentially correct, there may be errors in syntax as wellas semantics. Most importantly, these solutions provide a guide to the instructor as to the intendedanswer, rather than usable programs.1Data Structures and AlgorithmsInstructor’s note: Unlike the other chapters, many of the questions in this chapter are not really suitable for graded work. The questions are mainly intended to get students thinking about data structures issues.1.1This question does not have a specific right answer, provided the student keeps to the spirit of the question. Students may have trouble with the concept of “operations.”1.2This exercise asks the student to expand on their concept of an integer representation.A good answer is described by Project 4.5, where a singly-linkedlist is suggested. The most straightforward implementation stores each digitin its own list node, with digits stored in reverse order. Addition and multiplicationare implemented by what amounts to grade-school arithmetic. Foraddition, simply march down in parallel through the two lists representingthe operands, at each digit appending to a new list the appropriate partial sum and bringing forward a carry bit as necessary. For multiplication, combine the addition function with a new function that multiplies a single digitby an integer. Exponentiation can be done either by repeated multiplication (not really practical) or by the traditional Θ(log n)-time algorithm based on the binary representation of the exponent. Discovering this faster algorithm will be beyond the reach of most students, so should not be required.1.3A sample ADT for character strings might look as follows (with the normal interpretation of the function names assumed).Chap. 1 Data Structures and Algorithms// Concatenate two stringsString strcat(String s1, String s2);// Return the length of a stringint length(String s1);// Extract a substring, starting at ‘start’,// and of length ‘length’String extract(String s1, int start, int length);// Get the first characterchar first(String s1);// Compare two strings: the normal C++ strcmp function.Some// convention should be indicated for how to interpretthe// return value. In C++, this is 1for s1// and 1 for s1>s2.int strcmp(String s1, String s2)// Copy a stringint strcpy(String source, String destination)1.4The answer to this question is provided by the ADT for listsgiven in Chapter 4.1.5One’s compliment stores the binary representation of positive numbers, and stores the binary representation of a negative number with the bits inverted. Two’s compliment is the same, except that a negative number has its bits inverted and then one is added (for reasons of efficiency in hardware implementation).This representation is the physical implementation of an ADT defined by the normal arithmetic operations, declarations, and other support given by the programming language for integers.1.6An ADT for two-dimensional arrays might look as follows.Matrix add(Matrix M1, Matrix M2);Matrix multiply(Matrix M1, Matrix M2);Matrix transpose(Matrix M1);void setvalue(Matrix M1, int row, int col, int val);int getvalue(Matrix M1, int row, int col);List getrow(Matrix M1, int row);One implementation for the sparse matrix is described in Section 12.3 Another implementationis a hash table whose search key is a concatenation of the matrix coordinates.1.7Every problem certainly does not have an algorithm. As discussed in Chapter 15, there are a number of reasons why this might be the case. Some problems don’t have a sufficiently clear definition. Some problems, such as the halting problem, are non-computable. For some problems, such as one typicallystudied by artificial intelligence researchers, we simply don’t know a solution.1.8We must assume that by “algorithm” we mean something composed of steps areof a nature that they can be performed by a computer. If so, than any algorithm can be expressed in C++. In particular, if an algorithm can be expressed in any other computer programming language, then it can be expressed in C++, since all (sufficiently general) computer programming languages compute the same set of functions.1.9The primitive operations are (1) adding new words to the dictionary and (2) searching the dictionary for a given word. Typically, dictionary access involves some sort of pre-processing of the word to arrive at the “root” of the word.A twenty page document (single spaced) is likely to contain about 20,000 words. A user may be willing to wait a few seconds between individual “hits” of mis-spelled words, or perhaps up to a minute for the whole document to be processed. This means that a check for an individual word can take about 10-20 ms. Users will typically insert individual words into the dictionary interactively, so this process cantake a couple of seconds. Thus, search must be much more efficient than insertion.1.10The user should be able to find a city based on a variety of attributes (name, location,perhaps characteristics such as population size). The user should also be able to insertand delete cities. These are the fundamental operations of any database system: search, insertion and deletion.A reasonable database has a time constraint that will satisfy the patience of a typicaluser. For an insert, delete, or exact match query, a few seconds is satisfactory. If thedatabase is meant to support range queries and mass deletions, the entire operation may be allowed to take longer, perhaps on the order of a minute. However, the time spent to process individual cities within the range must be appropriately reduced.Inpractice, the data representation will need to be such that it accommodates efficient processing to meet these time constraints. In particular, it may be necessary to support operations that process range queries efficiently by processing all cities in the range as a batch, rather than as a series of operations on individual cities.1.11Students at this level are likely already familiar with binary search. Thus, they should typically respond with sequential search and binary search. Binary search should be described as better since it typically needs to make fewer comparisons (and thus is likely to be much faster).1.12The answer to this question is discussed in Chapter 8. Typical measures of cost will be number of comparisons and number of swaps. Tests should include running timings on sorted, reverse sorted, and random lists of various sizes.Chap. 1 Data Structures and Algorithms1.13The first part is easy with the hint, but the second part is rather difficult to do withouta stack.a) bool checkstring(string S) {int count = 0;for (int i=0; i<="" p="">if (S[i] == ’(’) count++;if (S[i] == ’)’) {if (count == 0) return FALSE;count--;}}if (count == 0) return TRUE;else return FALSE;}b) int checkstring(String Str) {Stack S;int count = 0;for (int i=0; i<="" p="">if (S[i] == ’(’)S.push(i);if (S[i] == ’)’) {if (S.isEmpty()) return i;S.pop();}if (S.isEmpty()) return -1;else return S.pop();}1.14Answers to this question are discussed in Section 7.2.1.15This is somewhat different from writing sorting algorithms for a computer, since person’s “working space” is typically limited, as is their ability to physically manipulatethe pieces of paper. Nonetheless, many of the common sorting algorithms have their analogs to solutions for this problem. Most typical answers will be insertion sort, variations on mergesort, and variations on binsort.1.16Answers to this question are discussed in Chapter 8.2Mathematical Preliminaries2.1(a) Not reflexive if the set has any members. One could argue it is symmetric, antisymmetric, and transitive, since no element violate any ofthe rules.(b)Not reflexive (for any female). Not symmetric (consider a brother and sister). Not antisymmetric (consider two brothers). Transitive (for any3 brothers).(c)Not reflexive. Not symmetric, and is antisymmetric. Not transitive(only goes one level).(d)Not reflexive (for nearly all numbers). Symmetric since a+ b+ a,so not antisymmetric. Transitive, but vacuously so (there can be nodistinct a, b,and cwhere aRband bRc).(e)Reflexive. Symmetric, so not antisymmetric. Transitive (but sort of vacuous).(f)Reflexive – check all the cases. Since it is only true when x= y,itis technically symmetric and antisymmetric, but rather vacuous. Likewise,it is technically transitive, but vacuous.2.2In general, prove that something is an equivalence relation by proving that it is reflexive, symmetric, and transitive.(a)This is an equivalence that effectively splits the integers into odd andeven sets. It is reflexive (x+ xis even for any integer x), symmetric(since x+ y= y+ x) and transitive (since you are always adding twoodd or even numbers for any satisfactory a, b,and c).This is not an equivalence. To begin with, it is not reflexive for any integer.(c)This is an equivalence that divides the non-zero rational numbers into positive and negative. It is reflexive since x ˙x>0. It is symmetric sincexy˙= yx˙. It is transitive since any two members of the given class satisfy the relationship.5Chap. 2 Mathematical Preliminaries(d)This is not an equivalance relation since it is not symmetric. For example,a=1and b=2.(e)This is an eqivalance relation that divides the rationals based on their fractional values. It is reflexive since for all a, a.a =0. It is symmetricsince if a.b=xthen b.a=.x. It is transitive since any two rationalswith the same fractional value will yeild an integer.(f)This is not an equivalance relation since it is not transitive. For example, 4.2=2and 2.0=2,but 4.0=4.2.3A relation is a partial ordering if it is antisymmetric and transitive.(a)Not a partial ordering because it is not transitive.(b)Is a partial ordering bacause it is antisymmetric (if ais an ancestor ofb, then bcannot be an ancestor of a) and transitive (since the ancestor of an ancestor is an ancestor).(c)Is a partial ordering bacause it is antisymmetric (if ais older than b,then bcannot be older than a) and transitive (since if ais older than band bis older than c, ais older than c).(d)Not a partial ordering, since it is not antisymmetric for any pair of sisters.(e)Not a partial ordering because it is not antisymmetric.(f)This is a partial ordering. It is antisymmetric (no violations exist) and transitive (no violations exist).2.4A total ordering can be viewed as a permuation of the elements. Since there are n!permuations of nelements, there must be n!total orderings.2.5This proposed ADT is inspired by the list ADT of Chapter 4.void clear();void insert(int);void remove(int);void sizeof();bool isEmpty();bool isInSet(int);2.6This proposed ADT is inspired by the list ADT of Chapter 4. Note that while it is similiar to the operations proposed for Question 2.5, the behaviour is somewhat different.void clear();void insert(int);void remove(int);void sizeof();7bool isEmpty();// Return the number of elements with a given valueintcountInBag(int);2.7The list class ADT from Chapter 4 is a sequence.2.8long ifact(int n) { // make n <= 12 so n! for long intlong fact = 1;Assert((n >= 0) && (n <= 12), "Input out of range");for (int i=1; i<= n; i++)fact = fact * i;return fact;}2.9void rpermute(int *array, int n) {swap(array, n-1, Random(n));rpermute(array, n-1);}2.10(a) Most people will find the recursive form natural and easy to understand. The iterative version requires careful examination to understand whatit does, or to have confidence that it works as claimed.(b)Fibr is so much slower than Fibi because Fibr re-computes thebulk of the series twice to get the two values to add. What is muchworse, the recursive calls to compute the subexpressions also re-computethe bulk of the series, and do so recursively. The result is an exponential explosion. In contrast, Fibicomputes each value in the seriesexactly once, and so its running time is proportional to n.2.11// Array curr[i] indicates current position of ring i.void GenTOH(int n, POLE goal, POLE t1, POLE t2,POLE* curr) {if (curr[n] == goal) // Get top n-1 rings set upGenTOH(n-1, goal, t1, t2, curr);else {if (curr[n] == t1) swap(t1, t2); // Get names right// Now, ring n is on pole t2. Put others on t1.GenTOH(n-1, t1, goal, t2, curr);move(t2, goal);GenTOH(n-1, goal, t1, t2, curr); // Move n-1 back}}2.12At each step of the way, the reduction toward the base case is only half asfar as the previous time. In theory, this series approaches, but never reaches, 0, so it will go on forever. In practice, the value should become computationally indistinguishable from zero, and terminate. However, this is terrible programming practice.Chap. 2 Mathematical Preliminaries2.13void allpermute(int array[], int n, int currpos) {if (currpos == (n-1)} {printout(array);return;}for (int i=currpos; i<="">swap(array, currpos, i);allpermute(array, n, currpos+1);swap(array, currpos, i); // Put back for next pass}}2.14In the following, function bitposition(n, i) returns the value (0 or1) at the ith bit position of integer value n. The idea is the print out the elements at the indicated bit positions within the set. If we do this for values in the range 0 to 2n.1, we will get the entire powerset.void powerset(int n) {for (int i=0; i<="">for (int j=0; j<="" p="">if (bitposition(n, j) == 1) cout << j << " ";cout << endl;}2.15 Proof: Assume that there is a largest prime number. Call it Pn,the nth largest prime number, and label all of the primes in order P1 =2, P2 =3,and so on. Now, consider the number Cformed by multiplying all of the nprime numbers together. The value C+1is not divisible by any of the nprime numbers. C+1is a prime number larger than Pn, a contradiction.Thus, we conclude that there is no largest prime number. .2.16Note: This problem is harder than most sophomore level students can handle.√Proof: The proof is by contradiction. Assume that 2is rational. By definition, there exist integers pand qsuch that√p2=,qwhere pand qhave no common factors (that is, the fraction p/qis in lowestterms). By squaring both sides and doing some simple algebraic manipulation, we get2p2=2q222q= pSince p2 must be even, p must be even. Thus,。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
This flow is not unique. For instance, two units of the flow that goes from G to D to A to E could go by G to H to E.
-47-
9.12 Let T be the tree with root r , and children r 1, r 2, ..., rk , which are the roots of T 1, T 2, ..., Tk , which have maximum incoming flow of c 1, c 2, ..., ck , respectively. By the problem statement, we may take the maximum incoming flow of r to be infinity. The recursive function FindMaxFlow( T, IncomingCap ) finds the value of the maximum flow in T (finding the actual flow is a matter of bookkeeping); the flow is guaranteed not to exceed IncomingCap . If T is a leaf, then FindMaxFlow returns IncomingCap since we have assumed a sink of infinite capacity. Otherwise, a standard postorder traversal can be used to compute the maximum flow in linear time. _ ______________________________________________________________________________ FlowType FindMaxFlow( Tree T, FlowType IncomingCap ) { FlowType ChildFlow, TotalFlow; if( IsLeaf( T ) ) return IncomingCap; else { TotalFlow = 0; for( each subtree Ti of T ) { ChildFlow = FindMaxFlow( Ti , min( IncomingCap, ci ) ); TotalFlow += ChildFlow; IncomingCap -= ChildFlow; } return TotalFlow; } } _ ______________________________________________________________________________ 9.13 (a) Assume that the graph is connected and undirected. If it is not connected, then apply the algorithm to the connected components. Initially, mark all vertices as unknown. Pick any vertex v , color it red, and perform a depth-first search. When a node is first encountered, color it blue if the DFS has just come from a red node, and red otherwise. If at any point, the depth-first search encounters an edge between two identical colors, then the graph is not bipartite; otherwise, it is. A breadth-first search (that is, using a queue) also works. This problem, which is essentially two-coloring a graph, is clearly solvable in linear time. This contrasts with three-coloring, which is NP-complete. (b) Construct an undirected graph with a vertex for each instructor, a vertex for each course, and an edge between (v ,w ) if instructor v is qualified to teach course w . Such a graph is bipartite; a matching of M edges means that M courses can be covered simultaneously. (c) Give each edge in the bipartite graph a weight of 1, and direct the edge from the instructor to the course. Add a vertex s with edges of weight 1 from s to all instructor vertices. Add a vertex t with edges of weight 1 from all course vertices to t . The maximum flow is equal to the maximum matching.
Chapter 9: Graph Algorithms
9.1 The following ordering is arrived at by using a queue and assumes that vertices appear on an adjacency list alphabetically. The topological order that results is then s, G, D, H, A, B, E, I, F, C, t Assuming the same adjacency list, the topological order produced when a stack is used is s, G, H, D, A, E, I, F, B, C, t Because a topological sort processes vertices in the same manner as a breadth-first search, it tends to produce a more natural ordering. 9.4 9.5 The idea is the same as in Exercise 5.10. (a) (Unweighted paths) A->B, A->C, A->B->G, A->B->E, A->C->D, A->B->E->F. (b) (Weighted paths) A->C, A->B, A->B->G, A->B->G->E, A->B->G->E->F, A->B->G>E->D. 9.6 We’ll assume that Dijkstra’s algorithm is implemented with a priority queue of vertices that uses the DecreaseKey operation. Dijkstra’s algorithm uses | E | DecreaseKey operations, which cost O (logd | V | ) each, and | V | DeleteMin operations, which cost O (d logd | V | ) each. The running time is thus O ( | E | logd | V | + | V | d logd | V | ). The cost of the DecreaseKey operations balances the Insert operations when d = | E | / | V | . For a sparse graph, this might give a value of d that is less than 2; we can’t allow this, so d is chosen to be max (2, | E | / | V | ). This gives a running time of O ( | E | log2 + | E | / | V | | V | ), which is a slight theoretical improvement. Moret and Shapiro report (indirectly) that d -heaps do not improve the running time in practice. (a) The graph shown here is an example. Dijkstra’s algorithm gives a path from A to C of cost 2, when the path from A to B to C has cost 1. C 2 A 3 B -2 9.2
Next, send three units of flow along s, D, E, F, t. The residual graph that results is as follows: A 1 s 2 4 1 3 G 3 D 2 2 4 1 H 2 2 3 2 2 4 E 3 I B 2 2 3 1 C 1 F 4 4 3 t