数据结构与算法分析C++版答案

合集下载

《数据结构、算法与应用(C++语言描述)》习题参考答案doc

《数据结构、算法与应用(C++语言描述)》习题参考答案doc

第1章概论1.数据、数据元素、数据结构、数据类型的含义分别是什么?数据:对客观事物的符号表示,在计算机科学中是指所有能输入到计算机中并由计算机程序处理的符号的总称。

数据元素:数据的基本单位,在计算机程序中通常作为一个整体考虑。

数据结构:数据元素之间的关系+运算,是以数据为成员的结构,是带结构的数据元素的集合,数据元素之间存在着一种或多种特定的关系。

数据类型:数据类型是用来区分不同的数据;由于数据在存储时所需要的容量各不相同,不同的数据就必须要分配不同大小的内存空间来存储,所有就要将数据划分成不同的数据类型。

数据类型包含取值范围和基本运算等概念。

2.什么是数据的逻辑结构?什么是数据的物理结构?数据的逻辑结构与物理结构的区别和联系是什么?逻辑结构:数据的逻辑结构定义了数据结构中数据元素之间的相互逻辑关系。

数据的逻辑结构包含下面两个方面的信息:①数据元素的信息;②各数据元素之间的关系。

物理结构:也叫储存结构,是指逻辑结构的存储表示,即数据的逻辑结构在计算机存储空间中的存放形式,包括结点的数据和结点间关系的存储表示。

数据的逻辑结构和存储结构是密不可分的,一个操作算法的设计取决于所选定的逻辑结构,而算法的实现依赖于所采与的存储结构。

采用不同的存储结构,其数据处理的效率是不同的。

因此,在进行数据处理时,针对不同问题,选择合理的逻辑结构和存储结构非常重要。

3.数据结构的主要操作包括哪些?对于各种数据结构而言,他们在基本操作上是相似的,最常用的操作有:●创建:建立一个数据结构;●清除:清除一个数据结构;●插入:在数据结构中增加新的结点;●删除:把指定的结点从数据结构中删除;●访问:对数据结构中的结点进行访问;●更新:改变指定结点的值或改变指定的某些结点之间的关系;●查找:在数据结构中查找满足一定条件的结点;●排序:对数据结构中各个结点按指定数据项的值,以升序或降序重新排列。

4.什么是抽象数据类型?如何定义抽象数据类型?抽象数据类型(Abstract Data Type 简称ADT)是指一个数学模型以及定义在此数学模型上的一组操作。

《数据结构与算法分析》(C++第二版)【美】Clifford A.Shaffer著 课后习题答案 二

《数据结构与算法分析》(C++第二版)【美】Clifford A.Shaffer著 课后习题答案 二

《数据结构与算法分析》(C++第二版)【美】Clifford A.Shaffer著课后习题答案二5Binary Trees5.1 Consider a non-full binary tree. By definition, this tree must have some internalnode X with only one non-empty child. If we modify the tree to removeX, replacing it with its child, the modified tree will have a higher fraction ofnon-empty nodes since one non-empty node and one empty node have been removed.5.2 Use as the base case the tree of one leaf node. The number of degree-2 nodesis 0, and the number of leaves is 1. Thus, the theorem holds.For the induction hypothesis, assume the theorem is true for any tree withn − 1 nodes.For the induction step, consider a tree T with n nodes. Remove from the treeany leaf node, and call the resulting tree T. By the induction hypothesis, Thas one more leaf node than it has nodes of degree 2.Now, restore the leaf node that was removed to form T. There are twopossible cases.(1) If this leaf node is the only child of its parent in T, then the number ofnodes of degree 2 has not changed, nor has the number of leaf nodes. Thus,the theorem holds.(2) If this leaf node is the child of a node in T with degree 2, then that nodehas degree 1 in T. Thus, by restoring the leaf node we are adding one newleaf node and one new node of degree 2. Thus, the theorem holds.By mathematical induction, the theorem is correct.32335.3 Base Case: For the tree of one leaf node, I = 0, E = 0, n = 0, so thetheorem holds.Induction Hypothesis: The theorem holds for the full binary tree containingn internal nodes.Induction Step: Take an arbitrary tree (call it T) of n internal nodes. Selectsome internal node x from T that has two leaves, and remove those twoleaves. Call the resulting tree T’. Tree T’ is full and has n−1 internal nodes,so by the Induction Hypothesis E = I + 2(n − 1).Call the depth of node x as d. Restore the two children of x, each at leveld+1. We have nowadded d to I since x is now once again an internal node.We have now added 2(d + 1) − d = d + 2 to E since we added the two leafnodes, but lost the contribution of x to E. Thus, if before the addition we had E = I + 2(n − 1) (by the induction hypothesis), then after the addition we have E + d = I + d + 2 + 2(n − 1) or E = I + 2n which is correct. Thus,by the principle of mathematical induction, the theorem is correct.5.4 (a) template <class Elem>void inorder(BinNode<Elem>* subroot) {if (subroot == NULL) return; // Empty, do nothingpreorder(subroot->left());visit(subroot); // Perform desired actionpreorder(subroot->right());}(b) template <class Elem>void postorder(BinNode<Elem>* subroot) {if (subroot == NULL) return; // Empty, do nothingpreorder(subroot->left());preorder(subroot->right());visit(subroot); // Perform desired action}5.5 The key is to search both subtrees, as necessary.template <class Key, class Elem, class KEComp>bool search(BinNode<Elem>* subroot, Key K);if (subroot == NULL) return false;if (subroot->value() == K) return true;if (search(subroot->right())) return true;return search(subroot->left());}34 Chap. 5 Binary Trees5.6 The key is to use a queue to store subtrees to be processed.template <class Elem>void level(BinNode<Elem>* subroot) {AQueue<BinNode<Elem>*> Q;Q.enqueue(subroot);while(!Q.isEmpty()) {BinNode<Elem>* temp;Q.dequeue(temp);if(temp != NULL) {Print(temp);Q.enqueue(temp->left());Q.enqueue(temp->right());}}}5.7 template <class Elem>int height(BinNode<Elem>* subroot) {if (subroot == NULL) return 0; // Empty subtreereturn 1 + max(height(subroot->left()),height(subroot->right()));}5.8 template <class Elem>int count(BinNode<Elem>* subroot) {if (subroot == NULL) return 0; // Empty subtreeif (subroot->isLeaf()) return 1; // A leafreturn 1 + count(subroot->left()) +count(subroot->right());}5.9 (a) Since every node stores 4 bytes of data and 12 bytes of pointers, the overhead fraction is 12/16 = 75%.(b) Since every node stores 16 bytes of data and 8 bytes of pointers, the overhead fraction is 8/24 ≈ 33%.(c) Leaf nodes store 8 bytes of data and 4 bytes of pointers; internal nodesstore 8 bytes of data and 12 bytes of pointers. Since the nodes havedifferent sizes, the total space needed for internal nodes is not the sameas for leaf nodes. Students must be careful to do the calculation correctly,taking the weighting into account. The correct formula looks asfollows, given that there are x internal nodes and x leaf nodes.4x + 12x12x + 20x= 16/32 = 50%.(d) Leaf nodes store 4 bytes of data; internal nodes store 4 bytes of pointers. The formula looks as follows, given that there are x internal nodes and35x leaf nodes:4x4x + 4x= 4/8 = 50%.5.10 If equal valued nodes were allowed to appear in either subtree, then during a search for all nodes of a given value, whenever we encounter a node of that value the search would be required to search in both directions.5.11 This tree is identical to the tree of Figure 5.20(a), except that a node with value 5 will be added as the right child of the node with value 2.5.12 This tree is identical to the tree of Figure 5.20(b), except that the value 24 replaces the value 7, and the leaf node that originally contained 24 is removed from the tree.5.13 template <class Key, class Elem, class KEComp>int smallcount(BinNode<Elem>* root, Key K);if (root == NULL) return 0;if (KEComp.gt(root->value(), K))return smallcount(root->leftchild(), K);elsereturn smallcount(root->leftchild(), K) +smallcount(root->rightchild(), K) + 1;5.14 template <class Key, class Elem, class KEComp>void printRange(BinNode<Elem>* root, int low,int high) {if (root == NULL) return;if (KEComp.lt(high, root->val()) // all to leftprintRange(root->left(), low, high);else if (KEComp.gt(low, root->val())) // all to rightprintRange(root->right(), low, high);else { // Must process both childrenprintRange(root->left(), low, high);PRINT(root->value());printRange(root->right(), low, high);}}5.15 The minimum number of elements is contained in the heap with a single node at depth h − 1, for a total of 2h−1 nodes.The maximum number of elements is contained in the heap that has completely filled up level h − 1, for a total of 2h − 1 nodes.5.16 The largest element could be at any leaf node.5.17 The corresponding array will be in the following order (equivalent to level order for the heap):12 9 10 5 4 1 8 7 3 236 Chap. 5 Binary Trees5.18 (a) The array will take on the following order:6 5 3 4 2 1The value 7 will be at the end of the array.(b) The array will take on the following order:7 4 6 3 2 1The value 5 will be at the end of the array.5.19 // Min-heap classtemplate <class Elem, class Comp> class minheap {private:Elem* Heap; // Pointer to the heap arrayint size; // Maximum size of the heapint n; // # of elements now in the heapvoid siftdown(int); // Put element in correct placepublic:minheap(Elem* h, int num, int max) // Constructor{ Heap = h; n = num; size = max; buildHeap(); }int heapsize() const // Return current size{ return n; }bool isLeaf(int pos) const // TRUE if pos a leaf{ return (pos >= n/2) && (pos < n); }int leftchild(int pos) const{ return 2*pos + 1; } // Return leftchild posint rightchild(int pos) const{ return 2*pos + 2; } // Return rightchild posint parent(int pos) const // Return parent position { return (pos-1)/2; }bool insert(const Elem&); // Insert value into heap bool removemin(Elem&); // Remove maximum value bool remove(int, Elem&); // Remove from given pos void buildHeap() // Heapify contents{ for (int i=n/2-1; i>=0; i--) siftdown(i); }};template <class Elem, class Comp>void minheap<Elem, Comp>::siftdown(int pos) { while (!isLeaf(pos)) { // Stop if pos is a leafint j = leftchild(pos); int rc = rightchild(pos);if ((rc < n) && Comp::gt(Heap[j], Heap[rc]))j = rc; // Set j to lesser child’s valueif (!Comp::gt(Heap[pos], Heap[j])) return; // Done37swap(Heap, pos, j);pos = j; // Move down}}template <class Elem, class Comp>bool minheap<Elem, Comp>::insert(const Elem& val) { if (n >= size) return false; // Heap is fullint curr = n++;Heap[curr] = val; // Start at end of heap// Now sift up until curr’s parent < currwhile ((curr!=0) &&(Comp::lt(Heap[curr], Heap[parent(curr)]))) {swap(Heap, curr, parent(curr));curr = parent(curr);}return true;}template <class Elem, class Comp>bool minheap<Elem, Comp>::removemin(Elem& it) { if (n == 0) return false; // Heap is emptyswap(Heap, 0, --n); // Swap max with last valueif (n != 0) siftdown(0); // Siftdown new root valit = Heap[n]; // Return deleted valuereturn true;}38 Chap. 5 Binary Trees// Remove value at specified positiontemplate <class Elem, class Comp>bool minheap<Elem, Comp>::remove(int pos, Elem& it) {if ((pos < 0) || (pos >= n)) return false; // Bad posswap(Heap, pos, --n); // Swap with last valuewhile ((pos != 0) &&(Comp::lt(Heap[pos], Heap[parent(pos)])))swap(Heap, pos, parent(pos)); // Push up if largesiftdown(pos); // Push down if small keyit = Heap[n];return true;}5.20 Note that this summation is similar to Equation 2.5. To solve the summation requires the shifting technique from Chapter 14, so this problem may be too advanced for many students at this time. Note that 2f(n) − f(n) = f(n),but also that:2f(n) − f(n) = n(24+48+616+ ··· +2(log n − 1)n) −n(14+28+316+ ··· +log n − 1n)logn−1i=112i− log n − 1n)= n(1 − 1n− log n − 1n)= n − log n.5.21 Here are the final codes, rather than a picture.l 00h 010i 011e 1000f 1001j 101d 11000a 1100100b 1100101c 110011g 1101k 11139The average code length is 3.234455.22 The set of sixteen characters with equal weight will create a Huffman coding tree that is complete with 16 leaf nodes all at depth 4. Thus, the average code length will be 4 bits. This is identical to the fixed length code. Thus, in this situation, the Huffman coding tree saves no space (and costs no space).5.23 (a) By the prefix property, there can be no character with codes 0, 00, or 001x where “x” stands for any binary string.(b) There must be at least one code with each form 1x, 01x, 000x where“x” could be any binary string (including the empty string).5.24 (a) Q and Z are at level 5, so any string of length n containing only Q’s and Z’s requires 5n bits.(b) O and E are at level 2, so any string of length n containing only O’s and E’s requires 2n bits.(c) The weighted average is5 ∗ 5 + 10 ∗ 4 + 35 ∗ 3 + 50 ∗ 2100bits per character5.25 This is a straightforward modification.// Build a Huffman tree from minheap h1template <class Elem>HuffTree<Elem>*buildHuff(minheap<HuffTree<Elem>*,HHCompare<Elem> >* hl) {HuffTree<Elem> *temp1, *temp2, *temp3;while(h1->heapsize() > 1) { // While at least 2 itemshl->removemin(temp1); // Pull first two treeshl->removemin(temp2); // off the heaptemp3 = new HuffTree<Elem>(temp1, temp2);hl->insert(temp3); // Put the new tree back on listdelete temp1; // Must delete the remnantsdelete temp2; // of the trees we created}return temp3;}6General Trees6.1 The following algorithm is linear on the size of the two trees. // Return TRUE iff t1 and t2 are roots of identical// general treestemplate <class Elem>bool Compare(GTNode<Elem>* t1, GTNode<Elem>* t2) { GTNode<Elem> *c1, *c2;if (((t1 == NULL) && (t2 != NULL)) ||((t2 == NULL) && (t1 != NULL)))return false;if ((t1 == NULL) && (t2 == NULL)) return true;if (t1->val() != t2->val()) return false;c1 = t1->leftmost_child();c2 = t2->leftmost_child();while(!((c1 == NULL) && (c2 == NULL))) {if (!Compare(c1, c2)) return false;if (c1 != NULL) c1 = c1->right_sibling();if (c2 != NULL) c2 = c2->right_sibling();}}6.2 The following algorithm is Θ(n2).// Return true iff t1 and t2 are roots of identical// binary treestemplate <class Elem>bool Compare2(BinNode<Elem>* t1, BinNode<Elem* t2) { BinNode<Elem> *c1, *c2;if (((t1 == NULL) && (t2 != NULL)) ||((t2 == NULL) && (t1 != NULL)))return false;if ((t1 == NULL) && (t2 == NULL)) return true;4041if (t1->val() != t2->val()) return false;if (Compare2(t1->leftchild(), t2->leftchild())if (Compare2(t1->rightchild(), t2->rightchild())return true;if (Compare2(t1->leftchild(), t2->rightchild())if (Compare2(t1->rightchild(), t2->leftchild))return true;return false;}6.3 template <class Elem> // Print, postorder traversalvoid postprint(GTNode<Elem>* subroot) {for (GTNode<Elem>* temp = subroot->leftmost_child();temp != NULL; temp = temp->right_sibling())postprint(temp);if (subroot->isLeaf()) cout << "Leaf: ";else cout << "Internal: ";cout << subroot->value() << "\n";}6.4 template <class Elem> // Count the number of nodesint gencount(GTNode<Elem>* subroot) {if (subroot == NULL) return 0int count = 1;GTNode<Elem>* temp = rt->leftmost_child();while (temp != NULL) {count += gencount(temp);temp = temp->right_sibling();}return count;}6.5 The Weighted Union Rule requires that when two parent-pointer trees are merged, the smaller one’s root becomes a child of the larger one’s root. Thus, we need to keep track of the number of nodes in a tree. To do so, modify the node array to store an integer value with each node. Initially, each node isin its own tree, so the weights for each node begin as 1. Whenever we wishto merge two trees, check the weights of the roots to determine which has more nodes. Then, add to the weight of the final root the weight of the new subtree.6.60 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15-1 0 0 0 0 0 0 6 0 0 0 9 0 0 12 06.7 The resulting tree should have the following structure:42 Chap. 6 General TreesNode 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15Parent 4 4 4 4 -1 4 4 0 0 4 9 9 9 12 9 -16.8 For eight nodes labeled 0 through 7, use the following series of equivalences: (0, 1) (2, 3) (4, 5) (6, 7) (4 6) (0, 2) (4 0)This requires checking fourteen parent pointers (two for each equivalence),but none are actually followed since these are all roots. It is possible todouble the number of parent pointers checked by choosing direct children ofroots in each case.6.9 For the “lists of Children” representation, every node stores a data value and a pointer to its list of children. Further, every child (every node except the root)has a record associated with it containing an index and a pointer. Indicatingthe size of the data value as D, the size of a pointer as P and the size of anindex as I, the overhead fraction is3P + ID + 3P + I.For the “Left Child/Right Sibling” representation, every node stores three pointers and a data value, for an overhead fraction of3PD + 3P.The first linked representation of Section 6.3.3 stores with each node a datavalue and a size field (denoted by S). Each child (every node except the root)also has a pointer pointing to it. The overhead fraction is thusS + PD + S + Pmaking it quite efficient.The second linked representation of Section 6.3.3 stores with each node adata value and a pointer to the list of children. Each child (every node exceptthe root) has two additional pointers associated with it to indicate its placeon the parent’s linked list. Thus, the overhead fraction is3PD + 3P.6.10 template <class Elem>BinNode<Elem>* convert(GTNode<Elem>* genroot) {if (genroot == NULL) return NULL;43GTNode<Elem>* gtemp = genroot->leftmost_child();btemp = new BinNode(genroot->val(), convert(gtemp),convert(genroot->right_sibling()));}6.11 • Parent(r) = (r − 1)/k if 0 < r < n.• Ith child(r) = kr + I if kr +I < n.• Left sibling(r) = r − 1 if r mod k = 1 0 < r < n.• Right sibling(r) = r + 1 if r mod k = 0 and r + 1 < n.6.12 (a) The overhead fraction is4(k + 1)4 + 4(k + 1).(b) The overhead fraction is4k16 + 4k.(c) The overhead fraction is4(k + 2)16 + 4(k + 2).(d) The overhead fraction is2k2k + 4.6.13 Base Case: The number of leaves in a non-empty tree of 0 internal nodes is (K − 1)0 + 1 = 1. Thus, the theorem is correct in the base case.Induction Hypothesis: Assume that the theorem is correct for any full Karytree containing n internal nodes.Induction Step: Add K children to an arbitrary leaf node of the tree withn internal nodes. This new tree now has 1 more internal node, and K − 1more leaf nodes, so theorem still holds. Thus, the theorem is correct, by the principle of Mathematical Induction.6.14 (a) CA/BG///FEDD///H/I//(b) CA/BG/FED/H/I6.15 X|P-----| | |C Q R---| |V M44 Chap. 6 General Trees6.16 (a) // Use a helper function with a pass-by-reference// variable to indicate current position in the// node list.template <class Elem>BinNode<Elem>* convert(char* inlist) {int curr = 0;return converthelp(inlist, curr);}// As converthelp processes the node list, curr is// incremented appropriately.template <class Elem>BinNode<Elem>* converthelp(char* inlist,int& curr) {if (inlist[curr] == ’/’) {curr++;return NULL;}BinNode<Elem>* temp = new BinNode(inlist[curr++], NULL, NULL);temp->left = converthelp(inlist, curr);temp->right = converthelp(inlist, curr);return temp;}(b) // Use a helper function with a pass-by-reference // variable to indicate current position in the// node list.template <class Elem>BinNode<Elem>* convert(char* inlist) {int curr = 0;return converthelp(inlist, curr);}// As converthelp processes the node list, curr is// incremented appropriately.template <class Elem>BinNode<Elem>* converthelp(char* inlist,int& curr) {if (inlist[curr] == ’/’) {curr++;return NULL;}BinNode<Elem>* temp =new BinNode<Elem>(inlist[curr++], NULL, NULL);if (inlist[curr] == ’\’’) return temp;45curr++ // Eat the internal node mark.temp->left = converthelp(inlist, curr);temp->right = converthelp(inlist, curr);return temp;}(c) // Use a helper function with a pass-by-reference// variable to indicate current position in the// node list.template <class Elem>GTNode<Elem>* convert(char* inlist) {int curr = 0;return converthelp(inlist, curr);}// As converthelp processes the node list, curr is// incremented appropriately.template <class Elem>GTNode<Elem>* converthelp(char* inlist,int& curr) {if (inlist[curr] == ’)’) {curr++;return NULL;}GTNode<Elem>* temp =new GTNode<Elem>(inlist[curr++]);if (curr == ’)’) {temp->insert_first(NULL);return temp;}temp->insert_first(converthelp(inlist, curr));while (curr != ’)’)temp->insert_next(converthelp(inlist, curr));curr++;return temp;}6.17 The Huffman tree is a full binary tree. To decode, we do not need to know the weights of nodes, only the letter values stored in the leaf nodes. Thus, we can use a coding much like that of Equation 6.2, storing only a bit mark for internal nodes, and a bit mark and letter value for leaf nodes.7Internal Sorting7.1 Base Case: For the list of one element, the double loop is not executed and the list is not processed. Thus, the list of one element remains unaltered and is sorted.Induction Hypothesis: Assume that the list of n elements is sorted correctlyby Insertion Sort.Induction Step: The list of n + 1 elements is processed by first sorting thetop n elements. By the induction hypothesis, this is done correctly. The final pass of the outer for loop will process the last element (call it X). This isdone by the inner for loop, which moves X up the list until a value smallerthan that of X is encountered. At this point, X has been properly insertedinto the sorted list, leaving the entire collection of n + 1 elements correctly sorted. Thus, by the principle of Mathematical Induction, the theorem is correct.7.2 void StackSort(AStack<int>& IN) {AStack<int> Temp1, Temp2;while (!IN.isEmpty()) // Transfer to another stackTemp1.push(IN.pop());IN.push(Temp1.pop()); // Put back one elementwhile (!Temp1.isEmpty()) { // Process rest of elemswhile (IN.top() > Temp1.top()) // Find elem’s placeTemp2.push(IN.pop());IN.push(Temp1.pop()); // Put the element inwhile (!Temp2.isEmpty()) // Put the rest backIN.push(Temp2.pop());}}46477.3 The revised algorithm will work correctly, and its asymptotic complexity will remain Θ(n2). However, it will do about twice as many comparisons, since it will compare adjacent elements within the portion of the list already knownto be sorted. These additional comparisons are unproductive.7.4 While binary search will find the proper place to locate the next element, it will still be necessary to move the intervening elements down one position in the array. This requires the same number of operations as a sequential search. However, it does reduce the number of element/element comparisons, and may be somewhat faster by a constant factor since shifting several elements may be more efficient than an equal number of swap operations.7.5 (a) template <class Elem, class Comp>void selsort(Elem A[], int n) { // Selection Sortfor (int i=0; i<n-1; i++) { // Select i’th recordint lowindex = i; // Remember its indexfor (int j=n-1; j>i; j--) // Find least valueif (Comp::lt(A[j], A[lowindex]))lowindex = j; // Put it in placeif (i != lowindex) // Add check for exerciseswap(A, i, lowindex);}}(b) There is unlikely to be much improvement; more likely the algorithmwill slow down. This is because the time spent checking (n times) isunlikely to save enough swaps to make up.(c) Try it and see!7.6 • Insertion Sort is stable. A swap is done only if the lower element’svalue is LESS.• Bubble Sort is stable. A swap is done only if the lower element’s valueis LESS.• Selection Sort is NOT stable. The new low value is set only if it isactually less than the previous one, but the direction of the search isfrom the bottom of the array. The algorithm will be stable if “less than”in the check becomes “less than or equal to” for selecting the low key position.• Shell Sort is NOT stable. The sublist sorts are done independently, andit is quite possible to swap an element in one sublist ahead of its equalvalue in another sublist. Once they are in the same sublist, they willretain this (incorrect) relationship.• Quick-sort is NOT stable. After selecting the pivot, it is swapped withthe last element. This action can easily put equal records out of place.48 Chap. 7 Internal Sorting• Conceptually (in particular, the linked list version) Mergesort is stable.The array implementations are NOT stable, since, given that the sublistsare stable, the merge operation will pick the element from the lower listbefore the upper list if they are equal. This is easily modified to replace“less than” with “less than or equal to.”• Heapsort is NOT stable. Elements in separate sides of the heap are processed independently, and could easily become out of relative order.• Binsort is stable. Equal values that come later are appended to the list.• Radix Sort is stable. While the processing is from bottom to top, thebins are also filled from bottom to top, preserving relative order.7.7 In the worst case, the stack can store n records. This can be cut to log n in the worst case by putting the larger partition on FIRST, followed by the smaller. Thus, the smaller will be processed first, cutting the size of the next stacked partition by at least half.7.8 Here is how I derived a permutation that will give the desired (worst-case) behavior:a b c 0 d e f g First, put 0 in pivot index (0+7/2),assign labels to the other positionsa b c g d e f 0 First swap0 b c g d e f a End of first partition pass0 b c g 1 e f a Set d = 1, it is in pivot index (1+7/2)0 b c g a e f 1 First swap0 1 c g a e f b End of partition pass0 1 c g 2 e f b Set a = 2, it is in pivot index (2+7/2)0 1 c g b e f 2 First swap0 1 2 g b e f c End of partition pass0 1 2 g b 3 f c Set e = 3, it is in pivot index (3+7/2)0 1 2 g b c f 3 First swap0 1 2 3 b c f g End of partition pass0 1 2 3 b 4 f g Set c = 4, it is in pivot index (4+7/2)0 1 2 3 b g f 4 First swap0 1 2 3 4 g f b End of partition pass0 1 2 3 4 g 5 b Set f = 5, it is in pivot index (5+7/2)0 1 2 3 4 g b 5 First swap0 1 2 3 4 5 b g End of partition pass0 1 2 3 4 5 6 g Set b = 6, it is in pivot index (6+7/2)0 1 2 3 4 5 g 6 First swap0 1 2 3 4 5 6 g End of parition pass0 1 2 3 4 5 6 7 Set g = 7.Plugging the variable assignments into the original permutation yields:492 6 4 0 13 5 77.9 (a) Each call to qsort costs Θ(i log i). Thus, the total cost isni=1i log i = Θ(n2 log n).(b) Each call to qsort costs Θ(n log n) for length(L) = n, so the totalcost is Θ(n2 log n).7.10 All that we need to do is redefine the comparison test to use strcmp. The quicksort algorithm itself need not change. This is the advantage of paramerizing the comparator.7.11 For n = 1000, n2 = 1, 000, 000, n1.5 = 1000 ∗√1000 ≈ 32, 000, andn log n ≈ 10, 000. So, the constant factor for Shellsort can be anything less than about 32 times that of Insertion Sort for Shellsort to be faster. The constant factor for Shellsort can be anything less than about 100 times thatof Insertion Sort for Quicksort to be faster.7.12 (a) The worst case occurs when all of the sublists are of size 1, except for one list of size i − k + 1. If this happens on each call to SPLITk, thenthe total cost of the algorithm will be Θ(n2).(b) In the average case, the lists are split into k sublists of roughly equal length. Thus, the total cost is Θ(n logk n).7.13 (This question comes from Rawlins.) Assume that all nuts and all bolts havea partner. We use two arrays N[1..n] and B[1..n] to represent nuts and bolts. Algorithm 1Using merge-sort to solve this problem.First, split the input into n/2 sub-lists such that each sub-list contains twonuts and two bolts. Then sort each sub-lists. We could well come up with apair of nuts that are both smaller than either of a pair of bolts. In that case,all you can know is something like:N1, N2。

数据结构与算法分析c语言描述中文答案

数据结构与算法分析c语言描述中文答案

数据结构与算法分析c语言描述中文答案一、引言数据结构与算法是计算机科学中非常重要的基础知识,它们为解决实际问题提供了有效的工具和方法。

本文将以C语言描述中文的方式,介绍数据结构与算法分析的基本概念和原理。

二、数据结构1. 数组数组是在内存中连续存储相同类型的数据元素的集合。

在C语言中,可以通过定义数组类型、声明数组变量以及对数组进行操作来实现。

2. 链表链表是一种动态数据结构,它由一系列的节点组成,每个节点包含了数据和一个指向下一个节点的指针。

链表可以是单链表、双链表或循环链表等多种形式。

3. 栈栈是一种遵循“先进后出”(Last-In-First-Out,LIFO)原则的数据结构。

在C语言中,可以通过数组或链表实现栈,同时实现入栈和出栈操作。

4. 队列队列是一种遵循“先进先出”(First-In-First-Out,FIFO)原则的数据结构。

在C语言中,可以通过数组或链表实现队列,同时实现入队和出队操作。

5. 树树是一种非线性的数据结构,它由节点和边组成。

每个节点可以有多个子节点,其中一个节点被称为根节点。

在C语言中,可以通过定义结构体和指针的方式来实现树的表示和操作。

6. 图图是由顶点和边组成的数据结构,它可以用来表示各种实际问题,如社交网络、路网等。

在C语言中,可以通过邻接矩阵或邻接表的方式来表示图,并实现图的遍历和查找等操作。

三、算法分析1. 时间复杂度时间复杂度是用来衡量算法的执行时间随着问题规模增长的趋势。

常见的时间复杂度有O(1)、O(log n)、O(n)、O(n^2)等,其中O表示“量级”。

2. 空间复杂度空间复杂度是用来衡量算法的执行所需的额外内存空间随着问题规模增长的趋势。

常见的空间复杂度有O(1)、O(n)等。

3. 排序算法排序算法是对一组数据按照特定规则进行排序的算法。

常见的排序算法有冒泡排序、插入排序、选择排序、快速排序、归并排序等,它们的时间复杂度和空间复杂度各不相同。

清华大学出版社数据结构(C 版)(第2版)课后习题答案最全整理

清华大学出版社数据结构(C  版)(第2版)课后习题答案最全整理

第1 章绪论课后习题讲解1. 填空⑴()是数据的基本单位,在计算机程序中通常作为一个整体进行考虑和处理。

【解答】数据元素⑵()是数据的最小单位,()是讨论数据结构时涉及的最小数据单位。

【解答】数据项,数据元素【分析】数据结构指的是数据元素以及数据元素之间的关系。

⑶从逻辑关系上讲,数据结构主要分为()、()、()和()。

【解答】集合,线性结构,树结构,图结构⑷数据的存储结构主要有()和()两种基本方法,不论哪种存储结构,都要存储两方面的内容:()和()。

【解答】顺序存储结构,链接存储结构,数据元素,数据元素之间的关系⑸算法具有五个特性,分别是()、()、()、()、()。

【解答】有零个或多个输入,有一个或多个输出,有穷性,确定性,可行性⑹算法的描述方法通常有()、()、()和()四种,其中,()被称为算法语言。

【解答】自然语言,程序设计语言,流程图,伪代码,伪代码⑺在一般情况下,一个算法的时间复杂度是()的函数。

【解答】问题规模⑻设待处理问题的规模为n,若一个算法的时间复杂度为一个常数,则表示成数量级的形式为(),若为n*log25n,则表示成数量级的形式为()。

【解答】Ο(1),Ο(nlog2n)【分析】用大O记号表示算法的时间复杂度,需要将低次幂去掉,将最高次幂的系数去掉。

2. 选择题⑴顺序存储结构中数据元素之间的逻辑关系是由()表示的,链接存储结构中的数据元素之间的逻辑关系是由()表示的。

A 线性结构B 非线性结构C 存储位置D 指针【解答】C,D【分析】顺序存储结构就是用一维数组存储数据结构中的数据元素,其逻辑关系由存储位置(即元素在数组中的下标)表示;链接存储结构中一个数据元素对应链表中的一个结点,元素之间的逻辑关系由结点中的指针表示。

⑵假设有如下遗产继承规则:丈夫和妻子可以相互继承遗产;子女可以继承父亲或母亲的遗产;子女间不能相互继承。

则表示该遗产继承关系的最合适的数据结构应该是()。

数据结构课后习题答案详解(C语言版_严蔚敏) 2

数据结构课后习题答案详解(C语言版_严蔚敏) 2

数据结构习题集答案(C语言版严蔚敏)第2章线性表2.1 描述以下三个概念的区别:头指针,头结点,首元结点(第一个元素结点)。

解:头指针是指向链表中第一个结点的指针。

首元结点是指链表中存储第一个数据元素的结点。

头结点是在首元结点之前附设的一个结点,该结点不存储数据元素,其指针域指向首元结点,其作用主要是为了方便对链表的操作。

它可以对空表、非空表以及首元结点的操作进行统一处理。

2.2 填空题。

解:(1) 在顺序表中插入或删除一个元素,需要平均移动表中一半元素,具体移动的元素个数与元素在表中的位置有关。

(2) 顺序表中逻辑上相邻的元素的物理位置必定紧邻。

单链表中逻辑上相邻的元素的物理位置不一定紧邻。

(3) 在单链表中,除了首元结点外,任一结点的存储位置由其前驱结点的链域的值指示。

(4) 在单链表中设置头结点的作用是插入和删除首元结点时不用进行特殊处理。

2.3 在什么情况下用顺序表比链表好?解:当线性表的数据元素在物理位置上是连续存储的时候,用顺序表比用链表好,其特点是可以进行随机存取。

2.4 对以下单链表分别执行下列各程序段,并画出结果示意图。

解:2.5 画出执行下列各行语句后各指针及链表的示意图。

L=(LinkList)malloc(sizeof(LNode)); P=L;for(i=1;i<=4;i++){P->next=(LinkList)malloc(sizeof(LNode));P=P->next; P->data=i*2-1;}P->next=NULL;for(i=4;i>=1;i--) Ins_LinkList(L,i+1,i*2);for(i=1;i<=3;i++) Del_LinkList(L,i);解:2.6 已知L是无表头结点的单链表,且P结点既不是首元结点,也不是尾元结点,试从下列提供的答案中选择合适的语句序列。

a. 在P结点后插入S结点的语句序列是__________________。

数据结构与C语言程序设计试题及答案

数据结构与C语言程序设计试题及答案
5.已知模式匹配的KMP算法中模式串t=’adabbadada’,其next函数的值为0112112343。
6.在置换-选择排序中,假设工作区的容量为w,若不计输入、输出的时间,则对n个记录的文件而言,生成所有初始归并段所需时间为O(n log w)。
三.简答题(6’5)
1.有n个不同的英文单词,它们的长度相等,均为m,若n>>50,m<5,试问采用什么排序方法时间复杂度最佳?为什么?
采用基数排序方法最佳。
因单词长度相等,而只有26个字母组成,符合基数排序的条件。
因m<<n,故时间复杂性由O(m(n+rm))变成O(n)。
2.对于一个栈,给出输入序列A,B,C,试给出全部可能的输出序列。若输入序列的长度为n,则可能的输出序列有多少?
ABC,ACB,BAC,BCA,CBA
C2nn/(n+1)
()10、任何有向图的顶点都可以按拓扑序排序。
二.填空题(2’6)
1.假设用于通信的电文由8个字母组成,其频率分别为0.07,0.19,0.02,0.06, 0.32,0.03,0.21,0.10,为这8个字母设计哈夫曼编码,其中编码长度最大的字母的编码是5位。
2.已知二叉树按中序遍历所得到的结点序列为DCBGEAHFIJK,按后序遍历所得到的结点序列为DCEGBFHKJIA,按先序遍历所得到的结点序列为ABCDGEIHFJK。
O(n log n)
四.程序设计题(38’)
1.假设有两个集合A和B,均以元素值递增有序排列的带头结点的单链表作为存储结构。请编写算法求C=AB,要求C按元素值递增有序排列,并要求利用原表(即表A和表B)的结点空间存放表C。(12’)
void Join(LinkList &la , LinkList &lb , LinkList &lc)

算法与数据结构C语言习题参考答案1-5章

算法与数据结构C语言习题参考答案1-5章

绪论1.将下列复杂度由小到大重新排序:A.2n B.n! C.n5D.10 000 E.n*log2 (n)【答】10 000< n*log2(n)< n5< 2n < n!2.将下列复杂度由小到大重新排序:A.n*log2(n) B.n + n2 + n3C.24D.n0.5【答】24< n0.5< n*log2 (n) < n + n2 + n33.用大“O”表示法描述下列复杂度:A.5n5/2 + n2/5 B.6*log2(n) + 9nC.3n4+ n* log2(n) D.5n2 + n3/2【答】A:O (n5/2) B:O (n) C:O (n4) D:O (n2)4.按照增长率从低到高的顺序排列以下表达式:4n2 , log3n, 3n , 20n , 2000 , log2n , n2/3。

又n!应排在第几位?【答】按照增长率从低到高依次为:2000, log3n, log2n , n2/3 , 20n , 4n2 , 3n。

n!的增长率比它们中的每一个都要大,应排在最后一位。

5. 计算下列程序片断的时间代价:int i=1;while(i<=n){printf(“i=%d\n”,i);i=i+1;}【答】循环控制变量i从1增加到n,循环体执行n次,第一句i的初始化执行次数为1,第二句执行n次,循环体中第一句printf执行n次,第二句i从1循环到n,共执行n次。

所以该程序段总的时间代价为:T(n) = 1 + n + 2n = 3n+ 1 = O(n)6. 计算下列程序片断的时间代价:int i=1;while(i<=n){int j=1;while(j<=n){int k=1;while(k<=n){printf(“i=%d,j=%d,k=%d\n”,I,j,k);k=k+1;}j=j+1;}i=i+1;}【答】循环控制变量i从1增加到n,最外层循环体执行n次,循环控制变量j从1增加到n,中间层循环体执行n次,循环控制变量k从1增加到n,最内层循环体执行n次,所以该程序段总的时间代价为:T(n) = 1 + n + n{1 + n + n[1 + n + 2n +1] +1 +1}+ 1= 3n3 + 3n2 +4n +2= O(n3)2. 线性表1.试写一个插入算法int insertPost_seq(palist, p, x ),在palist所指顺序表中,下标为p的元素之后,插入一个值为x的元素,返回插入成功与否的标志。

《数据结构(C语言版)》课后答案 课后题答案

《数据结构(C语言版)》课后答案 课后题答案

//输出字符串 str
DestroyStack (&S);
DestroyStack (&T);
} 5.解答: int ACK ( int m, int n) {
if ( m == 0) return n + 1;
if ( m <> 0 && n == 0 ) return ACK( m - 1, 1);
{'>', '>', '>', '>', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'},
{'<', '<', '<', '<', '<', '=', ' '}, {'>', '>', '>', '>', ' ', '>', '>'},
{'<', '<', '<', '<', '<', ' ', '='}};
}
项目三 栈和队列

算法与数据结构C语言版课后习题参考答案(机械工业出版社)1绪论习题详细答案

算法与数据结构C语言版课后习题参考答案(机械工业出版社)1绪论习题详细答案

第1章概论习题参考答案一、基础知识题1.简述下列概念数据,数据元素,数据类型,数据结构,逻辑结构,存储结构,算法。

【解答】数据是信息的载体,是描述客观事物的数、字符,以及所有能输入到计算机中并被计算机程序识别和处理的符号的集合。

数据元素是数据的基本单位。

在不同的条件下,数据元素又可称为元素、结点、顶点、记录等。

数据类型是对数据的取值范围、数据元素之间的结构以及允许施加操作的一种总体描述。

每一种计算机程序设计语言都定义有自己的数据类型。

“数据结构”这一术语有两种含义,一是作为一门课程的名称;二是作为一个科学的概念。

作为科学概念,目前尚无公认定义,一般认为,讨论数据结构要包括三个方面,一是数据的逻辑结构,二是数据的存储结构,三是对数据进行的操作(运算)。

而数据类型是值的集合和操作的集合,可以看作是已实现了的数据结构,后者是前者的一种简化情况。

数据的逻辑结构反映数据元素之间的逻辑关系(即数据元素之间的关联方式或“邻接关系”),数据的存储结构是数据结构在计算机中的表示,包括数据元素的表示及其关系的表示。

数据的运算是对数据定义的一组操作,运算是定义在逻辑结构上的,和存储结构无关,而运算的实现则依赖于存储结构。

数据结构在计算机中的表示称为物理结构,又称存储结构。

是逻辑结构在存储器中的映像,包括数据元素的表示和关系的表示。

逻辑结构与计算机无关。

算法是对特定问题求解步骤的一种描述,是指令的有限序列。

其中每一条指令表示一个或多个操作。

一个算法应该具有下列特性:有穷性、确定性、可行性、输入和输出。

2.数据的逻辑结构分哪几种,为什么说逻辑结构是数据组织的主要方面?【解答】数据的逻辑结构分为线性结构和非线性结构。

(也可以分为集合、线性结构、树形结构和图形即网状结构)。

逻辑结构是数据组织的某种“本质性”的东西:(1)逻辑结构与数据元素本身的形式、内容无关。

(2)逻辑结构与数据元素的相对位置无关。

(3)逻辑结构与所含数据元素的个数无关。

数据结构(C语言版)第三版习题答案

数据结构(C语言版)第三版习题答案

精神成就事业,态度决定一切。

附录习题参考答案习题1参考答案1.1.选择题(1). A. (2). A. (3). A. (4). B.C. (5). A. (6). A. (7). C. (8). A. (9). B. (10.) A.1.2.填空题(1). 数据关系(2). 逻辑结构物理结构(3). 线性数据结构树型结构图结构(4). 顺序存储链式存储索引存储散列表(Hash)存储(5). 变量的取值范围操作的类别(6). 数据元素间的逻辑关系数据元素存储方式或者数据元素的物理关系(7). 关系网状结构树结构(8). 空间复杂度和时间复杂度(9). 空间时间(10). Ο(n)1.3 名词解释如下:数据:数据是信息的载体是计算机程序加工和处理的对象包括数值数据和非数值数据数据项:数据项指不可分割的、具有独立意义的最小数据单位数据项有时也称为字段或域数据元素:数据元素是数据的基本单位在计算机程序中通常作为一个整体进行考虑和处理一个数据元素可由若干个数据项组成数据逻辑结构:数据的逻辑结构就是指数据元素间的关系数据存储结构:数据的物理结构表示数据元素的存储方式或者数据元素的物理关系数据类型:是指变量的取值范围和所能够进行的操作的总和算法:是对特定问题求解步骤的一种描述是指令的有限序列1.4 语句的时间复杂度为:(1) Ο(n2)(2) Ο(n2)(3) Ο(n2)(4) Ο(n-1)(5) Ο(n3)1.5 参考程序:main(){int XYZ;scanf("%d %d%d"&X&YZ);if (X>=Y)if(X>=Z)if (Y>=Z) { printf("%d %d%d"XYZ);}else{ printf("%d %d%d"XZY);}else{ printf("%d %d%d"ZXY);}else if(Z>=X)if (Y>=Z) { printf("%d %d%d"YZX);}else{ printf("%d%d%d"ZYX);}else{ printf("%d%d%d"YXZ);}}1.6 参考程序:main(){int in;float xa[]p;printf("\nn=");scanf("%f"&n);printf("\nx=");scanf("%f"&x);for(i=0;i<=n;i++)scanf("%f "&a[i]);p=a[0];for(i=1;i<=n;i++){ p=p+a[i]*x;x=x*x;}printf("%f"p)'}习题2参考答案2.1选择题(1). C. (2). B. (3). B. (4). B. 5. D. 6. B. 7. B. 8. A. 9. A. 10. D.2.2.填空题(1). 有限序列(2). 顺序存储和链式存储(3). O(n) O(n)(4). n-i+1 n-i(5). 链式(6). 数据指针(7). 前驱后继(8). Ο(1) Ο(n)(9). s->next=p->next; p->next=s ;(10). s->next2.3. 解题思路:将顺序表A中的元素输入数组a若数组a中元素个数为n将下标为012...(n-1)/2的元素依次与下标为nn-1...(n-1)/2的元素交换输出数组a的元素参考程序如下:main(){int in;float ta[];printf("\nn=");scanf("%f"&n);for(i=0;i<=n-1;i++)scanf("%f "&a[i]);for(i=0;i<=(n-1)/2;i++){ t=a[i]; a[i] =a[n-1-i]; a[n-1-i]=t;} for(i=0;i<=n-1;i++)printf("%f"a[i]);}2.4 算法与程序:main(){int in;float ta[];printf("\nn=");scanf("%f"&n);for(i=0;i<n;i++)scanf("%f "&a[i]);for(i=1;i<n;i++)if(a[i]>a[0]{ t=a[i]; a[i] =a[0]; a[0]=t;}printf("%f"a[0]);for(i=2;i<n;i++)if(a[i]>a[1]{ t=a[i]; a[i] =a[1]; a[1]=t;}printf("%f"a[0]);}2.5 算法与程序:main(){int ijkn;float xta[];printf("\nx=");scanf("%f"&x);printf("\nn=");scanf("%f"&n);for(i=0;i<n;i++)scanf("%f "&a[i]); // 输入线性表中的元素for (i=0; i<n; i++) { // 对线性表中的元素递增排序k=i;for (j=i+1; j<n; j++) if (a[j]<a[k]) k=j; if (k<>j) {t=a[i];a[i]=a[k];a[k]=t;}}for(i=0;i<n;i++) // 在线性表中找到合适的位置if(a[i]>x) break;for(k=n-1;k>=i;i--) // 移动线性表中元素然后插入元素xa[k+1]=a[k];a[i]=x;for(i=0;i<=n;i++) // 依次输出线性表中的元素printf("%f"a[i]);}2.6 算法思路:依次扫描A和B的元素比较A、B当前的元素的值将较小值的元素赋给C如此直到一个线性表扫描完毕最后将未扫描完顺序表中的余下部分赋给C即可C的容量要能够容纳A、B两个线性表相加的长度有序表的合并算法:void merge (SeqList ASeqList BSeqList *C){ int ijk;i=0;j=0;k=0;while ( i<=st && j<=st )if (A.data[i]<=B.data[j])C->data[k++]=A.data[i++];elseC->data[k++]=B.data[j++];while (i<=st )C->data[k++]= A.data[i++];while (j<=st )C->data[k++]=B.data[j++];C->last=k-1;}2.7 算法思路:依次将A中的元素和B的元素比较将值相等的元素赋给C如此直到线性表扫描完毕线性表C就是所求递增有序线性表算法:void merge (SeqList ASeqList BSeqList *C){ int ijk;i=0;j=0;k=0;while ( i<=st)while(j<=st )if (A.data[i]=B.data[j])C->data[k++]=A.data[i++];C->last=k-1;}习题3参考答案3.1.选择题(1). D (2). C (3). D (4). C (5). B (6). C (7). C (8). C (9). B (10).AB (11). D (12). B (13). D (14). C (15). C (16). D(17). D (18). C (19). C (20). C 3.2.填空题(1) FILOFIFO(2) -13 4 X * + 2 Y * 3 / -(3) stack.topstack.s[stack.top]=x(4) p>llink->rlink=p->rlinkp->rlink->llink=p->rlink(5) (R-F+M)%M(6) top1+1=top2(7) F==R(8) front==rear(9) front==(rear+1)%n(10) N-13.3 答:一般线性表使用数组来表示的线性表一般有插入、删除、读取等对于任意元素的操作而栈只是一种特殊的线性表栈只能在线性表的一端插入(称为入栈push)或者读取栈顶元素或者称为"弹出、出栈"(pop)3.4 答:相同点:栈和队列都是特殊的线性表只在端点处进行插入删除操作不同点:栈只在一端(栈顶)进行插入删除操作;队列在一端(top)删除一端(rear)插入3.5 答:可能序列有14种:ABCD; ACBD; ACDB; ABDC; ADCB; BACD; BADC; BCAD; BCDA; BDCA; CBAD; CBDA; CDBA; DCBA3.6 答:不能得到435612最先出栈的是4则按321的方式出不可能得到1在2前的序列可以得到135426按如下方式进行push(1)pop()push(2)push(3)pop()push(4)push(5)pop()pop()pop()push(6)pop()3.7 答:stack3.8 非递归:int vonvert (int noint a[]) //将十进制数转换为2进制存放在a[] 并返回位数{int r;SeStack s*p;P=&s;Init_stack(p);while(no){push(pno%2);no/=10;}r=0;while(!empty_stack(p)){pop(pa+r);r++;}return r;}递归算法:void convert(int no){if(no/2>0){Convert(no/2);Printf("%d"no%2);}elseprintf("%d"no);}3.9 参考程序:void view(SeStack s){SeStack *p; //假设栈元素为字符型char c;p=&s;while(!empty_stack(p)){c=pop(p);printf("%c"c);}printf("\n");}3.10 答:char3.11 参考程序:void out(linkqueue q){int e;while(q.rear !=q.front ){dequeue(qe);print(e); //打印}}习题4参考答案4.1 选择题:(1). A (2). D (3). C (4). C (5). B (6). B (7). D (8). A (9). B (10). D 4.2 填空题:(1)串长相等且对应位置字符相等(2)不含任何元素的串(3)所含字符均是空格所含空格数(4) 10(5) "hello boy"(6) 13(7) 1066(8)模式匹配(9)串中所含不同字符的个数(10) 364.3 StrLength (s)=14StrLength (t)=4SubStr( s87)=" STUDENT"SubStr(t21)="O"StrIndex(s"A")=3StrIndex (st)=0StrRep(s"STUDENT"q)=" I AM A WORKER"4.4 StrRep(s"Y""+");StrRep(s"+*""*Y");4.5 空串:不含任何字符;空格串:所含字符都是空格串变量和串常量:串常量在程序的执行过程中只能引用不能改变;串变量的值在程序执行过程中是可以改变和重新赋值的主串与子串:子串是主串的一个子集串变量的名字与串变量的值:串变量的名字表示串值的标识符4.6int EQUAl(ST){char *p*q;p=&S;q=&T;while(*p&&*q){if(*p!=*q)return *p-*q;p++;q++;}return *p-*q;}4.7(1)6*8*6=288(2)1000+47*6=1282(3)1000+(8+4)*8=1096(4)1000+(6*7+4)*8=13684.8习题5参考答案5.1 选择(1)C(2)B(3)C(4)B(5)C(6)D(7)C(8)C(9)B(10)C (11)B(12)C(13)C(14)C(15)C(16)B5.2 填空(1)1(2)1036;1040(3)2i(4) 1 ; n ; n-1 ; 2(5)2k-1;2k-1(6)ACDBGJKIHFE(7)p!=NULL(8)Huffman树(9)其第一个孩子; 下一个兄弟(10)先序遍历;中序遍历5.3叶子结点:C、F、G、L、I、M、K;非终端结点:A、B、D、E、J;各结点的度:结点: A B C D E F G L I J K M度: 4 3 0 1 2 0 0 0 0 1 0 0树深:4无序树形态如下:二叉树形态如下:5.5二叉链表如下:三叉链表如下:5.6先序遍历序列:ABDEHICFJG中序遍历序列:DBHEIAFJCG后序遍历序列:DHIEBJFGCA5.7(1) 先序序列和中序序列相同:空树或缺左子树的单支树;(2) 后序序列和中序序列相同:空树或缺右子树的单支树;(3) 先序序列和后序序列相同:空树或只有根结点的二叉树5.8这棵二叉树为:先根遍历序列:ABFGLCDIEJMK后根遍历序列:FGLBCIDMJKEA层次遍历序列:ABCDEFGLIJKM5.10证明:设树中结点总数为n叶子结点数为n0则n=n0 + n1 + ...... + nm (1)再设树中分支数目为B则B=n1 + 2n2 + 3n3 + ...... + m nm (2)因为除根结点外每个结点均对应一个进入它的分支所以有n= B + 1 (3)将(1)和(2)代入(3)得n0 + n1 + ...... + nm = n1 + 2n2 + 3n3 + ...... + m nm + 1 从而可得叶子结点数为:n0 = n2 + 2n3 + ...... + (m-1)nm + 15.11由5.10结论得n0 = (k-1)nk + 1又由 n=n0 + nk得nk= n-n0代入上式得n0 = (k-1)(n-n0)+ 1叶子结点数为:n0 = n (k-1) / k5.12int NodeCount(BiTree T){ //计算结点总数if(T)if (T-> lchild==NULL )&&( T --> rchild==NULL )return 1;elsereturn NodeCount(T-> lchild ) +Node ( T --> rchild )+1; elsereturn 0;}void ExchangeLR(Bitree bt){/* 将bt所指二叉树中所有结点的左、右子树相互交换 */ if (bt && (bt->lchild || bt->rchild)) {bt->lchild<->bt->rchild;Exchange-lr(bt->lchild);Exchange-lr(bt->rchild);}}/* ExchangeLR */5.14int IsFullBitree(Bitree T){/* 是则返回1否则返回0*/Init_Queue(Q); /* 初始化队列*/flag=0;In_Queue(QT); /* 根指针入队列按层次遍历*/while(!Empty_Queue (Q)){Out_Queue(Qp);if(!p) flag=1; /* 若本次出队列的是空指针时则修改flag值为1若以后出队列的指针存在非空则可断定不是完全二叉树 */else if (flag) return 0; /*断定不是完全二叉树 */ else{In_Queue(Qp->lchild);In_Queue(Qp->rchild); /* 不管孩子是否为空都入队列*/}}/* while */return 1; /* 只有从某个孩子指针开始之后所有孩子指针都为空才可断定为完全二叉树*/}/* IsFullBitree */转换的二叉树为:5.16对应的森林分别为:5.17typedef char elemtype;typedef struct{ elemtype data;int parent;} NodeType;(1) 求树中结点双亲的算法:int Parent(NodeType t[ ]elemtype x){/* x不存在时返回-2否则返回x双亲的下标(根的双亲为-1 */for(i=0;i<MAXNODE;i++)if(x==t[i].data) return t[i].parent; return -2;}/*Parent*/(2) 求树中结点孩子的算法:void Children(NodeType t[ ]elemtype x){for(i=0;i<MAXNODE;i++){if(x==t[i].data)break;/*找到x退出循环*/}/*for*/if(i>=MAXNODE) printf("x不存在\n"); else {flag=0;for(j=0;j<MAXNODE;j++)if(i==t[j].parent){ printf("x的孩子:%c\n"t[j].data);flag=1;}if(flag==0) printf("x无孩子\n");}/*Children*/5.18typedef char elemtype;typedef struct ChildNode{ int childcode;struct ChildNode *nextchild;}typedef struct{ elemtype data;struct ChildNode *firstchild;} NodeType;(1) 求树中结点双亲的算法:int ParentCL(NodeType t[ ]elemtype x){/* x不存在时返回-2否则返回x双亲的下标 */for(i=0;i<MAXNODE;i++)if(x==t[i].data) {loc=i;/*记下x的下标*/break;}if(i>=MAXNODE) return -2; /* x不存在 *//*搜索x的双亲*/for(i=0;i<MAXNODE;i++)for(p=t[i].firstchild;p!=NULL;p=p->nextchild) if(loc==p->childcode)return i; /*返回x结点的双亲下标*/}/* ParentL */(2) 求树中结点孩子的算法:void ChildrenCL(NodeType t[ ]elemtype x){for(i=0;i<MAXNODE;i++)if(x==t[i].data) /*依次打印x的孩子*/{flag=0; /* x存在 */for(p=t[i].firstchild;p;p=p->nextchild){ printf("x的孩子:%c\n"t[p-> childcode].data);flag=1;}if(flag==0) printf("x无孩子\n");return;}/*if*/printf("x不存在\n");return;}/* ChildrenL */5.19typedef char elemtype;typedef struct TreeNode{ elemtype data;struct TreeNode *firstchild; struct TreeNode *nextsibling; } NodeType;void ChildrenCSL(NodeType *telemtype x){ /* 层次遍历方法 */Init_Queue(Q); /* 初始化队列 */In_Queue(Qt);count=0;while(!Empty_Queue (Q)){Out_Queue(Qp);if(p->data==x){ /*输出x的孩子*/p=p->firstchild;if(!p) printf("无孩子\n");else{ printf("x的第%i个孩子:%c\n"++countp->data);/*输出第一个孩子*/p=p->nextsibling; /*沿右分支*/while(p){printf("x的第%i个孩子:%c\n"++countp->data);p=p-> nextsibling;}}return;}if(p-> firstchild) In_Queue(Qp-> firstchild);if(p-> nextsibling) In_Queue(Qp-> nextsibling);}}/* ChildrenCSL */5.20(1) 哈夫曼树为:(2) 在上述哈夫曼树的每个左分支上标以1右分支上标以0并设这7个字母分别为A、B、C、D、E、F和H如下图所示:则它们的哈夫曼树为分别为:A:1100B:1101C:10D:011E:00F:010H:111习题6参考答案6.1 选择题(1)C (2)A (3)B(4)C(5)B______条边(6)B(7)A(8)A(9)B(10)A(11)A(12)A(13)B(14)A(15)B(16)A(17)C 6.2 填空(1) 4(2) 1对多 ; 多对多(3) n-1 ; n(4) 0_(5)有向图(6) 1(7)一半(8)一半(9)___第i个链表中边表结点数___(10)___第i个链表中边表结点数___(11)深度优先遍历;广度优先遍历(12)O(n2)(13)___无回路6.3(1)邻接矩阵:(2)邻接链表:(3)每个顶点的度:顶点度V1 3V2 3V3 2V4 3V5 36.4(1)邻接链表:(2)逆邻接链表:(3)顶点入度出度V1 3 0V2 2 2V3 1 2V4 1 3V5 2 1V6 2 36.5(1)深度优先查找遍历序列:V1 V2 V3 V4 V5; V1 V3 V5 V4 V2; V1 V4 V3 V5 V2 (1)广度优先查找遍历序列:V1 V2 V3 V4 V5; V1 V3 V2 V4 V5; V1 V4 V3 V2 V56.6有两个连通分量:6.7顶点(1)(2)(3)(4)(5)Low Close Cost VexLow CloseCost VexLow CloseCost VexLow CloseCost VexLow CloseCost VexV10 00 00 00 00 0V21 00 00 00 00 0V31 01 00 00 00 0V43 02 12 10 10 1V5∞ 05 13 22 30 3U{v1} {v1v2} {v1v2v3} {v1 v2 v3 v4} {v1 v2 v3 v4 v5} T {} { (v1 v2) } {(v1 v2) (v1 v3) } {(v1 v2) (v1 v3) (v2 v4) } {(v1 v2) (v1v3)(v2v4)(v4v5) }最小生成树的示意图如下:6.8拓扑排序结果: V3--> V1 --> V4 --> V5 --> V2 --> V66.9(1)建立无向图邻接矩阵算法:提示:参见算法6.1因为无向图的邻接矩阵是对称的所以有for (k=0; k<G ->e; k++) /*输入e条边建立无向图邻接矩阵*/{ scanf("\n%d%d"&i&j);G ->edges[i][j]= G ->edges[j][i]=1;}(2)建立无向网邻接矩阵算法:提示:参见算法6.1初始化邻接矩阵:#define INFINITY 32768 /* 表示极大值*/for(i=0;i<G->n;i++)for(j=0;j<G->n;j++) G->edges[i][j]= INFINITY;输入边的信息:不仅要输入边邻接的两个顶点序号还要输入边上的权值for (k=0; k<G ->e; k++) /*输入e条边建立无向网邻接矩阵*/{ scanf("\n%d%d%d"&i&j&cost); /*设权值为int型*/G ->edges[i][j]= G ->edges[j][i]=cost;/*对称矩阵*/}(3)建立有向图邻接矩阵算法:提示:参见算法6.16.10(1)建立无向图邻接链表算法:typedef VertexType char;int Create_NgAdjList(ALGraph *G){ /* 输入无向图的顶点数、边数、顶点信息和边的信息建立邻接表 */scanf("%d"&n); if(n<0) return -1; /* 顶点数不能为负 */G->n=n;scanf("%d"&e); if(e<0) return =1; /*边数不能为负 */G->e=e;for(m=0;m< G->n ;m++)G-> adjlist [m].firstedge=NULL; /*置每个单链表为空表*/for(m=0;m< G->n;m++)G->adjlist[m].vertex=getchar(); /*输入各顶点的符号*/for(m=1;m<= G->e; m++){scanf("\n%d%d"&i&j); /* 输入一对邻接顶点序号*/if((i<0 || j<0) return -1;p=(EdgeNode*)malloc(sizeof(EdgeNode));/*在第i+1个链表中插入一个边表结点*/ p->adjvex=j;p->next= G-> adjlist [i].firstedge;G-> adjlist [i].firstedge=p;p=(EdgeNode*)malloc(sizeof(EdgeNode));/*在第j+1个链表中插入一个边表结点*/ p->adjvex=i;p->next= G-> adjlist [j].firstedge;G-> adjlist [j].firstedge=p;} /* for*/return 0; /*成功*/}//Create_NgAdjList(2)建立有向图逆邻接链表算法:typedef VertexType char;int Create_AdjList(ALGraph *G){ /* 输入有向图的顶点数、边数、顶点信息和边的信息建立逆邻接链表 */scanf("%d"&n); if(n<0) return -1; /* 顶点数不能为负 */G->n=n;scanf("%d"&e); if(e<0) return =1; /*弧数不能为负 */G->e=e;for(m=0;m< G->n; m++)G-> adjlist [m].firstedge=NULL; /*置每个单链表为空表*/for(m=0;m< G->n;m++)G->adjlist[m].vertex=getchar(); /*输入各顶点的符号*/for(m=1;m<= G->e ; m++){scanf("\n%d%d"&t&h); /* 输入弧尾和弧头序号*/if((t<0 || h<0) return -1;p=(EdgeNode*)malloc(sizeof(EdgeNode));/*在第h+1个链表中插入一个边表结点*/ p->adjvex=t;p->next= G-> adjlist [h].firstedge;G-> adjlist [h].firstedge=p;} /* for*/return 0; /*成功*/}//Create_AdjList6.11void Create_AdjM(ALGraph *G1MGraph *G2){ /*通过无向图的邻接链表G1生成无向图的邻接矩阵G2*/G2->n=G1->n; G2->e=G1->e;for(i=0;i<G2->n;i++) /* 置G2每个元素为0 */for(j=0;j<G2->n;j++) G2->edges[i][j]= 0;for(m=0;m< G1->n;m++)G2->vexs[m]=G1->adjlist[m].vertex; /*复制顶点信息*/num=(G1->n/2==0?G1->n/2:G1->n/2+1); /*只要搜索前n/2个单链表即可*/for(m=0;m< num;m++){ p=G1->adjlist[m].firstedge;while(p){ /* 无向图的存储具有对称性*/G2->edges[m][ p->adjvex ]= G2->edges[p->adjvex ] [m] =1;p==p->next;}}/* for */}/*Create_AdjM */void Create_AdjL(ALGraph *G1MGraph *G2){ /*通过无向图的邻接矩阵G1生成无向图的邻接链表G2*/G2->n=G1->n; G2->e=G1->e;for(i=0;i<G1->n;i++) /* 建立每个单链表 */{ G2->vexs[i]=G1->adjlist[i].vertex;G2->adjlist[i].firstedge=NULL;for(j=i; j<G1->n; j++) /*对称矩阵只要搜索主对角以上的元素即可*/{ if(G1->edges[i][j]== 1){ p=(EdgeNode*)malloc(sizeof(EdgeNode));/*在第i+1个链表中插入一个边表结点*/p->adjvex=j;p->next= G-> adjlist [i].firstedge;G-> adjlist [i].firstedge=p;p=(EdgeNode*)malloc(sizeof(EdgeNode));/*在第j+1个链表中插入一个边表结点*/p->adjvex=i;p->next= G-> adjlist [j].firstedge;G-> adjlist [j].firstedge=p;}/*if*/}/* for*/}/* for*/}/* Create_AdjL */6.13(1) 邻接矩阵中1的个数的一半;(2) 若位于[i-1j-1]或[j-1i-1]位置的元素值等于1则有边相连否则没有(3) 顶点i的度等于第i-1行中或第i-1列中1的个数6.14(1) 邻接链表中边表结点的个数的一半;(2) 若第i-1(或j-1)个单链表中存在adjvex域值等于j-1(或i-1)的边表结点则有边相连否则没有(3) 顶点i的度等于第i-1个单链表中边表结点的个数提示:参见算法6.2 和6.3习题 7参考答案7.1 选择题(1)C (2)C (3) C (4)B (5) A (6)A (7) D (8)B (9)D (10) B(11)B (12)A (13)C (14)C (15)A (16)D (17)C (18)BC (19)B (20)A7.2 填空题(1) O(n)O(log2n)(2) 12485log2(n+1)-1(3)小于大于(4)增序序列(5)m-1(6) 70; 342055(7) n/m(8)开放地址法链地址法(9)产生冲突的可能性就越大产生冲突的可能性就越小(10)关键码直接(11)②①⑦(12) 1616821(13)直接定址法数字分析法平方取中法折叠法除留余数法随机数法(14)开放地址法再哈希法链地址法建立一个公共溢出区(15)装满程度(16)索引快(17)哈希函数装填因子(18)一个结点(19)中序(20)等于7.3 一棵二叉排序树(又称二叉查找树)或者是一棵空树或者是一棵同时满足下列条件的二叉树:(1)若它的左子树不空则左子树上所有结点的键值均小于它根结点键值(2)若它的右子树不空则右子树上所有结点的键值均大于它根结点键值(3)它的左、右子树也分别为二叉排序树7.4 对地址单元d=H(K)如发生冲突以d为中心在左右两边交替进行探测按照二次探测法键值K的散列地址序列为:do=H(K)d1=(d0+12)mod md2=(d0-12)mod md3=(d0+22)mod md4=(d0-12)mod m......7.5 衡量算法的标准有很多时间复杂度只是其中之一尽管有些算法时间性能很好但是其他方面可能就存在着不足比如散列查找的时间性能很优越但是需要关注如何合理地构造散列函数问题而且总存在着冲突等现象为了解决冲突还得采用其他方法二分查找也是有代价的因为事先必须对整个查找区间进行排序而排序也是费时的所以常应用于频繁查找的场合对于顺序查找尽管效率不高但却比较简单常用于查找范围较小或偶而进行查找的情况7.6此法要求设立多个散列函数Hii=1...k当给定值K与闭散列表中的某个键值是相对于某个散列函数Hi的同义词因而发生冲突时继续计算该给定值K在下一个散列函数Hi+1下的散列地址直到不再产生冲突为止7.7散列表由两个一维数组组成一个称为基本表另一个称为溢出表插入首先在基本表上进行;假如发生冲突则将同义词存人溢出表7.8 结点个数为n时高度最小的树的高度为1有两层它有n-1个叶结点1个分支结点;高度最大的树的高度为n-l有n层它有1个叶结点n-1个分支结点7.9 设顺序查找以h为表头指针的有序链表若查找成功则返回结点指针p查找失败则返回null值pointer sqesrearch(pointer hint xpointerp){p=null;while(h)if(x>h->key)h=h->link;else{if(x==h->key)p=h;return(p);}}虽然链表中的结点是按从小到大的顺序排列的但是其存储结构为单链表查找结点时只能从头指针开始逐步进行搜索故不能用折半(二分)查找7.10 分析:对二叉排序树来讲其中根遍历序列为一个递增有序序列因此对给定的二叉树进行中根遍历如果始终能保证前一个值比后一个值小则说明该二叉树是二叉排序树int bsbtr (bitreptr T) /*predt记录当前结点前趋值初值为-∞*/{ if (T==NULL) return(1);else{b1=bsbtr(T->lchild);/*判断左子树*/if (!b1|| (predt>=T->data)) return(0);*当前结点和前趋比较*/ predt=T->data;/*修改当前结点的前趋值*/return(bsbtr(T->rchild));/*判断右子树并返回最终结果*/}}7.11 (1)使用线性探查再散列法来构造散列表如表下所示散列表───────────────────────────────地址 0 1 2 3 4 5 6 7 8 9 10───────────────────────────────数据 33 1 13 12 34 38 27 22───────────────────────────────(2)使用链地址法来构造散列表如下图(3)装填因子a=8/11使用线性探查再散列法查找成功所需的平均查找次数为Snl=0.5(1+1/(1-a))=0.5*(1+1/(1-8/11))=7/3使用线性探查再散列法查找不成功所需的平均查找次数为:Unl=0.5(1+1/(1-a)2)=0.5*(1+1/(1-8/11)2)=65/9 使用链地址法查找成功所需的平均查找次数为:Snc=l+a/2=1+8/22=15/11使用链地址法查找不成功所需的平均查找次数为: 'Unl=a+e-a=8/1l+e-8/117.12 分析:在等查区间的上、下界处设两个指针由此计算出中间元素的序号当中间元素大于给定值X时接下来到其低端区间去查找;当中间元素小于给定值X时接下来到其高端区间去查找;当中间元素等于给定值X时表示查找成功输出其序号Int binlist(sqtable Aint stkeytype X) /*t、s分别为查找区间的上、下界*/{ if(s<t) return(0);/*查找失败*/else{ mid=(S+t)/2;switCh(mid){case x<A.item[midJ.key: return(binlist(Asmid-lX));/*在低端区间上递归*/case x==A.item[mid].key: return(mid);/+查找成功*/ case x>A.item[mid].key: return(amid+ltX));/*在高端区间上递归*/}}}int sqsearch0 (sqtable Akeytype X) /*数组有元素n个*/{ i=l;A.item[n+1].key=X;/t设置哨兵*/while (A.item[n+1].key!=X) i++;return (i% (n/1));/*找不到返回0找到返回其下标*/}查找成功平均查找长度为:(1+2+3+...+n)/n:(1+n)/2查找不成功平均查找长度为:n+17.14散列函数:H(key)=100+(key个位数+key十位数) mod l0;形成的散列表:100 101 102 103 104 105 106 107 108 10998 75 63 46 49 79 61 53 17查找成功时的平均长度为:(1+2+1+1+5+1+1+5+5+3)/10=2.5次由于长度为10的哈希表已满因此在插人第11个记录时所需作的比较次数的期望值为10查找不成功时的平均长度为10习题 8参考答案8.1 选择题(1)B (2)A (3)D (4)C (5)B (6)A (7)B (8)C (9)A (10)C(11)D (12)C (13) C (14)D (15)C (16)B (17) D (18)C (19)B (20)D8.2填空题(1)快速归并(2) O(log2n)O(nlog2n)(3)归并(4)向上根结点(5) 1918162030(6)(7)4913275076386597(8)88(9)插入选择(每次选择最大的)(10)快速归并(11)O(1)O(nlog2n)(12)稳定(13)3(14)(15205040)(15)O(log2n)(16)O(n2)(17)冒泡排序快速排序(18)完全二叉树n/2(19)稳定不稳定(20)24(2015)8.3. 假定给定含有n个记录的文件(r1f2...rn)其相应的关键字为(k1k2...kn)则排序就是确定文件的一个序列rrr2...rn使得k1'≤k2'≤...≤kn'从而使得文件中n个记录按其对应关键字有序排列如果整个排序过程在内存中进行则排序叫内部排序假设在待排序的文件中存在两个或两个以上的记录具有相同的关键字若采用某种排序方法后使得这些具有相同关键字的记录在排序前后相对次序依然保持不变则认为该排序方法是稳定的否则就认为排序方法是不稳定的8.4.稳定的有:直接插入排序、二分法插入排序、起泡排序、归并排序和直接选择排序8.5.初始记录序列按关键字有序或基本有序时比较次数为最多8.6.设5个元素分别用abcde表示取a与b、c与d进行比较若a>bc>d(也可能是a<bc<d此时情况类似)显然此时进行了两次比较取b与d再比较若b>d则a>b>d若b<d则有c>d>b此时已进行了3次比较要使排序比较最多7次可把另外两个元素按折半检索排序插入到上面所得的有序序列中此时共需要4次比较从而可得算法共只需7次比较8.7.题目中所说的几种排序方法中其排序速度都很快但快速排序、归并排序、基数排序和Shell排序都是在排序结束后才能确定数据元素的全部序列而排序过程中无法知道部分连续位置上的最终元素而堆排序则是每次输出一个堆顶元素(即最大或最少值的元素)然后对堆进行再调整保证堆顶元素总是当前剩下元素的最大或最小的从而可知欲在一个大量数据的文件中如含有15000个元素的记录文件中选取前10个最大的元素可采用堆排序进行8.8.二分法排序8.9.void insertsort(seqlist r) &nbsp;{ //对顺序表中记录R[0一N-1)按递增序进行插入排序&NBSP;int ij; &nbsp;for(i=n-2;i>=0; i--) //在有序区中依次插入r[n-2]..r[0] &nbsp;if(r[i].key>r[i+1].key) //若不是这样则r[i]原位不动&nbsp;{ &nbsp;r[n]=r[i];j=i+l;//r[n]是哨兵&nbsp;do{ //从左向右在有序区中查找插入位置&nbsp;r[j-1]= r[j];//将关键字小于r[i].key的记录向右移&nbsp;j++; &nbsp;}whle(r[j].key r[j-1]=r[n];//将引i)插入到正确位置上&nbsp;}//endif&nbsp;}//insertsort. &nbsp;8.10.建立初始堆:[937 694 863 265 438 751 742129075 3011]&NBSP;&NBSP;第一次排序重建堆:[863 694 751 765 438 301 742 129 075]9378.11.在排序过程中每次比较会有两种情况出现若整个排序过程至少需作t次比较则显然会有2^t个情况由于n个结点总共有n!种不同的排列因而必须有n!种不同的比较路径于是: 2t≥n!即t≥log2n!因为log2nl=nlog2n-n/ln2+log2n/2+O(1)故有log2n!≈nlog2n从而t≧nlog2n得证8.12.依据堆定义可知:序列(1)、(2)、(4)是堆(3)不是堆从而可对其调整使之为如下的大根堆(1009580604095821020)8.13.第一趟:[265 301] [129 751] [863 937] [694 742] [076 438]&NBSP; &NBSP;第二趟:[129 265 301 751] [694 742 863 937] [076 438]&NBSP;&NBSP;第三趟:[129 265 301 694 742 751 863 937] [076 438]&NBSP;&NBSP;第四趟:[076 129 265 301 438 694 742 751 863 937]&NBSP;8.14.(1)归并排序:(1829) (2547) (1258) (1051)(18252947) (10125158)(1012182529475158)(2)快速排序:(1018251229585147)(1018251229475158)(1012182529475158)(3)堆排序:初始堆(大顶堆):(58 47512918122510)第一次调整:(51 472529181210)(58)第二次调整:(47 2925101812)(5158)第三次调整:(29 18251012)(475158)第四次调整:(25 181210)(29475158)第五次调整:(18 1012)(2529475158)第六次调整:(12 10) (182529475158)第七次调整:(10 12182529475158)8.15.(1)直接插入排序序号 1 2 3 4 5 6 7 8 9 10 11 12 关键字 83 40 63 13 84 35 96 57 39 79 61 151=2 40 83 [63 13 84 35 96 57 39 79 61 15] 1=3 40 63 83 [13 84 35 96 57 39 79 61 15] 1=4 13 40 63 83 [84 3 5 96 57 39 79 61 15] I=5 13 40 63 83 84 [35 96 57 39 79 61 15] I=6 13 35 40 63 83 84 [96 57 39 79 61 15] 1=7 13 35 40 63 83 84 96 [57 39 79 61 15] 1=8 13 35 40 57 63 83 84 96 [ 39 79 61 15] 1=9 13 35 39 40 57 63 83 84 96 [79 61 15] I=10 13 35 39 40 57 63 79 83 84 96 [61 15] I=11 13 35 39 40 57 61 63 79 83 84 96 [15] 1=12 13 15 35 39 40 57 61 63 79 83 84 96 (2)直接选择排序序号 1 2 3 4 5 6 7 8 9 10 11 12 关键字 83 40 63 13 84 35 96 57 39 79 61 15i=1 13 [ 40 63 83 84 35 96 57 39 79 61 15] i=2 13 15 [63 83 84 35 96 57 39 79 61 40] i=3 13 15 35 [83 84 63 96 57 39 79 61 40] i=4 13 15 35 39 [84 63 96 57 83 79 61 40] i=5 13 15 35 39 40 [63 96 57 83 79 61 84] i=6 13 15 35 39 40 57 [96 63 83 79 61 84] i=7 13 15 35 39 40 57 61 [63 83 79 96 84] i=8 13 15 35 39 40 57 61 63 [83 79 96 84] i=9 13 15 35 39 40 57 61 63 79 183 96 84] i=10 13 15 35 39 40 57 61 63 79 83 [96 84] i=11 13 15 35 39 40 57 61 63 79 83 84 [96] (3)快速排序关键字 83 40 63 13 84 35 96 57 39 79 61 15 第一趟排序后 [15 40 63 13 61 35 79 57 39] 83 [96 84] 第二趟排序后 [13] 15 [63 40 61 35 79 57 39] 83 84 [96] 第三趟排序后 13 15 [39 40 61 35 57] 63 [79] 83 84 96 第四趟排序后 13 15 [35] 39 [61 40 57] 63 79 83 84 96第五趟排序后 13 15 35 39 [57 40] 61 63 79 83 84 96 第六趟排序后 13 15 35 39 40 [57] 61 63 79 83 84 96 第七趟排序后 13 15 35 39 40 57 61 63 79 83 84 96 (4)堆排序关键字 83 40 63 13 84 35 96 57 39 79 61 15排序成功的序列 96 84 83 79 63 61 57 40 39 35 15 13(5)归并排序关键字 83 40 63 13 84 35 96 57 39 79 61 15 第一趟排序后 [40 83] [13 63] [3584] [57 96] [39 79] [15 61]第二趟排序后 [13 40 63 83] [35 57 84 96] [15 39 61 79] 第三趟排序后 [13 35 40 57 63 83 84 96]] [15 39 61 79] 第四趟排序后 13 15 35 39 40 57 61 63 79 83 84 96。

算法与数据结构C语言版课后习题答案(机械工业出版社)第3,4章习题参考答案

算法与数据结构C语言版课后习题答案(机械工业出版社)第3,4章习题参考答案

算法与数据结构C语⾔版课后习题答案(机械⼯业出版社)第3,4章习题参考答案第3章栈和队列⼀、基础知识题3.1有五个数依次进栈:1,2,3,4,5。

在各种出栈的序列中,以3,4先出的序列有哪⼏个。

(3在4之前出栈)。

【解答】34215 ,34251,345213.2铁路进⾏列车调度时,常把站台设计成栈式结构,若进站的六辆列车顺序为:1,2,3,4,5,6,那么是否能够得到435612, 325641, 154623和135426的出站序列,如果不能,说明为什么不能;如果能,说明如何得到(即写出"进栈"或"出栈"的序列)。

【解答】输⼊序列为123456,不能得出435612和154623。

不能得到435612的理由是,输出序列最后两元素是12,前⾯4个元素(4356)得到后,栈中元素剩12,且2在栈顶,不可能让栈底元素1在栈顶元素2之前出栈。

不能得到154623的理由类似,当栈中元素只剩23,且3在栈顶,2不可能先于3出栈。

得到325641的过程如下:1 2 3顺序⼊栈,32出栈,得到部分输出序列32;然后45⼊栈,5出栈,部分输出序列变为325;接着6⼊栈并退栈,部分输出序列变为3256;最后41退栈,得最终结果325641。

得到135426的过程如下:1⼊栈并出栈,得到部分输出序列1;然后2和3⼊栈,3出栈,部分输出序列变为13;接着4和5⼊栈,5,4和2依次出栈,部分输出序列变为13542;最后6⼊栈并退栈,得最终结果135426。

3.3若⽤⼀个⼤⼩为6的数组来实现循环队列,且当前rear和front的值分别为0和3,当从队列中删除⼀个元素,再加⼊两个元素后,rear和front的值分别为多少?【解答】2和43.4设栈S和队列Q的初始状态为空,元素e1,e2,e3,e4,e5和e6依次通过栈S,⼀个元素出栈后即进队列Q,若6个元素出队的序列是e3,e5,e4,e6,e2,e1,则栈S的容量⾄少应该是多少?【解答】43.5循环队列的优点是什么,如何判断“空”和“满”。

数据结构与算法分析c第三版答案

数据结构与算法分析c第三版答案

数据结构与算法分析c第三版答案【篇一:数据结构第三章习题答案】txt>#include iostream#include stringusing namespace std;bool huiwen(string s){int n=s.length();int i,j;i= 0;j=n-1;while(ij s[i]==s[j]){ i++;j--;}if(i=j) return true;else return false;}int main(){string s1;cins1;couthuiwen(s1);return 0;}=============(2)设从键盘输入一整数的序列:a1, a2, a3,…,an,试编写算法实现:用栈结构存储输入的整数,当ai≠-1时,将ai进栈;当ai=-1时,输出栈顶整数并出栈。

算法应对异常情况(入栈满等)给出相应的信息。

#include iostreamusing namespace std;#define overflow -2#define ok 1#define error 0typedef int selemtype;typedef int status;typedef struct{selemtype a[5];int top;} sqstack;status initstack(sqstack s){s.top=0;return ok;}status push(sqstack s,selemtype e){if (s.top4){coutoverlow!endl;return error;}else s.a[s.top++]=e;return ok;}status pop(sqstack s,selemtype e){if (s.top==0) {coutunderflowendl; return error;}e=s.a[--s.top];couteendl;return ok;}int main(){sqstack s;initstack(s);int n,x,e1;coutn=?endl;cinn;for(int i=0;in;i++){ cinx;if(x!=-1 )push(s,x);else pop(s,e1); }return 0;}============(3)假设以i和o分别表示入栈和出栈操作。

数据结构与算法分析c语言描述中文答案

数据结构与算法分析c语言描述中文答案

数据结构与算法分析c语言描述中文答案【篇一:数据结构(c语言版)课后习题答案完整版】选择题:ccbdca6.试分析下面各程序段的时间复杂度。

(1)o(1)(2)o(m*n)(3)o(n2)(4)o(log3n)(5)因为x++共执行了n-1+n-2+??+1= n(n-1)/2,所以执行时间为o(n2)(6)o(n)第2章线性表1.选择题babadbcabdcddac 2.算法设计题(6)设计一个算法,通过一趟遍历在单链表中确定值最大的结点。

elemtype max (linklist l ){if(l-next==null) return null;pmax=l-next; //假定第一个结点中数据具有最大值 p=l-next-next; while(p != null ){//如果下一个结点存在if(p-data pmax-data) pmax=p;p=p-next; }return pmax-data;(7)设计一个算法,通过遍历一趟,将链表中所有结点的链接方向逆转,仍利用原表的存储空间。

void inverse(linklist l) { // 逆置带头结点的单链表 l p=l-next; l-next=null; while ( p) {q=p-next; // q指向*p的后继p-next=l-next;l-next=p; // *p插入在头结点之后p = q; }}(10)已知长度为n的线性表a采用顺序存储结构,请写一时间复杂度为o(n)、空间复杂度为o(1)的算法,该算法删除线性表中所有值为item的数据元素。

[题目分析] 在顺序存储的线性表上删除元素,通常要涉及到一系列元素的移动(删第i个元素,第i+1至第n个元素要依次前移)。

本题要求删除线性表中所有值为item的数据元素,并未要求元素间的相对位置不变。

因此可以考虑设头尾两个指针(i=1,j=n),从两端向中间移动,凡遇到值item的数据元素时,直接将右端元素左移至值为item的数据元素位置。

算法与数据结构C语言习题参考答案6-9章

算法与数据结构C语言习题参考答案6-9章

1. 现在有一个已排序的字典,请改写二分法检索算法,使之当排序码key在字典中重复出现时算法能找出第一个key出现的元素下标(用*position来保存)。

保持算法时间代价为O(log n)。

【答】思路一般的二分法检索算法只要找出关键码key在字典中的一个下标。

在比较的过程中,一旦发现相等,记录下当前下标mid就符合要求。

程序如下:数据结构字典采用6.1.4节中的顺序表示法。

typedef int KeyType;typedef int DataType;二分法检索算法int binarySearch(SeqDictionary * pdic, KeyType key, int * position) {int low, mid, high;low = 0;high = pdic->n - 1;while (low <= high){mid = (low + high) / 2;if (pdic->element[mid].key = = key) {*position = mid;return TRUE;}elseif (pdic->element[mid].key > key)high = mid - 1;elselow = mid + 1;}*position = low;return FALSE;}改写后的算法想要找出关键码key在字典中第一次出现的下标。

在比较中,如果遇到相等(key与pdic->element[mid].key相等),则需要分情形讨论。

(1)如果当前下标mid等于0,或者key与pdic->element[mid-1].key不等,那么mid 一定是key第一次出现的下标,返回mid即可。

(2)如果情形(1)不成立,那么mid一定大于等于key第一次出现的下标,需要在low 和mid-1之间继续进行搜索,找出key第一次出现的下标。

数据结构c语言版课后习题答案完整版

数据结构c语言版课后习题答案完整版

数据结构c语言版课后习题答案完整版Document serial number【KKGB-LBS98YT-BS8CB-BSUT-BST108】第1章绪论5.选择题:CCBDCA6.试分析下面各程序段的时间复杂度。

(1)O(1)(2)O(m*n)(3)O(n2)n)(4)O(log3(5)因为x++共执行了n-1+n-2+……+1= n(n-1)/2,所以执行时间为O(n2)(6)O(n)第2章线性表1.选择题babadbcabdcddac2.算法设计题(6)设计一个算法,通过一趟遍历在单链表中确定值最大的结点。

ElemType Max (LinkList L ){if(L->next==NULL) return NULL;pmax=L->next; 法设计题(2)回文是指正读反读均相同的字符序列,如“abba”和“abdba”均是回文,但“good”不是回文。

试写一个算法判定给定的字符向量是否为回文。

(提示:将一半字符入栈)根据提示,算法可设计为:合应用题(1)已知模式串t=‘abcaabbabcab’写出用KMP法求得的每个字符对应的next和nextval函数值。

-1到9,列下标从1到11,从首地址S开始连续存放主存储器中,主存储器字长为16位。

求:①存放该数组所需多少单元②存放数组第4列所有元素至少需多少单元③数组按行存放时,元素A[7,4]的起始地址是多少④ 数组按列存放时,元素A[4,7]的起始地址是多少每个元素32个二进制位,主存字长16位,故每个元素占2个字长,行下标可平移至1到11。

(1)242 (2)22 (3)s+182 (4)s+142(4)请将香蕉banana 用工具 H( )—Head( ),T( )—Tail( )从L 中取出。

L=(apple,(orange,(strawberry,(banana)),peach),pear)H (H (T (H (T (H (T (L )))))))(5)写一个算法统计在输入字符串中各个不同字符出现的频度并将结果存入文件(字符串中的合法字符为A-Z 这26个字母和0-9这10个数字)。

数据结构c语言版第三版习题解答

数据结构c语言版第三版习题解答

数据结构c语言版第三版习题解答数据结构是计算机科学中非常重要的一门学科,它研究如何在计算机中存储和组织数据,以便有效地进行检索和操作。

数据结构的知识对于编写高效的程序和解决复杂的问题至关重要。

在学习和理解数据结构的过程中,解决习题是一种非常有效的方法。

本文将为读者提供《数据结构C语言版(第三版)》习题的解答。

1. 第一章:绪论第一章主要介绍了数据结构的基本概念和内容,包括算法和数据结构的概念、抽象数据类型(ADT)以及算法的评价等。

习题解答中,我们可以通过分析和讨论的方式对这些概念进行加深理解。

2. 第二章:算法分析第二章主要介绍了算法的基本概念和分析方法,包括时间复杂度和空间复杂度的计算方法。

习题解答中,我们可以通过具体的算法实例来计算其时间和空间复杂度,加深对算法分析的理解。

3. 第三章:线性表第三章主要介绍了线性表的概念和实现,包括顺序表和链表两种实现方式。

习题解答中,我们可以通过编写代码实现线性表的基本操作,并分析其时间和空间复杂度。

4. 第四章:栈和队列第四章主要介绍了栈和队列的概念和实现,包括顺序栈、链栈、顺序队列和链队列四种实现方式。

习题解答中,我们可以通过编写代码实现栈和队列的基本操作,并分析其时间和空间复杂度。

5. 第五章:串第五章主要介绍了串的概念和实现,包括顺序串和链串两种实现方式。

习题解答中,我们可以通过编写代码实现串的基本操作,并分析其时间和空间复杂度。

6. 第六章:树第六章主要介绍了树的概念和实现,包括二叉树、哈夫曼树和赫夫曼编码等内容。

习题解答中,我们可以通过编写代码实现树的基本操作,并分析其时间和空间复杂度。

7. 第七章:图第七章主要介绍了图的基本概念和实现,包括图的表示方法和图的遍历算法等。

习题解答中,我们可以通过编写代码实现图的基本操作,并分析其时间和空间复杂度。

8. 第八章:查找第八章主要介绍了查找算法的基本概念和实现,包括顺序查找、二分查找、哈希查找等内容。

数据结构(C语言版)习题及答案第二章

数据结构(C语言版)习题及答案第二章

数据结构(C语⾔版)习题及答案第⼆章习题2.1选择题1、线性表的顺序存储结构是⼀种(A)的存储结构,线性表的链式存储结构是⼀种(B)的存储结构。

A、随机存取B、顺序存取C、索引存取D、散列存取2、对于⼀个线性,既要求能够进⾏较快的插⼊和删除,⼜要求存储结构能够反映数据元素之间的逻辑关系,则应该选择(B)。

A、顺序存储⽅式B、链式存储⽅式C、散列存储⽅式D、索引存储⽅式3、已知,L是⼀个不带头结点的单链表,p指向其中的⼀个结点,选择合适的语句实现在p结点的后⾯插⼊s结点的操作(B)。

A、p->next=s ; s->next=p->next ;B、s->next=p->next ; p->next=s ;C、p->next=s ; s->next=p ;D、s->next=p ; p->next=s ;4、单链表中各结点之间的地址( C D)。

A、必须连续B、部分地址必须连续C、不⼀定连续D、连续与否都可以5、在⼀个长度为n的顺序表中向第i个元素(0A、n-iB、n-i+1C、n-i-1D、i2.2填空题1、顺序存储的长度为n的线性表,在任何位置上插⼊和删除操作的时间复杂度基本上都⼀样。

插⼊⼀个元素⼤约移动表中的(n/2)个元素,删除⼀个元素时⼤约移动表中的((n-1)/2)个元素。

2、在线性表的顺序存储⽅式中,元素之间的逻辑关系是通过(物理顺序)来体现的;在链式存储⽅式,元素之间的逻辑关系是通过(指针)体现的。

3、对于⼀个长度为n的单链表,在已知的p结点后⾯插⼊⼀个新结点的时间复杂度为(o(1)),在p结点之前插⼊⼀个新结点的时间复杂度为(o(n)),在给定值为e的结点之后插⼊⼀个新结点的时间复杂度为(o(n))。

4、在双向链表中,每个结点包含两个指针域,⼀个指向(前驱)结点,另⼀个指向(后继)结点。

5、对于循环链表来讲,逐个访问各个结点的结束判断条件是(设P为指向结点的指针,L为链表的头指针,则p->next= =L)。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Data Structures and Algorithm习题答案Preface ii1Data Structures and Algorithms 12Mathematical Preliminaries 53Algorithm Analysis 174Lists, Stacks, and Queues 235Binary Trees 326General Trees 407Internal Sorting 468File Processing and External Sorting54 9Searching 5810Indexing 6411Graphs 6912Lists and Arrays Revisited 7613Advanced Tree Structures 82iii Contents14Analysis Techniques 88 15Limits 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. In a 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 intended answer, rather than usable programs.1 Data 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.This 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. ”This exercise asks the student to expand on their concept of an integer representation.A good answer is described by Project , where a singly-linked list is suggested. The most straightforward implementation stores each digit in its own list node, with digits stored in reverse order. Addition and multiplication are implemented by what amounts to grade-school arithmetic. For addition, simply march down in parallel through the two lists representing the 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 digit by an integer. Exponentiation can be done either by repeated multiplication(not really p ractical) or by the traditi onal O (log n) -time algorithm based onthe binary representation of the exponent. Discovering this faster algorithm will be beyond the reach of most students, so should not be required.A sample ADT for character strings might look as follows (with the normal interpretation of the function names assumed).Chap. 1 Data Structures and AlgorithmsSomeIn C++, this is 1 for s1<s2; 0 for s1=s2;int strcmp(String s1, String s2)One' s compliment stores the binary rep resentation of positive numbers, andstores 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 oneis added (for reasons of efficiency in implementation).hardware This representation is the physical implementation of an ADT defined by the normalarithmetic operations, declarations, and other support given by the programming language for integers.An 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 Another implementationis a hash table whose search key is a concatenation of the matrix coordinates.Every 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 'thave a sufficiently clear definition. Some problems, such as the halting problem, are non-computable. For some problems, such as one typically studied by artificial intelligen ce researchers, we simply don 't know a solution.We must assume that by “algorithm ” we mean something composed of steps are of 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, thenit can be expressed in C++, since all (sufficiently general) computer programming languages compute the same set of functions.The 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.The 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 insert and 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 typical user. For an insert, delete, or exact match query, a few seconds is satisfactory. If the database 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.Students 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).The 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 AlgorithmsThe first part is easy with the hint, but the second part is rather difficult to do without a 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')' ) {= 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] == '(')(i);if (S[i] == ')') {if ()) return i;();}}if ()) return -1; else return ();}Answers to this question are discussed in Section .This is somewhat different from writing sorting algorithms for a computer, since person 's“working space” is typically limited, as is their ability manipulatethe pieces of paper. Nonetheless, many of the common sorting algorithms have their analogs to solutions for this problem. Most typical answers will sort, variations on mergesort, and variations on binsort.Answers to this question are discussed in Chapter 8.to physically be insertion2Mathematical Preliminaries(a)Not reflexive if the set has any members. One could argue it is symmetric, antisymmetric, and transitive, since no element violate any of the rules.(b)Not reflexive (for any female). Not symmetric (consider a brother and sister). Not antisymmetric (consider two brothers). Transitive (for any 3 brothers).(c)Not reflexive. Not symmetric, and is antisymmetric. Not transitive (only goes one level). (b) Not reflexive (for nearly all numbers). Symmetric since a + b = b+ a,so not antisymmetric. Transitive, but vacuously so (there can be no distinct a, b,and c where aRb and 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.In 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 and even sets. It is reflexive (x+ x is even for any integer x), symmetric (since x+ y= y+ x) and transitive (since you are always adding two odd or even numbers for anysatisfactory 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 xx>0. It is symmetric sincexy -=yx ' .It is tran sitive si nee any two members of the give n 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,=0. It is symmetric since if=xthen=.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.A 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 a is 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 a is older than b, then bcannot be older than a) and transitive (since if a is older than b and bis older than c, a is 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).A total ordering can be viewed as a permuation of the elements. Since there aren!permuations of n elements, there must be n!total orderings.This 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);This proposed ADT is inspired by the list ADT of Chapter 4. Note that while it is similiar to the operations proposed for Question , the behaviour is somewhat different.void clear();void insert(int);void remove(int);void sizeof();bool isEmpty();long ifact(int n) {The iterative version requires careful examination to understand what it does, or to have confidence that it works as claimed.(b)Fibr is so much slower than Fibi because Fibr re-computes the bulk of the series twice to get the two values to add. What is much worse, the recursive calls to compute the subexpressions also re-compute the bulk of the series, and do so recursively. The result is an exponential explosion. In contrast, Fibicomputes each value in the series exactly once, and so its running time is proportional to n.void GenTOH(int n, POLE goal, POLE t1, POLE t2,POLE* curr) { if (curr[n] == goal) Put others on t1.GenTOH(n-1, t1, goal, t2, curr);move(t2, goal);GenTOH(n-1, goal, t1, t2, curr); 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 Preliminaries void 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); The idea is the print out the elements at the indicated bitpositions within the set. If we do this for values in the range 0 to 2n1, 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;}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 n prime numbers together. The value C +1is not divisible byany of the n prime numbers. C+1is a prime number larger than Pn, a contradiction. Thus, we conclude that there is nolargest prime number. .Note: 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 thatp2=,qwhere pand qhave no common factors (that is, the fraction p/q is in lowestterms). By squaring both sides and doing some simple algebraic manipulation, we get 2p2=2q222q= pSince p2 must be even, p must be even. Thus,222q=4(p)222q=2(p)2This implies that q2 is also even. Thus, p and qare both even, which contradicts the requirement that pand qhave no common factors. Thus, 2must be irrational. .The leftmost summation sums the integers from 1 to n. The second summation merely reverses this order, summing the numbers from n1+1=ndown to nn+1=1. The third summation has a variable substitution ofi, with a corresponding substitution in the summation bounds. Thus, it is also the summation of n 0=nto n (n1)=1.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.2(n1)3 +3(n1)2 +(n1)i2 =6i=1(c) Induction Step.i2 i2 +n2i=1 i=12(n1)3 +3(n 1)2 +(n1)+n 62n3 .6n2 +6n2+3n2 .6n+3+n1 2+n62n3 +3n2 +n6Thus, the theorem is proved by mathematical induction.Proof:(a)Base case.For n=1, 1/2=1.1/2=1/2. Thus, the formula is correct for the base case.(b)Induction Hypothesis.112i=1Chap. 2 Mathematical Preliminaries(c)Induction Step.111=+i in222i=1 i=111=1.+n221=1.n2Thus, the theorem is proved by mathematical induction. .Proof:(a) Base case. For n=0, 20 =21 .1=1. Thus, the formula is correct for the base case. (b) Induction Hypothesis.2i=2n1.i=0(c)Induction Step.2i=2i+2ni=0 i=0n=2n1+2n+1 .1=2.Thus, the theorem is proved by mathematical induction. .The closed form solution is 3n+, which I deduced by noting that 3F (n).2n+1 .3F(n)=2F(n)=3. Now, to verify that this is correct, use mathematical induction as follows. For the base case, F (1)=3= .The induction hypothesis is that =(3n3)/2.i=1So,3i=3i+3ni=1 i=13n3n= +32n+1 .332Thus, the theorem is proved by mathematical induction.11 nTheorem (2i)=n2 +n.i=1(a)Proof: We know from Example that the sum of the first noddnumbers is ith even number is simply one greater than the ithodd 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:2i=(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.2i=( 2i)+2n i=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=1Proof:52Base case. For n=1,Fib(1) = 1 < 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 Induction Hypothesis, Fib(n.1)<(5) and Fib(n.2)<(5)33 55Fib(n) < () +()3355 5<() +() 33322 Chap. 2 Mathematical Preliminaries 85= ()3355<()2()33n53Thus, the theorem is proved by mathematical induction.Proof:12(1+1)23 =(a) Base case. For n=1, 1=1. Thus, the formula is correct4for the base case.(b) Induction Hypothesis.(n1) n i3 = .4i=0(c)Induction Step. n2(n1)n2i33=+n4i=02n4 .2n3 +n3+n4n4 +2n3 +n24n2(n2 +2n+2)2n2(n+1)4Thus, the theorem is proved by mathematical induction.(a)Proof: By contradiction. Assume that the theorem is false. Then, each pigeonhole contains at most 1 pigeon. Since there are n holes, there is room for only n pigeons. This contradicts the fact that a total of n +1pigeons are within the n holes. Thus, the theorem must be correct. .(b)Proof:i.Base case.For one pigeon hole and two pigeons, there must be two pigeons in the hole.ii.Induction Hypothesis. For n pigeons in n1holes, some hole must contain at least two pigeons.13iii.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 other hole 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). If it contains more than one pigeon, then it fits the requirements of the theorem directly.(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(n1)+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 . Base case: T(n1)=1=1(1+1)/2.Induction hypothesis: T(n1)=(n1)(n)/2.Induction step:T(n)= T(n1)+n=(n1)(n)/2+n= n(n+1)/2.Thus, the theorem is proved by mathematical induction.If we expand the recurrence, we getT(n)=2T(n1)+1=2(2T(n2)+1)+1)=4T(n2+2+1.Expanding again yieldsT(n)=8T(n3)+4+2+1.From this, we can deduce a pattern and hypothesize that the recurrence is equivalent to nT(n)= .12i=2n1.i=0To prove this formula is in fact the proper closed form solution, we use mathematical induction.Base case: T(1)=21 .1=1.14Chap. 2 Mathematical PreliminariesInduction hypothesis: T(n1)= .1.Induction step:T(n)=2T(n1)+1 = 2 .1) + 1=2n1.Thus, as proved by mathematical induction, this formula is indeed the correct closed form solution for the recurrence.(a) The probability is for each choice.(b)The average number of “1” bits is n/2, since each position has probability of being “1.”(c)The leftmost “1” will be the leftmost bit (call it position 0) with probability ; in position 1 with probability , and so on. The numberof positions we must examine is 1 in the case where the leftmost “1” is in position 0; 2 when it is in position 1, and so on. Thus, the expected cost is the value of the summationni2ii=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.)There 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 volume slightly less than 50 liters; a 160 pound person has a volume slightly less than 20 gallons.(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) i mages, which is 3 x640 x480, or just less than 1 Mbyte per image. The full database requires some 30-35 CDs.(b)Since we needed 30-35 CDs before, compressing by a factor of 10 is not 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 single 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 miles and 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 X Rainfall 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 in ches/year ~.1 in ches/day ~.000002 miles/day (2 X .Thus, the flow is about 2 cubic miles/day.Note that the student should NOT be providing answers that look like they were 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 savings would be 1/4% each payment over the life of the mortgage. The monthly charge 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 slightly over 4 years to save $1000. If the money had been invested, then in 5 years the investment would be worth about $1300 (at 5would be close to 5 1/2years.Disk drive seek time is somewhere around 10 milliseconds or a little lessin 2000. RAM memory requires around 50 nano sec onds — much less tha na microsecond. Given that there are about 30 million seconds in a year, a machine capable of executing at 100 MIPS would execute about 3 billion billion (3 .1018) instructions in a year.Typical 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 of 50 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.A typical page has around 400 words (best way to derive this is to estimate the 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 PreliminariesAn 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.Well over 100,000, depending on what you wish to classify as a city or town. The real question is what technique the student uses.(a)The time required is 1 minute for the first mile, then 60/59 minutes for the second mile, and so on until the last mile requires 60/1=60 minutes. 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.3Algorithm AnalysisNote that nis a positive integer.5nlog nis most efficient for n=1.2nis most efficie nt whe n 2 <nW4.10nis most efficient for all n>5. 20nand 2nare never more efficient than the other choices.Both log3 nand log2 nwill have value 0 when n=1.Otherwise, 2 is the most efficient expression for all n>1. 2/32 3n2 log3nlog2 nn20n4nn!.(a)n+6 inputs (an additive amount, independent of n).(b)8ninputs (a multiplicative factor).(c)64ninputs.100n.10n.VAbout (actually, 3 100n).n+6.(a)These questions are quite hard. If f(n)=2n= x, then f(2n)=22n2(2n)2 = x.(b)The answer is 2(nlog2 3). Extending from part (a), we need some way to make the growth rate even higher. In particular, we seek some way to log2 3 =make the exponent go up by a factor of 3. Note that, if f(n)= n)=2log2 3log2 3 =3xy, then f(2nn. So, we combine this observation with part (a) to get the desired answer.First, we need to find constants cand nosuch that 1 wex1 for n>n0.This is true for any positive value c<1 and any positive value of n0 (since nplays no role in the equation).Next, we need to find constants cand n0 such that 1 wcxnfor n>n0.This is true for, say, c=1 and n0 =1.1718Chap. 3 Algorithm AnalysisOther values for n0 and care possible than what is given here.(a)The upper bound is O(n) for n0 >0 and c= c1. The lower bound isQ (n) for nO >0 and c= c1.(b)The upper bound is O(n3) for n0 >c3 and c= c2 +1. The lowerbound is Q (n3) for n0 >c3 and c= c2.(c)The upper bound is O(nlog n) for n0 >c5 and c= c4 +1. The lower bound is Q (nlog n) for n0 >c5 and c= c4.(d)The upper bound is O(2n) for n0 >c7100 and c= c6 +lower bound is Q (2n) for n0 >c7100 and c= c6. (100 is used forconvenience to insure that 2n>n6)(a) f(n)= O (g( n)) since log n2 = 2 log n.(b)f(n) is in Q (g(n)) since ncgrows faster than log ncfor any c.(c)f(n) is in Q (g(n)). Dividing both sides by log n, we see that log n grows faster than 1. (d)f(n) is in Q(g(n)). If we take both f(n) and g(n) as exponents for 2,2we get 2non one side and 2log2 n=(2log n)2 = n2 on the other, and ngrows slower than 2n(e)f(n) is in Q (g(n)). Dividing both sides by log nand throwing away the low order terms, we see that ngrows faster than 1.(f)。

相关文档
最新文档