数据结构(英文版)课后习题答案
数据结构课程 课后习题答案

数据结构课程课后习题答案一、栈和队列1. 栈是一种后进先出(Last-In-First-Out, LIFO)的数据结构,只能在栈顶进行插入和删除操作。
请写出判断一个字符串是否为回文的算法,并给出代码实现。
算法思路:- 将字符串中的字符依次入栈。
- 依次出栈和字符串中的字符进行比较,若全部相等,则为回文;否则,不是回文。
代码实现:```pythonclass Stack:def __init__(self):self.stack = []def is_empty(self):return len(self.stack) == 0def push(self, item):self.stack.append(item)def pop(self):if not self.is_empty():return self.stack.pop()else:return Nonedef peek(self):if not self.is_empty():return self.stack[-1]else:return Nonedef is_palindrome(string):stack = Stack()for char in string:stack.push(char)for char in string:if char != stack.pop():return Falsereturn True# 测试print(is_palindrome("level")) # Trueprint(is_palindrome("hello")) # False```2. 队列是一种先进先出(First-In-First-Out, FIFO)的数据结构,请写出使用两个栈来实现一个队列的算法,并给出代码实现。
算法思路:- 使用一个栈stack1来对入队元素进行存储。
- 使用另一个栈stack2来对出队元素进行存储。
《数据结构》课后习题答案(第2版)

《数据结构》课后习题答案(第2版)数据结构课后习题答案(第2版)第一章:基本概念1. 什么是数据结构?数据结构是指数据元素之间的关系,以及相应的操作。
它研究如何组织、存储和管理数据,以及如何进行高效的数据操作。
2. 数据结构的分类有哪些?数据结构可以分为线性结构和非线性结构。
线性结构包括数组、链表、栈和队列;非线性结构包括树和图。
3. 什么是算法?算法是解决特定问题的一系列有序步骤。
它描述了如何输入数据、处理数据,并产生期望的输出结果。
4. 算法的特性有哪些?算法具有确定性、有限性、输入、输出和可行性这五个特性。
5. 数据结构和算法之间的关系是什么?数据结构是算法的基础,算法操作的对象是数据结构。
第二章:线性表1. 顺序表的两种实现方式是什么?顺序表可以通过静态分配或动态分配的方式实现。
静态分配使用数组,动态分配使用指针和动态内存分配。
2. 单链表的特点是什么?单链表由节点组成,每个节点包含数据和一个指向下一个节点的指针。
它的插入和删除操作效率高,但是查找效率较低。
3. 循环链表和双向链表分别是什么?循环链表是一种特殊的单链表,在尾节点的指针指向头节点。
双向链表每个节点都有一个指向前一个节点和后一个节点的指针。
4. 链表和顺序表的区别是什么?链表的插入和删除操作效率更高,但是查找操作效率较低;顺序表的插入和删除操作效率较低,但是查找操作效率较高。
第三章:栈和队列1. 栈是什么?栈是一种特殊的线性表,只能在表的一端进行插入和删除操作。
后进先出(LIFO)是栈的特点。
2. 队列是什么?队列是一种特殊的线性表,只能在表的一端进行插入操作,在另一端进行删除操作。
先进先出(FIFO)是队列的特点。
3. 栈和队列的应用有哪些?栈和队列在计算机科学中有广泛的应用,例如浏览器的前进后退功能使用了栈,操作系统的进程调度使用了队列。
4. 栈和队列有哪些实现方式?栈和队列可以使用数组或链表来实现,还有更为复杂的如双端队列和优先队列。
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
Mark Allen Weiss 数据结构与算法分析 课后习题答案11

Chapter11:Amortized Analysis11.1When the number of trees after the insertions is more than the number before.11.2Although each insertion takes roughly log N ,and each DeleteMin takes2log N actualtime,our accounting system is charging these particular operations as2for the insertion and3log N −2for the DeleteMin. The total time is still the same;this is an accounting gimmick.If the number of insertions and DeleteMins are roughly equivalent,then it really is just a gimmick and not very meaningful;the bound has more significance if,for instance,there are N insertions and O (N / log N )DeleteMins (in which case,the total time is linear).11.3Insert the sequence N ,N +1,N −1,N +2,N −2,N +3,...,1,2N into an initiallyempty skew heap.The right path has N nodes,so any operation could takeΩ(N )time. 11.5We implement DecreaseKey(X,H)as follows:If lowering the value of X creates a heaporder violation,then cut X from its parent,which creates a new skew heap H 1with the new value of X as a root,and also makes the old skew heap H smaller.This operation might also increase the potential of H ,but only by at most log N .We now merge H andH 1.The total amortized time of the Merge is O (log N ),so the total time of theDecreaseKey operation is O (log N ).11.8For the zig −zig case,the actual cost is2,and the potential change isR f ( X )+ R f ( P )+ R f ( G )− R i ( X )− R i ( P )− R i ( G ).This gives an amortized time bound ofAT zig −zig =2+ R f ( X )+ R f ( P )+ R f ( G )− R i ( X )− R i ( P )− R i ( G )Since R f ( X )= R i ( G ),this reduces to=2+ R f ( P )+ R f ( G )− R i ( X )− R i ( P )Also,R f ( X )> R f ( P )and R i ( X )< R i ( P ),soAT zig −zig <2+ R f ( X )+ R f ( G )−2R i ( X )Since S i ( X )+ S f ( G )< S f ( X ),it follows that R i ( X )+ R f ( G )<2R f ( X )−2.ThusAT zig −zig <3R f ( X )−3R i ( X )11.9(a)Choose W (i )=1/ N for each item.Then for any access of node X ,R f ( X )=0,andR i ( X )≥−log N ,so the amortized access for each item is at most3log N +1,and the net potential drop over the sequence is at most N log N ,giving a bound of O (M log N + M + N log N ),as claimed.(b)Assign a weight of q i /M to items i .Then R f ( X )=0,R i ( X )≥log(q i /M ),so theamortized cost of accessing item i is at most3log(M /q i )+1,and the theorem follows immediately.11.10(a)To merge two splay trees T 1and T 2,we access each node in the smaller tree andinsert it into the larger tree.Each time a node is accessed,it joins a tree that is at leasttwice as large;thus a node can be inserted log N times.This tells us that in any sequence of N −1merges,there are at most N log N inserts,giving a time bound of O (N log2N ).This presumes that we keep track of the tree sizes.Philosophically,this is ugly since it defeats the purpose of self-adjustment.(b)Port and Moffet[6]suggest the following algorithm:If T 2is the smaller tree,insert itsroot into T 1.Then recursively merge the left subtrees of T 1and T 2,and recursively merge their right subtrees.This algorithm is not analyzed;a variant in which the median of T 2is splayed to the rootfirst is with a claim of O (N log N )for the sequence of merges.11.11The potential function is c times the number of insertions since the last rehashing step,where c is a constant.For an insertion that doesn’t require rehashing,the actual time is 1,and the potential increases by c ,for a cost of1+ c .If an insertion causes a table to be rehashed from size S to2S ,then the actual cost is 1+ dS ,where dS represents the cost of initializing the new table and copying the old table back.A table that is rehashed when it reaches size S was last rehashed at size S / 2, so S / 2insertions had taken place prior to the rehash,and the initial potential was cS / 2.The new potential is0,so the potential change is−cS / 2,giving an amortized bound of(d − c / 2)S +1.We choose c =2d ,and obtain an O (1)amortized bound in both cases.11.12We show that the amortized number of node splits is1per insertion.The potential func-tion is the number of three-child nodes in T .If the actual number of nodes splits for an insertion is s ,then the change in the potential function is at most1− s ,because each split converts a three-child node to two two-child nodes,but the parent of the last node split gains a third child(unless it is the root).Thus an insertion costs1node split,amor-tized.An N node tree has N units of potential that might be converted to actual time,so the total cost is O (M + N ).(If we start from an initially empty tree,then the bound is O (M ).)11.13(a)This problem is similar to Exercise3.22.Thefirst four operations are easy to imple-ment by placing two stacks,S L and S R ,next to each other(with bottoms touching).We can implement thefifth operation by using two more stacks,M L and M R (which hold minimums).If both S L and S R never empty,then the operations can be implemented as follows:Push(X,D):push X onto S L ;if X is smaller than or equal to the top of M L ,push X onto M L as well.Inject(X,D):same operation as Push ,except use S R and M R .Pop(D):pop S L ;if the popped item is equal to the top of M L ,then pop M L as well.Eject(D):same operation as Pop ,except use S R and M R .FindMin(D):return the minimum of the top of M L and M R .These operations don’t work if either S L or S R is empty.If a Pop or E j ect is attempted on an empty stack,then we clear M L and M R .We then redistribute the elements so that half are in S L and the rest in S R ,and adjust M L and M R to reflect what the state would be.We can then perform the Pop or E j ect in the normal fashion.Fig. 11.1shows a transfor-mation.Define the potential function to be the absolute value of the number of elements in S L minus the number of elements in S R .Any operation that doesn’t empty S L or S R can3,1,4,6,5,9,2,61,2,63,1,4,65,9,2,6 1,4,65,2S L S R M L RL S RM L M R Fig.11.1.increase the potential by only1;since the actual time for these operations is constant,so is the amortized time.To complete the proof,we show that the cost of a reorganization is O (1)amortized time. Without loss of generality,if S R is empty,then the actual cost of the reorganization is | S L | units.The potential before the reorganization is | S L | ;afterward,it is at most1. Thus the potential change is1− | S L | ,and the amortized bound follows.。
JAVA数据结构习题及解答(英)

QuestionsThese questions are intended as a self-test for readers.Answers to the questions may be found in Appendix C.1.In many data structures you can________a single record,_________it,and_______it.2.Rearranging the contents of a data structure into a certain order is called_________.30CHAPTER1Overview3.In a database,a field isa.a specific data item.b.a specific object.c.part of a record.d.part of an algorithm.4.The field used when searching for a particular record is the______________.5.In object-oriented programming,an objecta.is a class.b.may contain data and methods.c.is a program.d.may contain classes.6.A classa.is a blueprint for many objects.b.represents a specific real-world object.c.will hold specific values in its fields.d.specifies the type of a method.7.In Java,a class specificationa.creates objects.b.requires the keyword new.c.creates references.d.none of the above.8.When an object wants to do something,it uses a________.9.In Java,accessing an object’s methods requires the_____operator.10.In Java,boolean and byte are_____________.(There are no experiments or programming projects for Chapter1.)Questions31Chapter1,OverviewAnswers to Questions1.insert,search for,delete2.sorting3.c4.search key5.b6.a7.d8.method9.dot10.data typesQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.Inserting an item into an unordered arraya.takes time proportional to the size of the array.b.requires multiple comparisons.c.requires shifting other items to make room.d.takes the same time no matter how many items there are.2.True or False:When you delete an item from an unordered array,in most cases you shift other items to fill in the gap.3.In an unordered array,allowing duplicatesa.increases times for all operations.b.increases search times in some situations.c.always increases insertion times.d.sometimes decreases insertion times.4.True or False:In an unordered array,it’s generally faster to find out an item is not in the array than to find out it is.5.Creating an array in Java requires using the keyword________.6.If class A is going to use class B for something,thena.class A’s methods should be easy to understand.b.it’s preferable if class B communicates with the program’s user.c.the more complex operations should be placed in class A.d.the more work that class B can do,the better.7.When class A is using class B for something,the methods and fields class A can access in class B are called class B’s__________.74CHAPTER2Arrays8.Ordered arrays,compared with unordered arrays,area.much quicker at deletion.b.quicker at insertion.c.quicker to create.d.quicker at searching.9.A logarithm is the inverse of_____________.10.The base10logarithm of1,000is_____.11.The maximum number of elements that must be examined to complete a binary search in an array of200elements isa.200.b.8.c.1.d.13.12.The base2logarithm of64is______.13.True or False:The base2logarithm of100is2.14.Big O notation tellsa.how the speed of an algorithm relates to the number of items.b.the running time of an algorithm for a given size data structure.c.the running time of an algorithm for a given number of items.d.how the size of a data structure relates to the number of items.15.O(1)means a process operates in_________time.16.Either variables of primitive types or_________can be placed in an array. Chapter2,ArraysAnswers to Questions1.d2.True3.b4.False5.new6.d740APPENDIX C Answers to Questions7.interface8.d9.raising to a power10.311.812.613.False14.a15.constant16.objectsuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.puter sorting algorithms are more limited than humans in thata.humans are better at inventing new algorithms.puters can handle only a fixed amount of data.c.humans know what to sort,whereas computers need to be told.puters can compare only two things at a time.2.The two basic operations in simple sorting are_________items and_________ them(or sometimes_________them).3.True or False:The bubble sort always ends up comparing every item with every other item.4.The bubble sort algorithm alternates betweenparing and swapping.b.moving and copying.c.moving and comparing.d.copying and comparing.5.True or False:If there are N items,the bubble sort makes exactly N*N comparisons.Questions1096.In the selection sort,a.the largest keys accumulate on the left(low indices).b.a minimum key is repeatedly discovered.c.a number of items must be shifted to insert each item in its correctlysorted position.d.the sorted items accumulate on the right.7.True or False:If,in a particular sorting situation,swaps take much longer than comparisons,the selection sort is about twice as fast as the bubble sort.8.A copy is________times as fast as a swap.9.What is the invariant in the selection sort?10.In the insertion sort,the“marked player”described in the text corresponds to which variable in the insertSort.java program?a.inb.outc.tempd.a[out]11.In the insertion sort,“partially sorted”means thata.some items are already sorted,but they may need to be moved.b.most items are in their final sorted positions,but a few still need to be sorted.c.only some of the items are sorted.d.group items are sorted among themselves,but items outside the groupmay need to be inserted in it.12.Shifting a group of items left or right requires repeated__________.13.In the insertion sort,after an item is inserted in the partially sorted group,it willa.never be moved again.b.never be shifted to the left.c.often be moved out of this group.d.find that its group is steadily shrinking.110CHAPTER3Simple Sorting14.The invariant in the insertion sort is that________.15.Stability might refer toa.items with secondary keys being excluded from a sort.b.keeping cities sorted by increasing population within each state,in a sortby state.c.keeping the same first names matched with the same last names.d.items keeping the same order of primary keys without regard to secondary keys.Chapter3,Simple SortingAnswers to Questions1.dparing and swapping(or copying)3.False4.a5.False6.b7.False8.three9.Items with indices less than or equal to outer are sorted.10.c11.d12.copies13.b14.Items with indices less than outer are partially sorted.15.buestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.Suppose you push10,20,30,and40onto the stack.Then you pop three items. Which one is left on the stack?2.Which of the following is true?a.The pop operation on a stack is considerably simpler than the remove operation on a queue.b.The contents of a queue can wrap around,while those of a stack cannot.c.The top of a stack corresponds to the front of a queue.d.In both the stack and the queue,items removed in sequence are takenfrom increasingly high index cells in the array.3.What do LIFO and FIFO mean?4.True or False:A stack or a queue often serves as the underlying mechanism on which an ADT array is based.5.Assume an array is numbered with index0on the left.A queue representing a line of movie-goers,with the first to arrive numbered1,has the ticket window on the right.Thena.there is no numerical correspondence between the index numbers andthe movie-goer numbers.b.the array index numbers and the movie-goer numbers increase inopposite left-right directions.c.the array index numbers correspond numerically to the locations in theline of movie-goers.d.the movie-goers and the items in the array move in the same direction.6.As other items are inserted and removed,does a particular item in a queue move along the array from lower to higher indices,or higher to lower?7.Suppose you insert15,25,35,and45into a queue.Then you remove three items.Which one is left?8.True or False:Pushing and popping items on a stack and inserting and removing items in a queue all take O(N)time.174CHAPTER4Stacks and Queues9.A queue might be used to holda.the items to be sorted in an insertion sort.b.reports of a variety of imminent attacks on the star ship Enterprise.c.keystrokes made by a computer user writing a letter.d.symbols in an algebraic expression being evaluated.10.Inserting an item into a typical priority queue takes what big O time?11.The term priority in a priority queue means thata.the highest priority items are inserted first.b.the programmer must prioritize access to the underlying array.c.the underlying array is sorted by the priority of the items.d.the lowest priority items are deleted first.12.True or False:At least one of the methods in the priorityQ.java program (Listing4.6)uses a linear search.13.One difference between a priority queue and an ordered array is thata.the lowest-priority item cannot be extracted easily from the array as it can from the priority queue.b.the array must be ordered while the priority queue need not be.c.the highest priority item can be extracted easily from the priority queue but not from the array.d.All of the above.14.Suppose you based a priority queue class on the OrdArray class in the orderedArray.java program(Listing2.4)in Chapter2,“Arrays.”This will buy you binary search capability.If you wanted the best performance for your priority queue,would you need to modify the OrdArray class?15.A priority queue might be used to holda.passengers to be picked up by a taxi from different parts of the city.b.keystrokes made at a computer keyboard.c.squares on a chessboard in a game program.d.planets in a solar system simulation.Chapter4,Stacks and QueuesAnswers to Questions1.102.bst-In-First-Out;and First-In-First-Out4.False.It’s the other way around.5.b6.It doesn’t move at all.7.458.False.They take O(1)time.9.c10.O(N)11.c12.True13.b14.Yes,you would need a method to find the minimum value.15.aQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.Questions2451.Which of the following is not true?A reference to a class objecta.can be used to access public methods in the object.b.has a size dependant on its class.c.has the data type of the class.d.does not hold the object itself.2.Access to the links in a linked list is usually through the_________link.3.When you create a reference to a link in a linked list,ita.must refer to the first link.b.must refer to the link pointed to by current.c.must refer to the link pointed to by next.d.can refer to any link you want.4.How many references must you change to insert a link in the middle of a singly linked list?5.How many references must you change to insert a link at the end of a singly linked list?6.In the insertFirst()method in the linkList.java program(Listing5.1),the statement newLink.next=first;means thata.the next new link to be inserted will refer to first.b.first will refer to the new link.c.the next field of the new link will refer to the old first link.d.newLink.next will refer to the new first link in the list.7.Assuming current points to the next-to-last link in a singly linked list,what statement will delete the last link from the list?8.When all references to a link are changed to refer to something else,what happens to the link?9.A double-ended lista.can be accessed from either end.b.is a different name for a doubly linked list.c.has pointers running both forward and backward between links.d.has its first link connected to its last link.246CHAPTER5Linked Lists10.A special case often occurs for insertion and deletion routines when a list is ________.11.Assuming a copy takes longer than a comparison,is it faster to delete an item with a certain key from a linked list or from an unsorted array?12.How many times would you need to traverse a singly linked list to delete the item with the largest key?13.Of the lists discussed in this chapter,which one would be best for implementing a queue?14.Which of the following is not true?Iterators would be useful if you wanted toa.do an insertion sort on a linked list.b.insert a new link at the beginning of a list.c.swap two links at arbitrary locations.d.delete all links with a certain key value.15.Which do you think would be a better choice to implement a stack:a singly linked list or an array?Chapter5,Linked ListsAnswers to Questions1.b2.first3.d4.25.16.c7.current.next=null;8.Java’s garbage collection process destroys it.Chapter5,Linked Lists7419.a10.empty11.a linked list12.once,if the links include a previous reference13.a double-ended list14.bually,the list.They both do push()and pop()in O(1)time,but the list uses memory more efficiently.QuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.If the user enters10in the triangle.java program(Listing6.1),what is the maximum number of“copies”of the triangle()method(actually just copies of its argument)that exist at any one time?2.Where are the copies of the argument,mentioned in question1,stored?a.in a variable in the triangle()methodb.in a field of the TriangleApp classc.in a variable of the getString()methodd.on a stack3.Assume the user enters10as in question1.What is the value of n when the triangle()method first returns a value other than1?4.Assume the same situation as in question1.What is the value of n when the triangle()method is about to return to main()?5.True or false:In the triangle()method,the return values are stored on thestack.6.In the anagram.java program(Listing6.2),at a certain depth of recursion,a version of the doAnagram()method is working with the string“led”.When this method calls a new version of itself,what letters will the new version be working with?7.We’ve seen that recursion can take the place of a loop,as in the loop-oriented orderedArray.java program(Listing2.4)and the recursive binarySearch.java program(Listing6.3).Which of the following is not true?a.Both programs divide the range repeatedly in half.b.If the key is not found,the loop version returns because the rangebounds cross,but the recursive version occurs because it reaches thebottom recursion level.c.If the key is found,the loop version returns from the entire method, whereas the recursive version returns from only one level of recursion.d.In the recursive version the range to be searched must be specified in the arguments,while in the loop version it need not be.310CHAPTER6Recursion8.In the recFind()method in the binarySearch.java program(Listing6.3),what takes the place of the loop in the non-recursive version?a.the recFind()methodb.arguments to recFind()c.recursive calls to recFind()d.the call from main()to recFind()9.The binarySearch.java program is an example of the_________approach to solving a problem.10.What gets smaller as you make repeated recursive calls in the redFind() method?11.What becomes smaller with repeated recursive calls in the towers.java program (Listing6.4)?12.The algorithm in the towers.java program involvesa.“trees”that are data storage devices.b.secretly putting small disks under large disks.c.changing which columns are the source and destination.d.moving one small disk and then a stack of larger disks.13.Which is not true about the merge()method in the merge.java program(Listing6.5)?a.Its algorithm can handle arrays of different sizes.b.It must search the target array to find where to put the next item.c.It is not recursive.d.It continuously takes the smallest item irrespective of what array it’s in.14.The disadvantage of mergesort is thata.it is not recursive.b.it uses more memory.c.although faster than the insertion sort,it is much slower than quicksort.d.it is complicated to implement.15.Besides a loop,a___________can often be used instead of recursion. Chapter6,RecursionAnswers to Questions1.102.d3.24.105.false6.“ed”7.b8.c9.divide-and-conquer10.the range of cells to search11.the number of disks to transfer12.c13.b14.b15.stackQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.The Shellsort works bya.partitioning the array.b.swapping adjacent elements.c.dealing with widely separated elements.d.starting with the normal insertion sort.2.If an array has100elements,then Knuth’s algorithm would start with an interval of________.Questions3613.To transform the insertion sort into the Shellsort,which of the following do you not do?a.Substitute h for1.b.Insert an algorithm for creating gaps of decreasing width.c.Enclose the normal insertion sort in a loop.d.Change the direction of the indices in the inner loop.4.True or false:A good interval sequence for the Shellsort is created by repeatedly dividing the array size in half.5.Fill in the big O values:The speed of the Shellsort is more than_______but less than________.6.Partitioning isa.putting all elements larger than a certain value on one end of the array.b.dividing an array in half.c.partially sorting parts of an array.d.sorting each half of an array separately.7.When partitioning,each array element is compared to the_______.8.In partitioning,if an array element is equal to the answer to question7,a.it is passed over.b.it is passed over or not,depending on the other array element.c.it is placed in the pivot position.d.it is swapped.9.True or false:In quicksort,the pivot can be an arbitrary element of the array.10.Assuming larger keys on the right,the partition isa.the element between the left and right subarrays.b.the key value of the element between the left and right subarrays.c.the left element in the right subarray.d.the key value of the left element in the right subarray.11.Quicksort involves partitioning the original array and then_________.362CHAPTER7Advanced Sorting12.After a partition in a simple version of quicksort,the pivot may beed to find the median of the array.b.exchanged with an element of the right subarray.ed as the starting point of the next partition.d.discarded.13.Median-of-three partitioning is a way of choosing the_______.14.In quicksort,for an array of N elements,the partitionIt()method will examine each element approximately______times.15.True or false:You can speed up quicksort if you stop partitioning when the partition size is5and finish by using a different sort.Chapter7,Advanced SortingAnswers to Questions1.c2.403.d4.false5.O(N*logN),O(N2)6.a7.pivot8.d9.true10.c11.partitioning the resulting subarrays12.b13.pivot14.log2N15.trueQuestionsThese questions are intended as a self-test for readers.Answers may be found inAppendix C.1.Insertion and deletion in a tree require what big O time?2.A binary tree is a search tree ifa.every non-leaf node has children whose key values are less than(or equalto)the parent.b.every left child has a key less than the parent and every right child has akey greater than(or equal to)the parent.c.in the path from the root to every leaf node,the key of each node isgreater than(or equal to)the key of its parent.d.a node can have a maximum of two children.3.True or False:Not all trees are binary trees.4.In a complete binary tree with20nodes,and the root considered to be at level 0,how many nodes are there at level4?5.A subtree of a binary tree always hasa.a root that is a child of the main tree’s root.b.a root unconnected to the main tree’s root.c.fewer nodes than the main tree.d.a sibling with the same number of nodes.6.In the Java code for a tree,the______and the_______are generally separate classes.Questions4237.Finding a node in a binary search tree involves going from node to node, askinga.how big the node’s key is in relation to the search key.b.how big the node’s key is compared to its right or left children.c.what leaf node we want to reach.d.what level we are on.8.An unbalanced tree is onea.in which most of the keys have values greater than the average.b.whose behavior is unpredictable.c.in which the root or some other node has many more left children thanright children,or vice versa.d.that is shaped like an umbrella.9.Inserting a node starts with the same steps as_______a node.10.Suppose a node A has a successor node S.Then S must have a key that is larger than_____but smaller than or equal to_______.11.In a binary tree used to represent a mathematical expression,which of the following is not true?a.Both children of an operator node must be operands.b.Following a postorder traversal,no parentheses need to be added.c.Following an inorder traversal,parentheses must be added.d.In pre-order traversal a node is visited before either of its children.12.If a tree is represented by an array,the right child of a node at index n has an index of_______.13.True or False:Deleting a node with one child from a binary search tree involves finding that node’s successor.14.A Huffman tree is typically used to_______text.15.Which of the following is not true about a Huffman tree?a.The most frequently used characters always appear near the top of the tree.b.Normally,decoding a message involves repeatedly following a path fromthe root to a leaf.424CHAPTER8Binary Treesc.In coding a character you typically start at a leaf and work upward.d.The tree can be generated by removal and insertion operations on apriority queue.Chapter8,Binary TreesAnswers to Questions1.O(logN)2.b3.True4.55.c6.node,tree7.a8.cChapter8,Binary Trees7439.finding10.A,A’s left-child descendents11.d12.2*n+113.Falsepress15.cQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.A2-3-4tree is so named because a node can havea.three children and four data items.b.two,three,or four children.c.two parents,three children,and four items.d.two parents,three items,and four children.2.A2-3-4tree is superior to a binary search tree in that it is________.3.Imagine a parent node with data items25,50,and75.If one of its child nodes had items with values60and70,it would be the child numbered__________.4.True or False:Data items are located exclusively in leaf nodes.514CHAPTER102-3-4Trees and External Storage5.Which of the following is not true each time a node is split?a.Exactly one new node is created.b.Exactly one new data item is added to the tree.c.One data item moves from the split node to its parent.d.One data item moves from the split node to its new sibling.6.A2-3-4tree increases its number of levels when________.7.Searching a2-3-4tree does not involvea.splitting nodes on the way down if necessary.b.picking the appropriate child to go to,based on data items in a node.c.ending up at a leaf node if the search key is not found.d.examining at least one data item in any node visited.8.After a non-root node of a2-3-4tree is split,does its new right child contain the item previously numbered0,1,or2?9.A4-node split in a2-3-4tree is equivalent to a_______in a red-black tree.10.Which of the following statements about a node-splitting operation in a2-3 tree(not a2-3-4tree)is not true?a.The parent of a split node must also be split if it is full.b.The smallest item in the node being split always stays in that node.c.When the parent is split,child2must always be disconnected from itsold parent and connected to the new parent.d.The splitting process starts at a leaf and works upward.11.What is the big O efficiency of a2-3tree?12.In accessing data on a disk drive,a.inserting data is slow but finding the place to write data is fast.b.moving data to make room for more data is fast because so many items can be accessed at once.c.deleting data is unusually fast.d.finding the place to write data is comparatively slow but a lot of data can be written quickly.13.In a B-tree each node contains_______data items.Questions51514.True or False:Node splits in a B-tree have similarities to node splits in a2-3 tree.15.In external storage,indexing means keeping a file ofa.keys and their corresponding blocks.b.records and their corresponding blocks.c.keys and their corresponding records.st names and their corresponding keys.Chapter9,Red-Black TreesAnswers to Questions1.in order(or inverse order)2.b3.False4.d5.b6.rotations,changing the colors of nodes7.red8.a9.left child,right child10.d11.a node,its two children12.b13.True14.a15.TrueQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.574CHAPTER11Hash Tablesing big O notation,say how long it takes(ideally)to find an item in a hash table.2.A__________transforms a range of key values into a range of index values.3.Open addressing refers toa.keeping many of the cells in the array unoccupied.b.keeping an open mind about which address to use.c.probing at cell x+1,x+2,and so on until an empty cell is found.d.looking for another location in the array when the one you want is occupied.ing the next available position after an unsuccessful probe is called_____________.5.What are the first five step sizes in quadratic probing?6.Secondary clustering occurs becausea.many keys hash to the same location.b.the sequence of step lengths is always the same.c.too many items with the same key are inserted.d.the hash function is not perfect.7.Separate chaining involves the use of a_____________at each location.8.A reasonable load factor in separate chaining is________.9.True or False:A possible hash function for strings involves multiplying each character by an ever-increasing power.10.The best technique when the amount of data is not well known isa.linear probing.b.quadratic probing.c.double hashing.d.separate chaining.11.If digit folding is used in a hash function,the number of digits in each group should reflect_____________.12.True or False:In linear probing an unsuccessful search takes longer than a successful search.Questions57513.In separate chaining the time to insert a new itema.increases linearly with the load factor.b.is proportional to the number of items in the table.c.is proportional to the number of lists.d.is proportional to the percentage of full cells in the array.14.True or False:In external hashing,it’s important that the records don’t become full.15.In external hashing,all records with keys that hash to the same value are located in___________.Chapter11,Hash TablesAnswers to Questions1.O(1)2.hash function3.d4.linear probing5.1,4,9,16,256.b7.linked listChapter11,Hash Tables7458.1.09.True10.d11.the array size12.False13.a14.False15.the same blockQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.What does the term complete mean when applied to binary trees?a.All the necessary data has been inserted.b.All the rows are filled with nodes,except possibly the bottom one.c.All existing nodes contain data.d.The node arrangement satisfies the heap condition.2.What does the term weakly ordered mean when applied to heaps?3.A node is always removed from the__________.4.To“trickle up”a node in a descending heap meansa.to repeatedly exchange it with its parent until it’s larger than its parent.b.to repeatedly exchange it with its child until it’s larger than its child.c.to repeatedly exchange it with its child until it’s smaller than its child.d.to repeatedly exchange it with its parent until it’s smaller than its parent.5.A heap can be represented by an array because a heap。
《数据结构与算法分析》(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。
数据结构课后习题答案1--7
数据结构课后习题答案1--7题目1:请你设计一个栈数据结构,使其具备以下功能:可以在O(1)的时间复杂度内获取栈的最小元素。
解答1:要实现在O(1)的时间复杂度内获取栈的最小元素,可以使用两个栈来实现。
一个栈用来保存原始数据,另一个栈用来保存当前栈的最小元素。
具体实现如下:1. 初始化两个栈:stack和min_stack,其中stack用于保存所有元素,min_stack用于保存当前栈中的最小元素。
2. 插入元素时,先将元素插入stack中,然后判断插入的元素是否比min_stack的栈顶元素小,如果是,则将元素也插入到min_stack中;如果不是,则将min_stack的栈顶元素再次插入到min_stack中。
3. 删除元素时,分别从stack和min_stack中弹出栈顶元素。
这样,min_stack的栈顶元素始终是stack中的最小元素。
题目2:请你设计一个队列数据结构,使其具备以下功能:可以在O(1)的时间复杂度内获取队列的最大元素。
解答2:要实现在O(1)的时间复杂度内获取队列的最大元素,可以使用两个队列来实现。
一个队列用来保存原始数据,另一个队列用来保存当前队列的最大元素。
具体实现如下:1. 初始化两个队列:queue和max_queue,其中queue用于保存所有元素,max_queue用于保存当前队列中的最大元素。
2. 插入元素时,先将元素插入queue中,然后判断插入的元素是否比max_queue的队尾元素大,如果是,则将元素也插入到max_queue的队尾;如果不是,则将max_queue中所有比插入元素小的元素都弹出,再将插入元素插入到max_queue的队尾。
3. 删除元素时,分别从queue和max_queue中弹出队头元素。
这样,max_queue的队头元素始终是queue中的最大元素。
题目3:请你设计一个栈数据结构,使其除了具有常规的入栈和出栈功能外,还具备以下功能:能够在O(1)的时间复杂度内获取栈中的最大元素。
数据结构样卷1(英文)答案by郑
重庆大学 数据结构 课程 样卷1开课学院: 计算机学院 课程号: 18001035 考试日期:考试方式:考试时间: 120 分钟一. Single choice1. In data structure, we logically divide the data into__C_____。
A. Dynamic structure and the static structureB. Sequence structure and chain structureC. Linear structure and non-linear structureD. The internal structure and external structure2. For a singly linked list with a head node pointer, The condition todetermine whether it is empty is__B_____。
A. head == NULLB. head->next == NULLC. head->next == headD. head != NULL3. In order to prevent Pseudo-overflow, we should___D____。
书上好像没有Pseudo-overflow 的内容,这道题我是猜的A. Define enough storage spaceB. Dequeue as soon as possibleC. Enqueue as soon as possibleD. Use circular queue4. Assuming data K1! =K2, After processed by a hash function H, it isH(K1)=H(K2), then the K1, K2 are known as the H’s __A_____。
数据库英文版第六版课后答案(32)
数据库英⽂版第六版课后答案(32)C H A P T E R11Indexing and HashingThis chapter covers indexing techniques ranging from the most basic one tohighly specialized ones.Due to the extensive use of indices in database systems,this chapter constitutes an important part of a database course.A class that has already had a course on data-structures would likely be famil-iar with hashing and perhaps even B+-trees.However,this chapter is necessaryreading even for those students since data structures courses typically cover in-dexing in main memory.Although the concepts carry over to database accessmethods,the details(e.g.,block-sized nodes),will be new to such students.The sections on B-trees(Sections11.4.5)and bitmap indexing(Section11.9) may be omitted if desired. Exercises11.15When is it preferable to use a dense index rather than a sparse index?Explain your answer.Answer:It is preferable to use a dense index instead of a sparse indexwhen the?le is not sorted on the indexed?eld(such as when the indexis a secondary index)or when the index?le is small compared to the sizeof memory.11.16What is the difference between a clustering index and a secondary index?Answer:The clustering index is on the?eld which speci?es the sequentialorder of the?le.There can be only one clustering index while there canbe many secondary indices.11.17For each B+-tree of Practice Exercise11.3,show the steps involved in thefollowing queries:a.Find records with a search-key value of11.b.Find records with a search-key value between7and17,inclusive.Answer:With the structure provided by the solution to Practice Exer-cise11.3a:9798Chapter11Indexing and Hashinga.Find records with a value of11i.Search the?rst level index;follow the?rst pointer.ii.Search next level;follow the third pointer.iii.Search leaf node;follow?rst pointer to records with key value11.b.Find records with value between7and17(inclusive)i.Search top index;follow?rst pointer.ii.Search next level;follow second pointer.iii.Search third level;follow second pointer to records with keyvalue7,and after accessing them,return to leaf node.iv.Follow fourth pointer to next leaf block in the chain.v.Follow?rst pointer to records with key value11,then return.vi.Follow second pointer to records with with key value17.With the structure provided by the solution to Practice Exercise12.3b:a.Find records with a value of11i.Search top level;follow second pointer.ii.Search next level;follow second pointer to records with key value11.b.Find records with value between7and17(inclusive)i.Search top level;follow second pointer.ii.Search next level;follow?rst pointer to records with key value7,then return.iii.Follow second pointer to records with key value11,then return.iv.Follow third pointer to records with key value17.With the structure provided by the solution to Practice Exercise12.3c:a.Find records with a value of11i.Search top level;follow second pointer.ii.Search next level;follow?rst pointer to records with key value11.b.Find records with value between7and17(inclusive)i.Search top level;follow?rst pointer.ii.Search next level;follow fourth pointer to records with key value7,then return.iii.Follow eighth pointer to next leaf block in chain.iv.Follow?rst pointer to records with key value11,then return.v.Follow second pointer to records with key value17.Exercises99 11.18The solution presented in Section11.3.4to deal with nonunique searchkeys added an extra attribute to the search key.What effect could this change have on the height of the B+-tree?Answer:The resultant B-tree’s extended search key is unique.This results in more number of nodes.A single node(which points to mutiple records with the same key)in the original tree may correspond to multiple nodes in the result tree.Dependingon how they are organized the height of the tree may increase;it might be more than that of the original tree.11.19Explain the distinction between closed and open hashing.Discuss therelative merits of each technique in database applications.Answer:Open hashing may place keys with the same hash function value in different buckets.Closed hashing always places such keys together in the same bucket.Thus in this case,different buckets can be of different sizes,though the implementation may be by linking together?xed size buckets using over?ow chains.Deletion is dif?cult with open hashing as all the buckets may have to inspected before we can ascertain that a key value has been deleted,whereas in closed hashing only that bucket whose address is obtained by hashing the key value need be inspected.Deletions are more common in databases and hence closed hashing is more appropriate for them.For a small,static set of data lookups may be more ef?cient using open hashing.The symbol table of a compiler would be a good example.11.20What are the causes of bucket over?ow in a hash?le organization?Whatcan be done to reduce the occurrence of bucket over?ows?Answer:The causes of bucket over?ow are:-a.Our estimate of the number of records that the relation will have wastoo low,and hence the number of buckets allotted was not suf?cient.b.Skew in the distribution of records to buckets.This may happeneither because there are many records with the same search keyvalue,or because the the hash function chosen did not have thedesirable properties of uniformity and randomness.To reduce the occurrence of over?ows,we can:-a.Choose the hash function more carefully,and make better estimatesof the relation size.b.If the estimated size of the relation is n r and number of records perblock is f r,allocate(n r/f r)?(1+d)buckets instead of(n r/f r)buckets.Here d is a fudge factor,typically around0.2.Some space is wasted:About20percent of the space in the buckets will be empty.But thebene?t is that some of the skew is handled and the probability ofover?ow is reduced.11.21Why is a hash structure not the best choice for a search key on whichrange queries are likely?100Chapter11Indexing and HashingAnswer:A range query cannot be answered ef?ciently using a hashindex,we will have to read all the buckets.This is because key valuesin the range do not occupy consecutive locations in the buckets,they aredistributed uniformly and randomly throughout all the buckets.11.22Suppose there is a relation r(A,B,C),with a B+-tree index with searchkey(A,B).a.What is the worst-case cost of?nding records satisfying10using this index,in terms of the number of records retrieved n1and the height h of the tree?b.What is the worst-case cost of?nding records satisfying1050∧5n2that satisfy this selection,as well as n1and h de?ned above?c.Under what conditions on n1and n2would the index be an ef?cient way of?nding records satisfying10Answer:a.What is the worst case cost of?nding records satisfying10using this index,in terms of the number of records retrieved n1and the height h of the tree?This query does not correspond to a range query on the search key as the condition on the?rst attribute if the search key is a comparison condition.It looks up records which have the value of A between10and50.However,each record is likely to be in a different block, because of the ordering of records in the?le,leading to many I/O operation.In the worst case,for each record,it needs to traverse the whole tree(cost is h),so the total cost is n1?h.b.What is the worst case cost of?nding records satisfying1050∧5n2that satisfy this selection,as well as n1and h de?ned above.This query can be answered by using an ordered index on the search key(A,B).For each value of A this is between10and50,the system located records with B value between5and10.However,each record could is likely to be in a different disk block.This amounts to exe-cuting the query based on the condition on A,this costs n1?h.Then these records are checked to see if the condition on B is satis?ed.So, the total cost in the worst case is n1?h.c.Under what conditions on n1and n2would the index be an ef?cient way of?nding records satisfying10n1records satisfy the?rst condition and n2records satisfy the second condition.When both the conditions are queried,n1records are output in the?rst stage.So,in the case where n1=n2,no extra records are output in the furst stage.Otherwise,the records whichExercises101 dont satisfy the second condition are also output with an additionalcost of h each(worst case).11.23Suppose you have to create a B+-tree index on a large number of names,where the maximum size of a name may be quite large(say40characters) and the average name is itselflarge(say10characters).Explain how pre?x compression can be used to maximize the average fanout of nonleaf nodes. Answer:There arises2problems in the given scenario.The?rst prob-lem is names can be of variable length.The second problem is names can be long(maximum is40characters),leading to a low fanout and a correspondingly increased tree height.With variable-length search keys, different nodes can have different fanouts even if they are full.The fanout of nodes can be increased bu using a technique called pre?x compres-sion.With pre?x compression,the entire search key value is not stored at internal nodes.Only a pre?x of each search key which is suf?ceint to distinguish between the key values in the subtrees that it seperates.The full name can be stored in the leaf nodes,this way we dont lose any information and also maximize the average fanout of internal nodes. 11.24Suppose a relation is stored in a B+-tree?le organization.Suppose sec-ondary indices stored record identi?ers that are pointers to records on disk.a.What would be the effect on the secondary indices if a node splithappens in the?le organization?b.What would be the cost of updating all affected records in a sec-ondary index?c.How does using the search key of the?le organization as a logicalrecord identi?er solve this problem?d.What is the extra cost due to the use of such logical record identi?ers?Answer:a.When a leaf page is split in a B+-tree?le organization,a numberof records are moved to a new page.In such cases,all secondaryindices that store pointers to the relocated records would have tobe updated,even though the values in the records may not havechanged.b.Each leaf page may contain a fairly large number of records,andeach of them may be in different locations on each secondary index.Thus,a leaf-page split may require tens or even hundreds of I/Ooperations to update all affected secondary indices,making it a veryexpensive operation.c.One solution is to store the values of the primary-index search keyattributes in secondary indices,in place of pointers to the indexed102Chapter11Indexing and Hashingrecords.Relocation of records because of leaf-page splits then doesnot require any update on any secondary index.d.Locating a record using the secondary index now requires two steps:First we use the secondary index to?nd the primary index search-key values,and then we use the primary index to?nd the corre-sponding records.This approach reduces the cost of index updatedue to?le reorganization,although it increases the cost of accesingdata using a secondary index.11.25Show how to compute existence bitmaps from other bitmaps.Make sure that your technique works even in the presence of null values,by using a bitmap for the value null.Answer:The existence bitmap for a relation can be calculated by takingthe union(logical-or)of all the bitmaps on that attribute,including thebitmap for value null.11.26How does data encryption affect index schemes?In particular,how might it affect schemes that attempt to store data in sorted order?Answer:Note that indices must operate on the encrypted data orsomeone could gain access to the index to interpret the data.Otherwise,the index would have to be restricted so that only certain users could access it.To keep the data in sorted order,the index scheme would haveto decrypt the data at each level in a tree.Note that hash systems wouldnot be affected.11.27Our description of static hashing assumes that a large contiguous stretch of disk blocks can be allocated to a static hash table.Suppose you can allocate only C contiguous blocks.Suggest how to implement the hash table,if it can be much larger than C blocks.Access to a block should stillbe ef?cient.Answer:A separate list/table as shown below can be created.Starting address of?rst set of C blocksCStarting address of next set of C blocks2Cand so onDesired block address=Starting adress(from the table depending onthe block number)+blocksize*(blocknumber%C)For each set of C blocks,a single entry is added to the table.In thiscase,locating a block requires2steps:First we use the block number tond the actual block address,and then we can access the desired block.。
《数据结构》教材课后习题+答案
《数据结构》教材课后习题+答案数据结构第一章介绍数据结构是计算机科学中重要的概念,它涉及到组织和存储数据的方法和技术。
数据结构的选择对于算法的效率有着重要的影响。
本教材为读者提供了丰富的课后习题,以帮助读者巩固所学知识并提高解决问题的能力。
下面是一些选定的习题及其答案,供读者参考。
第二章线性表习题一:给定一个顺序表L,编写一个算法,实现将其中元素逆置的功能。
答案一:算法思路:1. 初始化两个指针i和j,分别指向线性表L的首尾两个元素2. 对于L中的每一个元素,通过交换i和j所指向的元素,将元素逆置3. 当i>=j时,停止逆置算法实现:```pythondef reverse_list(L):i, j = 0, len(L)-1while i < j:L[i], L[j] = L[j], L[i]i += 1j -= 1```习题二:给定两个线性表A和B,编写一个算法,将线性表B中的元素按顺序插入到线性表A中。
答案二:算法思路:1. 遍历线性表B中的每一个元素2. 将B中的元素依次插入到A的末尾算法实现:```pythondef merge_lists(A, B):for element in B:A.append(element)```第三章栈和队列习题一:编写一个算法,判断一个表达式中的括号是否匹配。
表达式中的括号包括小括号"()"、中括号"[]"和大括号"{}"。
答案一:算法思路:1. 遍历表达式中的每一个字符2. 当遇到左括号时,将其推入栈中3. 当遇到右括号时,判断栈顶元素是否与其匹配4. 当遇到其他字符时,继续遍历下一个字符5. 最后判断栈是否为空,若为空则表示括号匹配算法实现:```pythondef is_matching(expression):stack = []for char in expression:if char in "([{":stack.append(char)elif char in ")]}":if not stack:return Falseelif (char == ")" and stack[-1] == "(") or (char == "]" and stack[-1] == "[") or (char == "}" and stack[-1] == "{"):stack.pop()else:return Falsereturn not stack```习题二:利用两个栈实现一个队列。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
ProgrammingPrinciples 1THE GAME OF LIFEExercisesDetermine by hand calculation what will happen to each of the configurations shown in Figure overthe course of five generations. [Suggestion: Set up the Life configuration on a checkerboard. Use onecolor of checkers for living cells in the current generation and a second color to mark those that will beborn or die in the next generation.]Answer(a)Figure remains stable.(b)(c)(d)Figure is stable.12 Chapter 1 _ Programming Principles(e)(f)Figure repeats itself.(g)(h)(i)Figure repeats itself.(j)(k)(l)Figure repeats itself.Section _ Programming Style 3PROGRAMMING STYLEExercisesE1. What classes would you define in implementing the following projects What methods would your classespossess(a) A program to store telephone numbers.Answer The program could use classes called Phone_book and Person. The methods for a Phone_bookobject would include look_up_name, add_person, remove_person. The methods for a Personobject would include Look_up_number. Additional methods to initialize and print objects ofboth classes would also be useful.(b) A program to play Monopoly.Answer The program could use classes called Game_board, Property, Bank, Player, and Dice. In additionto initialization and printing methods for all classes, the following methods would be useful. Theclass Game_board needs methods next_card and operate_jail. The class Property needs methodschange_owner, look_up_owner, rent, build, mortgage, and unmortgage. The class Bank needsmethods pay and collect. The class Player needs methods roll_dice, move_location, buy_propertyand pay_rent. The class Dice needs a method roll.(c) A program to play tic-tac-toe.Answer The program could use classes called Game_board and Square. The classes need initializationand printing methods. The class Game_board would also need methods make_move andis_game_over. The class Square would need methods is_occupied, occupied_by, and occupy.(d) A program to model the build up of queues of cars waiting at a busy intersection with a traffic light.Answer The program could use classes Car, Traffic_light, and Queue. The classes would all need initializationand printing methods. The class Traffic_light would need additional methods change_statusand status. The class Queue would need additional methods add_car andremove_car.E2. Rewrite the following class definition, which is supposed to model a deck of playing cards, so that itconforms to our principles of style.class a { Y1 lists the cards. */ public:a( );void Shuffle( ); thing d( ); Given the declarationsint a[n][n], i, j;where n is a constant, determine what the following statement does, and rewrite the statement to accomplishthe same effect in a less tricky way.for (i = 0; i < n; i..)for (j = 0; j < n; j..)a[i][j] = ((i . 1)/(j . 1)) * ((j . 1)/(i . 1));Answer This statement initializes the array a with all 0’s except for 1’s down the main diagonal. A lesstricky way to accomplish this initialization is:for (i = 0; i < n; i..)for (j = 0; j < n; j..)if (i == j) a[i][j] = 1;else a[i][j] = 0;E4. Rewrite the following function so that it accomplishes the same result in a less tricky way.void does_something(int &first, int &second){first = second first;second = second first;first = second . first;}Answer The function interchanges the values of its parameters:void swap(int &first, int &second)/* Pre: The integers first and second have been initialized.Post: The values of first and second have been switched. */{int temp = first;first = second;second = temp;}E5. Determine what each of the following functions does. Rewrite each function with meaningful variablenames, with better format, and without unnecessary variables and statements. (a) int calculate(int apple, int orange){ int peach, lemon;peach = 0; lemon = 0; if (apple < orange)peach = orange; else if (orange <= apple)peach = apple; else { peach = 17;lemon = 19; }return(peach);}Answer The function calculate returns the larger of its two parameters.int larger(int a, int b)/* Pre: The integers a and b have been initialized.Post: The value of the larger of a and b is returned. */{if (a < b) return b;return a;}Section _ Programming Style 5(b) For this part assume the declaration typedef float vector[max];float figure (vector vector1){ int loop1, loop4; float loop2, loop3;loop1 = 0; loop2 = vector1[loop1]; loop3 = ;loop4 = loop1; for (loop4 = 0;loop4 < max; loop4..) { loop1 = loop1 . 1;loop2 = vector1[loop1 1];loop3 = loop2 . loop3; } loop1 = loop1 1;loop2 = loop1 . 1;return(loop2 = loop3/loop2); }Answer The function figure obtains the mean of an array of floating point numbers. float mean(vector v)/* Pre: The vector v contains max floating point values.Post: The mean of the values in v is returned. */{float total = ;for (int i = 0; i < max; i..)total += v[i];return total/((float) max);}(c) int question(int &a17, int &stuff){ int another, yetanother, stillonemore;another = yetanother; stillonemore = a17;yetanother = stuff; another = stillonemore;a17 = yetanother; stillonemore = yetanother;stuff = another; another = yetanother;yetanother = stuff; }Answer The function question interchanges the values of its parameters.void swap(int &first, int &second)/* Pre: The integers first and second have been initialized.Post: The values of first and second have been switched. */{int temp = first;first = second;second = temp;}(d) int mystery(int apple, int orange, int peach){ if (apple > orange) if (apple > peach) if(peach > orange) return(peach); else if (apple < orange)return(apple); else return(orange); else return(apple); elseif (peach > apple) if (peach > orange) return(orange); elsereturn(peach); else return(apple); }Answer The function mystery returns the middle value of its three parameters.6 Chapter 1 _ Programming Principlesint median(int a, int b, int c)/* Pre: None.Post: Returns the middle value of the three integers a, b, c. */{if (a > b)if (c > a) return a; The following statement is designed to check the relative sizes of three integers, which you may assumeto be different from each other:if (x < z) if (x < y) if (y < z) c = 1; else c = 2; elseif (y < z) c = 3; else c = 4; else if (x < y)if (x < z) c = 5; else c = 6; else if (y < z) c = 7; elseif (z < x) if (z < y) c = 8; else c = 9; else c = 10;(a) Rewrite this statement in a form that is easier to read.Answerif (x < z)if (x < y) Find those that can never occur, and eliminate the redundant checks. Answer The impossible cases are shown in the remarks for the preceding programsegment. After theirremoval we have:if (x < z)if (x < y) Answerif ((x < y) && (y < z)) c = 1;else if ((x < z) && (z < y)) c = 2;else if ((y < x) && (x < z)) c = 3;else if ((z < x) && (x < y)) c = 6;else if ((y < z) && (z < x)) c = 7;else c = 8;E7. The following C++ function calculates the cube root of a floating-point number (by the Newton approximation),using the fact that, if y is one approximation to the cube root of x, thenz . 2y . x=y23cube roots is a closer approximation.float function fcn(float stuff){ float april, tim, tiny, shadow, tom, tam, square; int flag;tim = stuff; tam = stuff; tiny = ;if (stuff != 0) do {shadow = tim . tim; square = tim * tim;tom = (shadow . stuff/square); april = tom/;if (april*april * april tam > tiny) if (april*april*april tam< tiny) flag = 1; else flag = 0; else flag = 0;if (flag == 0) tim = april; else tim = tam; } while (flag != 1);if (stuff == 0) return(stuff); else return(april); }(a) Rewrite this function with meaningful variable names, without the extra variables that contribute nothingto the understanding, with a better layout, and without the redundant and useless statements.Answer After some study it can be seen that both stuff and tam play the role of the quantity x in theformula, tim plays the role of y, and tom and april both play the role of z. The object tiny is asmall constant which serves as a tolerance to stop the loop. The variable shadow is nothing but2y and square is y2 . The complicated two-line if statement checks whether the absolute valuejz3 xj is less than the tolerance, and the boolean flag is used then only to terminatethe loop.Changing all these variables to their mathematical forms and eliminating the redundant onesgives:const double tolerance = ;double cube_root(double x) y . x/(y * y))/;y = z;} while (z * z * z x > tolerance || x z * z * z > tolerance);return z;}(b) Write a function for calculating the cube root of x directly from the mathematical formula, by startingwith the assignment y = x and then repeatingy = (2 * y . (x/(y * y)))/3until abs(y * y * y x) < .8 Chapter 1 _ Programming PrinciplesAnswer const double tolerance = ;double formula(double x) y . x/(y * y))/;} while (y * y * y x > tolerance || x y * y * y > tolerance);return y;}(c) Which of these tasks is easierAnswer It is often easier to write a program fromscratch than it is to decipher and rewrite a poorly writtenprogram.E8. The mean of a sequence of numbers is their sum divided by the count of numbers in the sequence. Thestatistics (population) variance of the sequence is the mean of the squares of all numbers in the sequence, minusthe square of the mean of the numbers in the sequence. The standard deviation is the square root of thevariance. Write a well-structured C++ function to calculate the standard deviation of a sequence of nfloating-point numbers, where n is a constant and the numbers are in an array indexed from 0 to n1,which is a parameter to the function. Use, then write, subsidiary functions to calculate the mean andvariance.Answer #include <>double variance(double v[], int n);double standard_deviation(double v[], int n) double mean(double v[], int n); double variance(double v[], int n)for (i = 0; i < n; i..)sum_squares += v[i] * v[i];temp = mean(v, n);return sum_squares/n temp * temp;}This function in turn requires another function to calculate the mean.double mean(double v[], int n)sum += v[i];return sum/n;}Section _ Programming Style 9E9. Design a program that will plot a given set of points on a graph. The input to the program will be a textfile, each line of which contains two numbers that are the x and y coordinates of a point to be plotted.The program will use a function to plot one such pair of coordinates. The details of the function involveplotting the specificmethod of plotting and cannot be written since they depend on the requirements of the plottingequipment, which we do not know. Before plotting the points the program needs to know the maximumand minimum values of x and y that appear in its input file. The program should therefore use anotherfunction bounds that will read the whole file and determine these four maxima and minima. Afterward,another function is used to draw and label the axes; then the file can be reset and the individual pointsplotted.(a) Write the main program, not including the functions.Answer #include <>#include ""#include ""#include ""int main(int argc, char *argv[]){ifstream file(argv[1]);if (file == 0) {cout << "Can not open input points file" << endl;cout << "Usage:\n\t plotter input_points " << endl;exit(1);}double xmax, xmin; Answer void bounds(ifstream &file, double &xmax, double&xmin,double &ymax, double &ymin)Answer void draw_axes(double xmax, double xmin,double ymax, double ymin)/* Pre: The parameters xmin, xmax, ymin, and xmax give bounds for the x and y co-ordinates.Post: Draws and labels axes according to the given bounds. */{}void plot(double x, double y)/* Pre: The parameters x and y give co-ordinates of a point.Post: The point is plotted to the ouput graph. */{}CODING, TESTING, AND FURTHER REFINEMENTExercisesE1. If you suspected that the Life program contained errors, where would be a good place to insert scaffoldinginto the main program What information should be printed outAnswer Since much of the program’s work is done in neighbor_count, a good place would be withinthe loops of the update method, just before the switch statement. The values of row, col, andneighbor_count could be printed.E2. Take your solution to Section , Exercise E9 (designing a program to plot a set of points), and indicategood places to insert scaffolding if needed.Answer Suitable places might be after draw_axes (printing its four parameters) and (with a very smalltest file to plot) after the call to plot (printing the coordinates of the point just plotted).E3. Find suitable black-box test data for each of the following:(a) A function that returns the largest of its three parameters, which are floating-point numbers.Answereasy values: .1; 2; 3., .2; 3; 1., .3; 2; 1..typical values: .0; 0:5;9:6., .1:3; 3:5; 0:4., .2:1;3:5;1:6..extreme values: .0; 0; 0., .0; 1; 1., .1; 0; 1., .0; 0; 1.(b) A function that returns the square root of a floating-point number.Answereasy values: 1, 4, 9, 16.typical values: , , .extreme value: .illegal values: , 9.Section _ Coding, Testing, and Further Refinement 11(c) A function that returns the least common multiple of its two parameters, which must be positive integers.(The least common multiple is the smallest integer that is a multiple of both parameters. Examples:The least common multiple of 4 and 6 is 12, of 3 and 9 is 9, and of 5 and 7 is 35.) Answereasy values: .3; 4., .4; 8., .7; 3..typical values: .7; 8., .189; 433., .1081; 1173..illegal values: .7;6., .0; 5., .0; 0., .1;1..(d) A function that sorts three integers, given as its parameters, into ascending order. Answereasy values: .5; 3; 2., .2; 3; 5., .3; 5; 2., .5; 2; 3., .1;2;3.extreme values: .1; 1; 1., .1; 2; 1., .1; 1; 2..typical values: .487;390; 20., .0; 589; 333..(e) A function that sorts an array a containing n integers indexed from 0 to n 1 into ascending order,where a and n are both parameters.Answer For the number n of entries to be sorted choose values such as 2, 3, 4 (easy values), 0, 1, maximumsize of a (extreme values), and 1 (illegal value). Test with all entries of a the same value, theentries already in ascending order, the entries in descending order, and the entries inrandomorder.E4. Find suitable glass-box test data for each of the following:(a) The statementif (a < b) if (c > d) x = 1; else if (c == d) x = 2;else x = 3; else if (a == b) x = 4; else if (c == d) x = 5;else x = 6;Answer Choose values for a and b, such as .1; 2., .2; 1., and .1; 1., so that each of a < b, a > b, and a ==b holds true. Choose three similar pairs of values forc and d, giving nine sets of test data.(b) The Life method neighbor_count(row, col).Answer Set row in turn to 1, maxrow, and any intermediate value, as well as 0 and maxrow . 1 (as illegalvalues). Choose col similarly. For each of the legal (row, col) pairs set up the Life object so thatthe number of living neighbors of (row, col) is each possible value between 0 and 8. Finally, makethe cell at (row, col) itself either living or dead. (This process gives 98 sets of test data, providedmaxrow and maxrow are each at least 3.)Programming ProjectsP1. Enter the Life program of this chapter on your computer and make sure that it works correctly.Answer The complete program is implemented in the life subdirectory for Chapter 1. #include "../../c/"#include ""#include "../../c/"#include ""int main() /*Pre: The user supplies an initial configuration of living cells.Post: The program prints a sequence of pictures showing the changes inthe configuration of living cells according to the rules forthe game of Life.Uses: The class Life and its methods initialize(), print(), andupdate(); the functions instructions(), user_says_yes().*/12 Chapter 1 _ Programming Principles{Life configuration;instructions();();();cout << "Continue viewing new generations " << endl;while (user_says_yes()) {();();cout << "Continue viewing new generations " << endl;}}const int maxrow = 20, maxcol = 60; int neighbor_count(int row, int col); };void Life::print()/*Pre: The Life object contains a configuration.Post: The configuration is written for the user.*/{int row, col;cout << "\nThe current Life configuration is:" <<endl;for (row = 1; row <= maxrow; row++) {for (col = 1; col <= maxcol; col++)if (grid[row][col] == 1) cout << '*';else cout << ' ';cout << endl;}cout << endl;}int Life::neighbor_count(int row, int col)/*Pre: The Life object contains a configuration, and the coordinatesrow and col define a cell inside its hedge.Post: The number of living neighbors of the specified cell is returned.*/{int i, j;int count = 0;for (i = row - 1; i <= row + 1; i++)for (j = col - 1; j <= col + 1; j++)count += grid[i][j]; count -= grid[row][col]; return count;}Section _ Coding, Testing, and Further Refinement 13void Life::update()/*Pre: The Life object contains a configuration.Post: The Life object contains the next generation of configuration. */{int row, col;int new_grid[maxrow + 2][maxcol + 2];for (row = 1; row <= maxrow; row++)for (col = 1; col <= maxcol; col++)switch (neighbor_count(row, col)) {case 2:new_grid[row][col] = grid[row][col]; break;case 3:new_grid[row][col] = 1; break;default:new_grid[row][col] = 0; }for (row = 1; row <= maxrow; row++)for (col = 1; col <= maxcol; col++)grid[row][col] = new_grid[row][col];}void Life::initialize()/*Pre: None.Post: The Life object contains a configuration specified by the user. */{int row, col;for (row = 0; row <= maxrow+1; row++)for (col = 0; col <= maxcol+1; col++)grid[row][col] = 0;cout << "List the coordinates for living cells." << endl;cout << "Terminate the list with the the special pair -1 -1" << endl;cin >> row >> col;while (row != -1 || col != -1) {if (row >= 1 && row <= maxrow)if (col >= 1 && col <= maxcol)grid[row][col] = 1;elsecout << "Column " << col << " is out of range." << endl;elsecout << "Row " << row << " is out of range." << endl;cin >> row >> col;}}void instructions()/*Pre: None.Post: Instructions for using the Life program have been printed.*/14 Chapter 1 _ Programming Principles{cout << "Welcome to Conway's game of Life." << endl;cout << "This game uses a grid of size "<< maxrow << " by " << maxcol << " in which" << endl;cout << "each cell can either be occupied by an organism or not." << endl;cout << "The occupied cells change from generation to generation" << endl;cout << "according to the number of neighboring cells which are alive."<< endl;}P2. Test the Life program with the examples shown in Figure .Answer See the solution to the exercise in Section .P3. Run the Life program with the initial configurations shown in Figure . Several of these go throughmany changes before reaching a configuration that remains the same or has predictable behavior.Answer This is a demonstration to be performed by computer.PROGRAM MAINTENANCEExercisesE1. Sometimes the user might wish to run the Life game on a grid smaller than 20_60.Determine how it ispossible to make maxrow and maxcol into variables that the user can set when the program is run. Tryto make as few changes in the program as possible.Answer The integers maxrow and maxcol should become data members of the class Life. The methodinitialize, must now ask for input of the two data members maxrow and maxcol. Upper boundsof 20 and 60 for these integers should be stored in new constants called maxrowbound andmaxcolbound. The amended file now takes the form.const int maxrowbound = 20, maxcolbound = 60;2][maxcolbound . 2];E2. One idea for speeding up the function Life :: neighbor_count(row, col) is to delete the hedge (the extrarows and columns that are always dead) from the arrays grid and new_grid. Then, when a cell is onthe boundary, neighbor_count will look at fewer than the eight neighboring cells, since some of theseare outside the bounds of the grid. To do this, the function will need to determine whether or not the cell(row, col) is on the boundary, but this can be done outside the nested loops, by determining, before theloops commence, the lower and upper bounds for the loops. If, for example, row is as small as allowed,then the lower bound for the row loop is row; otherwise, it is row 1. Determine, in terms of the size ofthe grid, approximately how many statements are executed by the original version of neighbor_countand by the new version. Are the changes proposed in this exercise worth making Section _ Program Maintenance 15Answer We need four if statements at the beginning of neighbor_count to determine whether (row, col)is on the boundary. This gives a total of 4 _ maxrow _ maxcol extra statements. If the cell is inthe first or last row or column, but not in a corner, then the nested loops would iterate 3 fewertimes. There are 8 such positions. With the cell in one of the 4 cornerpositions, the nested loops would iterate 5 fewer times. Hence the total number of statementssaved is4 _ maxrow _ maxcol . .2 _ maxrow . 2 _ maxcol 8..20:Thus this proposed change actually costs additional work, except for very small values of maxrowand maxcol.The modified function could be coded as follows.int Life :: neighbor_count(int row, int col)/* Pre: The Life object contains a configuration, and the coordinates row and col define a cellinside its hedge.Post: The number of living neighbors of the specified cell is returned. */{int i, j;int count = 0;int rowlow = row 1, rowhigh = row . 1,collow = col 1, colhigh = col . 1;if (row == 1) rowlow..;if (row == maxrow) rowhigh;if (col == 1) collow..;if (col == maxcol) colhigh;for (i = rowlow; i <= rowhigh; i..)for (j = collow; j <= colhigh; j..)count += grid[i][j]; Modify the Life function initialize so that it sets up the initial Life :: grid configuration by acceptingoccupied positions as a sequence of blanks and x’s in appropriate rows, rather than requiring the occupiedpositions to be entered as numerical coordinate pairs.Answer The following program includes all the changes for projects P1–P6. The changes required forProjects P7 and P8 are system dependent and have not been implemented.#include "../../c/"#include ""#include "../../c/"#include ""int main() /*Pre: The user supplies an initial configuration of living cells.Post: The program prints a sequence of pictures showing the changes in the configuration of living cells according to the rules forthe game of Life.Uses: The class Life and methods initialize(), print(), and update();the functions instructions(), user_says_yes().*/16 Chapter 1 _ Programming Principles{Life configuration;instructions();();(cout);bool command;do {();(cout);cout << "Continue viewing without changes " << endl;if (!(command = user_says_yes())) {cout << "Do you want to quit " << flush;if (user_says_yes()) command = false;else {cout << "Do you want help " << flush;if (user_says_yes()) instructions();cout << "Do you want to make any changes " << flush;if (user_says_yes()) ();command = true;}}} while (command);cout << "Do you want to save the final position to file " << flush;if (user_says_yes()) {char name[1000];cout << "Give the save file name: " << flush;cin >> name;ofstream f(name);(f);}}const int maxrow = 20, maxcol = 60; int neighbor_count(int row, int col); bool step_mode;};void Life::edit()/* Post: User has edited configuration, and/or step mode */{cout << "Do you want to switch the step mode " << flush;if (user_says_yes()) step_mode = !step_mode;cout << "Do you want to change the configuration " << flush;if (!user_says_yes()) return;Section _ Program Maintenance 17int row, col;cout << "List the coordinates for cells to change." << endl;cout << "Terminate the list with the the special pair -1 -1" << endl;cin >> row >> col;while (row != -1 || col != -1) {if (row >= 1 && row <= maxrow)if (col >= 1 && col <= maxcol)grid[row][col] = 1 - grid[row][col];elsecout << "Column " << col << " is out of range." << endl;elsecout << "Row " << row << " is out of range." << endl;cin >> row >> col;}}void Life::print(ostream &f)/*Pre: The Life object contains a configuration.Post: The configuration is written to stream f for the user.*/{int row, col;f << "The current Life configuration is:" << endl;for (row = 1; row <= maxrow; row++) {for (col = 1; col <= maxcol; col++)if (grid[row][col] == 1) f << '*';else f << ' ';f << endl;}f << endl;}int Life::neighbor_count(int row, int col)/*Pre: The Life object contains a configuration, and the coordinates row and col define a cell inside its hedge.Post: The number of living neighbors of the specified cell is returned. */{int i, j;int count = 0;for (i = row - 1; i <= row + 1; i++)for (j = col - 1; j <= col + 1; j++)count += grid[i][j]; count -= grid[row][col]; return count;}void Life::update()/*Pre: The Life object contains a configuration.Post: The Life object contains the next generation of configuration. */{int row, col;int new_grid[maxrow + 2][maxcol + 2];18 Chapter 1 _ Programming Principlesfor (row = 1; row <= maxrow; row++)for (col = 1; col <= maxcol; col++)switch (neighbor_count(row, col)) {case 2:new_grid[row][col] = grid[row][col]; break;case 3:if (step_mode &&grid[row][col] == 0)cout << "Vivify cell " << row << " " << col << endl;new_grid[row][col] = 1; break;default:if (step_mode && grid[row][col] == 1)cout << "Kill cell " << row << " " << col << endl;。