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

上传人:豆**** 文档编号:34700754 上传时间:2022-08-17 格式:DOC 页数:33 大小:148.50KB
返回 下载 相关 举报
数据结构与算法分析 C++版答案.doc_第1页
第1页 / 共33页
数据结构与算法分析 C++版答案.doc_第2页
第2页 / 共33页
点击查看更多>>
资源描述

《数据结构与算法分析 C++版答案.doc》由会员分享,可在线阅读,更多相关《数据结构与算法分析 C++版答案.doc(33页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、如有侵权,请联系网站删除,仅供学习与交流数据结构与算法分析 C+版答案【精品文档】第 33 页Data Structures and Algorithm 习题答案Preface ii 1 Data Structures and Algorithms 1 2 Mathematical Preliminaries 5 3 Algorithm Analysis 17 4 Lists, Stacks, and Queues 23 5 Binary Trees 32 6 General Trees 40 7 Internal Sorting 46 8 File Processing and Extern

2、al Sorting 54 9Searching 58 10 Indexing 64 11 Graphs 69 12 Lists and Arrays Revisited 76 13 Advanced Tree Structures 82 i ii Contents 14 Analysis Techniques 88 15 Limits to Computation 94 Preface Contained herein are the solutions to all exercises from the textbook A Practical Introduction to Data S

3、tructures and Algorithm Analysis, 2nd edition. For most of the problems requiring an algorithm I have given actual code. In a few cases I have presented pseudocode. Please be aware that the code presented in this manual has not actually been compiled and tested. While I believe the algorithms to be

4、essentially correct, there may be errors in syntax as well as semantics. Most importantly, these solutions provide a guide to the instructor as to the intended answer, rather than usable programs. 1 Data Structures and Algorithms Instructors note: Unlike the other chapters, many of the questions in

5、this chapter are not really suitable for graded work. The questions are mainly intended to get students thinking about data structures issues. 1.1 This question does not have a specific right answer, provided the student keeps to the spirit of the question. Students may have trouble with the concept

6、 of “operations.” 1.2 This exercise asks the student to expand on their concept of an integer representation. A good answer is described by Project 4.5, where a singly-linked list is suggested. The most straightforward implementation stores each digit in its own list node, with digits stored in reve

7、rse order. Addition and multiplication are implemented by what amounts to grade-school arithmetic. For addition, simply march down in parallel through the two lists representing the operands, at each digit appending to a new list the appropriate partial sum and bringing forward a carry bit as necess

8、ary. For multiplication, combine the addition function with a new function that multiplies a single digit by an integer. Exponentiation can be done either by repeated multiplication (not really practical) or by the traditional (log n)-time algorithm based on the binary representation of the exponent

9、. Discovering this faster algorithm will be beyond the reach of most students, so should not be required. 1.3 A sample ADT for character strings might look as follows (with the normal interpretation of the function names assumed). Chap. 1 Data Structures and Algorithms / Concatenate two strings Stri

10、ng strcat(String s1, String s2); / Return the length of a string int length(String s1); / Extract a substring, starting at start, / and of length length String extract(String s1, int start, int length); / Get the first character char first(String s1); / Compare two strings: the normal C+ strcmp func

11、tion. Some / convention should be indicated for how to interpret the / return value. In C+, this is 1 for s1s2. int strcmp(String s1, String s2) / Copy a string int strcpy(String source, String destination) 1.4 The answer to this question is provided by the ADT for lists given in Chapter 4. 1.5 Ones

12、 compliment stores the binary representation of positive numbers, and stores the binary representation of a negative number with the bits inverted. Twos compliment is the same, except that a negative number has its bits inverted and then one is added (for reasons of efficiency in hardware implementa

13、tion). This representation is the physical implementation of an ADT defined by the normal arithmetic operations, declarations, and other support given by the programming language for integers. 1.6 An ADT for two-dimensional arrays might look as follows. Matrix add(Matrix M1, Matrix M2); Matrix multi

14、ply(Matrix M1, Matrix M2); Matrix transpose(Matrix M1); void setvalue(Matrix M1, int row, int col, int val); int getvalue(Matrix M1, int row, int col); List getrow(Matrix M1, int row); One implementation for the sparse matrix is described in Section 12.3 Another implementation is a hash table whose

15、search key is a concatenation of the matrix coordinates. 1.7 Every problem certainly does not have an algorithm. As discussed in Chapter 15, there are a number of reasons why this might be the case. Some problems dont have a sufficiently clear definition. Some problems, such as the halting problem,

16、are non-computable. For some problems, such as one typically studied by artificial intelligence researchers, we simply dont know a solution. 1.8 We must assume that by “algorithm” we mean something composed of steps are of a nature that they can be performed by a computer. If so, than any algorithm

17、can be expressed in C+. In particular, if an algorithm can be expressed in any other computer programming language, then it can be expressed in C+, since all (sufficiently general) computer programming languages compute the same set of functions. 1.9 The primitive operations are (1) adding new words

18、 to the dictionary and (2) searching the dictionary for a given word. Typically, dictionary access involves some sort of pre-processing of the word to arrive at the “root” of the word. A twenty page document (single spaced) is likely to contain about 20,000 words. A user may be willing to wait a few

19、 seconds between individual “hits” of mis-spelled words, or perhaps up to a minute for the whole document to be processed. This means that a check for an individual word can take about 10-20 ms. Users will typically insert individual words into the dictionary interactively, so this process can take

20、a couple of seconds. Thus, search must be much more efficient than insertion. 1.10 The user should be able to find a city based on a variety of attributes (name, location, perhaps characteristics such as population size). The user should also be able to insert and delete cities. These are the fundam

21、ental operations of any database system: search, insertion and deletion. A reasonable database has a time constraint that will satisfy the patience of a typical user. For an insert, delete, or exact match query, a few seconds is satisfactory. If the database is meant to support range queries and mas

22、s deletions, the entire operation may be allowed to take longer, perhaps on the order of a minute. However, the time spent to process individual cities within the range must be appropriately reduced. In practice, the data representation will need to be such that it accommodates efficient processing

23、to meet these time constraints. In particular, it may be necessary to support operations that process range queries efficiently by processing all cities in the range as a batch, rather than as a series of operations on individual cities. 1.11 Students at this level are likely already familiar with b

24、inary search. Thus, they should typically respond with sequential search and binary search. Binary search should be described as better since it typically needs to make fewer comparisons (and thus is likely to be much faster). 1.12 The answer to this question is discussed in Chapter 8. Typical measu

25、res of cost will be number of comparisons and number of swaps. Tests should include running timings on sorted, reverse sorted, and random lists of various sizes. Chap. 1 Data Structures and Algorithms 1.13 The first part is easy with the hint, but the second part is rather difficult to do without a

26、stack. a) bool checkstring(string S) int count = 0; for (int i=0; ilength(S); i+) if (Si = () count+; if (Si = ) if (count = 0) return FALSE; count-; if (count = 0) return TRUE; else return FALSE; b) int checkstring(String Str) Stack S; int count = 0; for (int i=0; i 0. It is symmetric since xy = yx

27、. It is transitive since any two members of the given class satisfy the relationship. 5 Chap. 2 Mathematical Preliminaries (d) This is not an equivalance relation since it is not symmetric. For example, a =1and b =2. (e) This is an eqivalance relation that divides the rationals based on their fracti

28、onal values. It is reflexive since for all a, a.a =0. It is symmetric since if a.b =x then b.a =.x. It is transitive since any two rationals with the same fractional value will yeild an integer. (f) This is not an equivalance relation since it is not transitive. For example, 4. 2=2and 2. 0=2,but 4.

29、0=4. 2.3 A relation is a partial ordering if it is antisymmetric and transitive. (a) Not a partial ordering because it is not transitive. (b) Is a partial ordering bacause it is antisymmetric (if a is an ancestor of b, then b cannot be an ancestor of a) and transitive (since the ancestor of an ances

30、tor is an ancestor). (c) Is a partial ordering bacause it is antisymmetric (if a is older than b, then b cannot be older than a) and transitive (since if a is older than b and b is older than c, a is older than c). (d) Not a partial ordering, since it is not antisymmetric for any pair of sisters. (e

31、) Not a partial ordering because it is not antisymmetric. (f) This is a partial ordering. It is antisymmetric (no violations exist) and transitive (no violations exist). 2.4 A total ordering can be viewed as a permuation of the elements. Since there are n!permuations of n elements, there must be n!t

32、otal orderings. 2.5 This proposed ADT is inspired by the list ADT of Chapter 4. void clear(); void insert(int); void remove(int); void sizeof(); bool isEmpty(); bool isInSet(int); 2.6 This proposed ADT is inspired by the list ADT of Chapter 4. Note that while it is similiar to the operations propose

33、d for Question 2.5, the behaviour is somewhat different. void clear(); void insert(int); void remove(int); void sizeof(); 7 bool isEmpty(); / Return the number of elements with a given valueint countInBag(int); 2.7 The list class ADT from Chapter 4 is a sequence. 2.8 long ifact(int n) / make n = 0)

34、& (n = 12), Input out of range); for (int i=1; i= n; i+) fact = fact * i; return fact; 2.9 void rpermute(int *array, int n) swap(array, n-1, Random(n); rpermute(array, n-1); 2.10 (a) Most people will find the recursive form natural and easy to understand. The iterative version requires careful exami

35、nation to understand what it does, or to have confidence that it works as claimed. (b) Fibr is so much slower than Fibi because Fibr re-computes the bulk of the series twice to get the two values to add. What is much worse, the recursive calls to compute the subexpressions also re-compute the bulk o

36、f the series, and do so recursively. The result is an exponential explosion. In contrast, Fibicomputes each value in the series exactly once, and so its running time is proportional to n. 2.11 / Array curri indicates current position of ring i. void GenTOH(int n, POLE goal, POLE t1, POLE t2, POLE* c

37、urr) if (currn = goal) / Get top n-1 rings set up GenTOH(n-1, goal, t1, t2, curr); else if (currn = t1) swap(t1, t2); / Get names right / Now, ring n is on pole t2. Put others on t1. GenTOH(n-1, t1, goal, t2, curr); move(t2, goal); GenTOH(n-1, goal, t1, t2, curr); / Move n-1 back 2.12 At each step o

38、f the way, the reduction toward the base case is only half as far as the previous time. In theory, this series approaches, but never reaches, 0, so it will go on forever. In practice, the value should become computationally indistinguishable from zero, and terminate. However, this is terrible progra

39、mming practice. Chap. 2 Mathematical Preliminaries 2.13 void allpermute(int array, int n, int currpos) if (currpos = (n-1) printout(array); return; for (int i=currpos; in; i+) swap(array, currpos, i); allpermute(array, n, currpos+1); swap(array, currpos, i); / Put back for next pass 2.14 In the following, function bitposition(n, i) returns the value (0 or 1) at the ith bit position of integer value n. The idea is the print out the elements at the indicated bit positions within the set. If we do this for values in the

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 高考资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁