




已閱讀5頁(yè),還剩58頁(yè)未讀, 繼續(xù)免費(fèi)閱讀
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
_Data Structures and Algorithm 習(xí)題答案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 External 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 Structures and Algorithm Analysis, 2nd edition. For most of the problems requiring an algorithm I have given actual code. In a few cases I have presented pseudocode. Please be aware that the code presented in this manual has not actually been compiled and tested. While I believe the algorithms to be essentially correct, there may be errors in syntax as well as semantics. Most importantly, these solutions provide a guide to the instructor as to the intended answer, rather than usable programs. 1 Data Structures and Algorithms Instructors note: Unlike the other chapters, many of the questions in this chapter are not really suitable for graded work. The questions are mainly intended to get students thinking about data structures issues. 1.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 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 reverse order. Addition and multiplication are implemented by what amounts to grade-school arithmetic. For addition, simply march down in parallel through the two lists representing the operands, at each digit appending to a new list the appropriate partial sum and bringing forward a carry bit as necessary. For multiplication, combine the addition function with a new function that multiplies a single digit by an integer. Exponentiation can be done either by repeated multiplication (not really practical) or by the traditional (log n)-time algorithm based on the binary representation of the exponent. Discovering this faster algorithm will be beyond the reach of most students, so should not be required. 1.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 String 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 function. 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 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 implementation). This representation is the physical implementation of an ADT defined by the normal arithmetic operations, declarations, and other support given by the programming language for integers. 1.6 An ADT for two-dimensional arrays might look as follows. Matrix add(Matrix M1, Matrix M2); Matrix multiply(Matrix M1, Matrix M2); Matrix transpose(Matrix M1); void setvalue(Matrix M1, int row, int col, int val); int getvalue(Matrix M1, int row, int col); List getrow(Matrix M1, int row); One implementation for the sparse matrix is described in Section 12.3 Another implementation is a hash table whose 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, 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 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 to the dictionary and (2) searching the dictionary for a given word. Typically, dictionary access involves some sort of pre-processing of the word to arrive at the “root” of the word. A twenty page document (single spaced) is likely to contain about 20,000 words. A user may be willing to wait a few seconds between individual “hits” of mis-spelled words, or perhaps up to a minute for the whole document to be processed. This means that a check for an individual word can take about 10-20 ms. Users will typically insert individual words into the dictionary interactively, so this process can take 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 fundamental operations of any database system: search, insertion and deletion. A reasonable database has a time constraint that will satisfy the patience of a typical user. For an insert, delete, or exact match query, a few seconds is satisfactory. If the database is meant to support range queries and mass deletions, the entire operation may be allowed to take longer, perhaps on the order of a minute. However, the time spent to process individual cities within the range must be appropriately reduced. In practice, the data representation will need to be such that it accommodates efficient processing to meet these time constraints. In particular, it may be necessary to support operations that process range queries efficiently by processing all cities in the range as a batch, rather than as a series of operations on individual cities. 1.11 Students at this level are likely already familiar with binary search. Thus, they should typically respond with sequential search and binary search. Binary search should be described as better since it typically needs to make fewer comparisons (and thus is likely to be much faster). 1.12 The answer to this question is discussed in Chapter 8. Typical measures of cost will be number of comparisons and number of swaps. Tests should include running timings on sorted, reverse sorted, and random lists of various sizes. Chap. 1 Data Structures and Algorithms 1.13 The first part is easy with the hint, but the second part is rather difficult to do without a stack. a) bool checkstring(string S) int count = 0; for (int i=0; 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. 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 fractional 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. 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 ancestor 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) 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!total 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 proposed 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) & (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 examination to understand what it does, or to have confidence that it works as claimed. (b) Fibr is so much slower than Fibi because Fibr re-computes the bulk of the series twice to get the two values to add. What is much worse, the recursive calls to compute the subexpressions also re-compute the bulk of the series, and do so recursively. The result is an exponential explosion. In contrast, Fibicomputes each value in the series exactly once, and so its running time is proportional to n. 2.11 / Array curri indicates current position of ring i. void GenTOH(int n, POLE goal, POLE t1, POLE t2, POLE* curr) 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 of 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 programming 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 range 0 to 2n . 1, we will get the entire powerset. void powerset(int n) for (int i=0; iipow(2, n); i+) for (int j=0; jn; j+) if (bitposition(n, j) = 1) cout j ; cout endl; 2.15 Proof: Assume that there is a largest prime number. Call it Pn,the nth largest prime number, and label all of the primes in order P1 =2, P2 =3, and so on. Now, consider the number C formed by multiplying all of the n prime numbers together. The value C +1is not divisible by any of the n prime numbers. C +1is a prime number larger than Pn, a contradiction. Thus, we conclude that there is no largest prime number. . 2.16 Note: This problem is harder than most sophomore level students can handle. Proof: The proof is by contradiction. Assume that 2is rational. By definition, there exist integers p and q such that p2=, q where p and q have no common factors (that is, the fraction p/q is in lowest terms). By squaring both sides and doing some simple algebraic manipulation, we get 2p2= 2q222q = p Since p2 must be even, p must be even. Thus, 9 222q =4(p)222 q =2(p)2This implies that q2 is also even. Thus, p and q are both even, which contra dicts the requirement that p and q have no common factors. Thus, 2must be irrational. . 2.17 The leftmost summation sums the integers from 1 to n. The second summation merely reverses this order, summing the numbers from n . 1+1=n down to n . n +1=1. The third summation has a variable substitution of i.1for i, with a corresponding substitution in the summation bounds. Thus, it is also the summation of n . 0=n to n . (n . 1)=1. 2.18 Proof: (a) Base case. For n =1, 12 = 2(1)3 +3(1)2 +1/6=1. Thus, the formula is correct for the base case. (b) Induction Hypothesis. n.1 2(n . 1)3 +3(n . 1)2 +(n . 1)i2 = .6 i=1 (c) Induction Step. nn.1 i2 i2 +n 2= i=1 i=1 2(n . 1)3 +3(n . 1)2 +(n . 1) 2= +n6 2n3 . 6n2 +6n . 2+3n2 . 6n +3+n . 1 2= +n6 2n3 +3n2 +n = .6 Thus, the theorem is proved by mathematical induction. . 2.19 Proof: (a) Base case. For n =1, 1/2=1. 1/2=1/2. Thus, the formula is correct for the base case. (b) Induction Hypothesis. n.1 11=1. .2in.12i=1 Chap. 2 Mathematical Preliminaries (c) Induction Step. nn.11 11 =+i in222i=1 i=1 11=1. + n.1 n221=1. . n2Thus, the theorem is proved by mathematical induction. . 2.20 Pro
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 空氣動(dòng)力學(xué)與飛行原理 課件 1.3-1.4 通航空器及其分類
- 豐田思考法分享
- 空氣動(dòng)力學(xué)與飛行原理 課件 5.1 主旋翼
- 丙型肝炎防治指南更新解讀
- 瓣膜功能損傷機(jī)制
- 頒獎(jiǎng)典禮主持詞5篇
- 安全生產(chǎn)月安全知識(shí)競(jìng)賽試題
- 安全應(yīng)急預(yù)案方案【7篇】
- 老年癡呆護(hù)理指南
- 臨潭縣第一中學(xué)2024-2025學(xué)年度第二學(xué)期高三期中考試數(shù)學(xué)試卷
- 2025年自然資源管理基本知識(shí)考試題目及答案
- 可信數(shù)據(jù)空間解決方案星環(huán)科技
- 2025-2030IVD原酶料市場(chǎng)發(fā)展態(tài)勢(shì)剖析及未來需求趨勢(shì)預(yù)測(cè)研究報(bào)告
- 基于單片機(jī)的智能臺(tái)燈控制系統(tǒng)的設(shè)計(jì)14000字【論文】
- (高清版)DB13(J)∕T 8557-2023 建設(shè)工程消耗量標(biāo)準(zhǔn)及計(jì)算規(guī)則(房屋修繕建筑工程)
- 2024云南省曲靖市陸良縣城鄉(xiāng)公交服務(wù)有限公司招聘(17人)筆試參考題庫(kù)附帶答案詳解
- 2025-2030年中國(guó)智能眼鏡行業(yè)市場(chǎng)市場(chǎng)現(xiàn)狀供需分析及投資評(píng)估規(guī)劃分析研究報(bào)告
- 2025年全國(guó)高考物理試題及答案
- 無人機(jī)飛行器編程基本知識(shí)試題及答案
- 國(guó)有企業(yè)違法犯罪課件
- 鉗工安全測(cè)試題及答案
評(píng)論
0/150
提交評(píng)論