数据结构与算法分析4

合集下载

《数据结构与算法(C++语言版)》第4章_串

《数据结构与算法(C++语言版)》第4章_串

串函数与串的类定义
• 常用的 常用的C++串函数 串函数 • C++的串库(string.h)中提供了许多字符串的操作函数,几 个常用的C++字符串函数及其使用方法如下。 •假设已有以下定义语句:
串函数与串的类定义
• (1)串拷贝函数 • char *strcpy(char *s1, const char *s2),将字符串s2复制到字 符串数组s1中,返回s1的值。 • char *strncpy(char *s1, const char *s2, size_tn)将字符串s2中最 多n个字符复制到字符串数组s1中,返回s1的值。 • 例如:
串函数与串的类定义
• (3)串比较函数 • int strcmp(const char *s1, const char *s2),比较字符串s1和字 符串s2。函数在s1等于、小于或大于s2时,分别返回0、小 于0或者大于0的值。 • int strncmp(const char *s1, const char *s2, size_tn)比较字符串 s1中的n个字符和字符串s2。函数在s1等于、小于或大于s2 时,分别返回0、小于0或者大于0的值。 • 例如:
串模式匹配
• 无回溯的匹配算法 • 在上面介绍的匹配算法中,某趟匹配失败时,下一趟的匹 配相当于将子串P后移1位再从头与主串中对应字符进行比 较,即相当于i指示器回溯到上趟(最近失败的一趟)匹配 的起点的下一个位置,这样,主串中每个字符都要与子串 中的第1个字符对应一次,再向后比较。因此,主串中每个 字符参加比较的次数最多可达n次(n为子串长度),因此 时间复杂度为O(nm)。那么,能否使目标串中每个字符只参 加一次比较呢?也就是说,能否不回溯i指示器?回答是肯 定的。这个问题是由D.E.Knoth与V.R.Pratt和J.H.Morris同时 解决的,所以有的文献也称这种思想的串匹配算法为KMP 算法。

数据结构与算法分析习题与参考答案

数据结构与算法分析习题与参考答案

大学《数据结构与算法分析》课程习题及参考答案模拟试卷一一、单选题(每题 2 分,共20分)1.以下数据结构中哪一个是线性结构?( )A. 有向图B. 队列C. 线索二叉树D. B树2.在一个单链表HL中,若要在当前由指针p指向的结点后面插入一个由q指向的结点,则执行如下( )语句序列。

A. p=q; p->next=q;B. p->next=q; q->next=p;C. p->next=q->next; p=q;D. q->next=p->next; p->next=q;3.以下哪一个不是队列的基本运算?()A. 在队列第i个元素之后插入一个元素B. 从队头删除一个元素C. 判断一个队列是否为空D.读取队头元素的值4.字符A、B、C依次进入一个栈,按出栈的先后顺序组成不同的字符串,至多可以组成( )个不同的字符串?A.14B.5C.6D.85.由权值分别为3,8,6,2的叶子生成一棵哈夫曼树,它的带权路径长度为( )。

以下6-8题基于图1。

6.该二叉树结点的前序遍历的序列为( )。

A.E、G、F、A、C、D、BB.E、A、G、C、F、B、DC.E、A、C、B、D、G、FD.E、G、A、C、D、F、B7.该二叉树结点的中序遍历的序列为( )。

A. A、B、C、D、E、G、FB. E、A、G、C、F、B、DC. E、A、C、B、D、G、FE.B、D、C、A、F、G、E8.该二叉树的按层遍历的序列为( )。

A.E、G、F、A、C、D、B B. E、A、C、B、D、G、FC. E、A、G、C、F、B、DD. E、G、A、C、D、F、B9.下面关于图的存储的叙述中正确的是( )。

A.用邻接表法存储图,占用的存储空间大小只与图中边数有关,而与结点个数无关B.用邻接表法存储图,占用的存储空间大小与图中边数和结点个数都有关C. 用邻接矩阵法存储图,占用的存储空间大小与图中结点个数和边数都有关D.用邻接矩阵法存储图,占用的存储空间大小只与图中边数有关,而与结点个数无关10.设有关键码序列(q,g,m,z,a,n,p,x,h),下面哪一个序列是从上述序列出发建堆的结果?( )A. a,g,h,m,n,p,q,x,zB. a,g,m,h,q,n,p,x,zC. g,m,q,a,n,p,x,h,zD. h,g,m,p,a,n,q,x,z二、填空题(每空1分,共26分)1.数据的物理结构被分为_________、________、__________和___________四种。

《数据结构与算法》第四章-学习指导材料

《数据结构与算法》第四章-学习指导材料

《数据结构与算法》第四章串知识点及例题精选串(即字符串)是一种特殊的线性表,它的数据元素仅由一个字符组成。

4.1 串及其基本运算4.1.1 串的基本概念1.串的定义串是由零个或多个任意字符组成的字符序列。

一般记作:s="s1 s2 … s n""其中s 是串名;在本书中,用双引号作为串的定界符,引号引起来的字符序列为串值,引号本身不属于串的内容;a i(1<=i<=n)是一个任意字符,它称为串的元素,是构成串的基本单位,i是它在整个串中的序号; n为串的长度,表示串中所包含的字符个数,当n=0时,称为空串,通常记为Ф。

2.几个术语子串与主串:串中任意连续的字符组成的子序列称为该串的子串。

包含子串的串相应地称为主串。

子串的位置:子串的第一个字符在主串中的序号称为子串的位置。

串相等:称两个串是相等的,是指两个串的长度相等且对应字符都相等。

4.2 串的定长顺序存储及基本运算因为串是数据元素类型为字符型的线性表,所以线性表的存储方式仍适用于串,也因为字符的特殊性和字符串经常作为一个整体来处理的特点,串在存储时还有一些与一般线性表不同之处。

4.2.1 串的定长顺序存储类似于顺序表,用一组地址连续的存储单元存储串值中的字符序列,所谓定长是指按预定义的大小,为每一个串变量分配一个固定长度的存储区,如:#define MAXSIZE 256char s[MAXSIZE];则串的最大长度不能超过256。

如何标识实际长度?1. 类似顺序表,用一个指针来指向最后一个字符,这样表示的串描述如下:typedef struct{ char data[MAXSIZE];int curlen;} SeqString;定义一个串变量:SeqString s;这种存储方式可以直接得到串的长度:s.curlen+1。

如图4.1所示。

s.dataMAXSIZE-1图4.1 串的顺序存储方式12. 在串尾存储一个不会在串中出现的特殊字符作为串的终结符,以此表示串的结尾。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

数据结构经典书籍

数据结构经典书籍

数据结构经典书籍摘要:一、数据结构的重要性二、经典数据结构书籍介绍1.《数据结构与算法分析》2.《大话数据结构》3.《算法导论》4.《数据结构与算法》三、书籍内容比较及选择建议正文:数据结构是计算机科学与技术领域中的核心基础课程,它主要研究数据的组织、存储、管理和操作方法。

掌握数据结构的知识,能够帮助我们更好地设计、分析、优化算法,提高程序的性能。

因此,学习数据结构对于计算机专业的学生和程序员来说至关重要。

在众多的数据结构书籍中,以下四本书被认为是经典之作:1.《数据结构与算法分析》(原名:Data Structures and Algorithm Analysis in Java)是Mark Allen Weiss 所著的一本数据结构和算法书籍。

该书以Java 语言为基础,详细介绍了数组、链表、堆、栈、队列等基本数据结构,以及排序、查找、图算法等常用算法。

书中提供了丰富的实例和习题,适合初学者入门学习。

2.《大话数据结构》是程杰所著的一本以轻松幽默的语言讲解数据结构的书籍。

该书通过大量的生活例子和图解,通俗易懂地阐述了数据结构的基本概念、原理和应用。

这本书适合编程初学者和对数据结构感兴趣的读者阅读。

3.《算法导论》(原名:Introduction to Algorithms)是ThomasH.Cormen 等人所著的一本关于算法分析和设计的经典教材。

该书详细介绍了各种数据结构及其操作,以及排序、查找、图算法等常用算法。

书中提供了丰富的实例和习题,以及大量的实际应用案例。

这本书适合已经具备一定编程基础的读者深入学习。

4.《数据结构与算法》(原名:Data Structures and Algorithms)是Alfred V.Aho 等人所著的一本数据结构和算法教材。

该书系统地介绍了数组、链表、堆、栈、队列等基本数据结构,以及排序、查找、图算法等常用算法。

书中提供了丰富的实例和习题,以及大量的实际应用案例。

数据结构经典书籍

数据结构经典书籍

数据结构经典书籍数据结构是计算机科学中的一门基础课程,它研究如何组织和存储数据,以便能够高效地访问和操作。

在学习数据结构时,经典书籍是我们不可或缺的学习资料。

下面是我列举的一些经典的数据结构书籍,它们涵盖了各种不同的数据结构和算法,帮助读者深入理解和掌握数据结构的基本原理和应用。

1. 《数据结构与算法分析》这本书由Mark Allen Weiss编写,是数据结构领域的经典教材之一。

它介绍了各种常见的数据结构和算法,并提供了详细的分析和实现示例。

该书以清晰的语言和丰富的示意图,帮助读者理解不同数据结构的特点和应用场景。

2. 《算法导论》由Thomas H. Cormen等人编写的《算法导论》是计算机科学领域最具影响力的教材之一。

它包含了广泛的算法和数据结构内容,并提供了详细的证明和分析。

该书不仅适合作为教材使用,也是研究和实践中的重要参考资料。

3. 《数据结构与算法分析:C语言描述》这本书由Clifford A. Shaffer编写,以C语言为基础,介绍了数据结构和算法的基本概念和实现方法。

该书通过大量的示例代码和练习题,帮助读者巩固和应用所学知识。

4. 《算法(第4版)》由Robert Sedgewick和Kevin Wayne合著的《算法(第4版)》是一本全面介绍算法和数据结构的教材。

该书以Java语言为例,涵盖了各种经典算法和数据结构的实现和分析。

它还提供了大量的练习题和在线学习资源,帮助读者深入理解和应用所学知识。

5. 《数据结构与算法分析:Java语言描述》这本书由Mark Allen Weiss编写,以Java语言为基础,介绍了数据结构和算法的基本概念和实现方法。

它通过清晰的示例代码和详细的分析,帮助读者理解和应用不同数据结构和算法。

6. 《数据结构与算法分析:Python语言描述》由Clifford A. Shaffer编写的《数据结构与算法分析:Python语言描述》是一本以Python语言为基础的数据结构教材。

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

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

数据结构与算法分析C++版答案(总53页)-本页仅作为预览文档封面,使用时请删除本页-Data Structures and Algorithm 习题答案Preface ii1 Data Structures and Algorithms 12 Mathematical Preliminaries 53 Algorithm Analysis 174 Lists, Stacks, and Queues 235 Binary Trees 326 General Trees 407 Internal Sorting 468 File Processing and External Sorting 54 9Searching 5810 Indexing 6411 Graphs 6912 Lists and Arrays Revisited 7613 Advanced Tree Structures 82iii Contents14 Analysis Techniques 8815 Limits to Computation 94PrefaceContained herein are the solutions to all exercises from the textbook A Practical Introduction to Data Structures and Algorithm Analysis, 2nd edition.For most of the problems requiring an algorithm I have given actual code. Ina few cases I have presented pseudocode. Please be aware that the code presented in this manual has not actually been compiled and tested. While I believe the algorithmsto be essentially correct, there may be errors in syntax as well as semantics.Most importantly, these solutions provide a guide to the instructor as to the intendedanswer, rather than usable programs.1Data Structures and AlgorithmsInstructor’s note: Unlike the other chapters, many of the questions in this chapter are not really suitable for graded work. The questions are mainly intended to get students thinking about data structures issues.This question does not have a specific right answer, provided the studentkeeps to the spirit of the question. Students may have trouble with the conceptof “operations.”This exercise asks the student to expand on their concept of an integer representation.A good answer is described by Project , where a singly-linkedlist is suggested. The most straightforward implementation stores each digitin its own list node, with digits stored in reverse order. Addition and multiplication are implemented by what amounts to grade-school arithmetic. Foraddition, simply march down in parallel through the two lists representingthe operands, at each digit appending to a new list the appropriate partialsum and bringing forward a carry bit as necessary. For multiplication, combine the addition function with a new function that multiplies a single digitby an integer. Exponentiation can be done either by repeated multiplication (not really practical) or by the traditional Θ(log n)-time algorithm based onthe binary representation of the exponent. Discovering this faster algorithmwill be beyond the reach of most students, so should not be required.A sample ADT for character strings might look as follows (with the normal interpretation of the function names assumed).Chap. 1 Data Structures and AlgorithmsSomeIn C++, this is 1for s1<s2; 0 for s1=s2;int strcmp(String s1, String s2)One’s co mpliment stores the binary representation of positive numbers, and stores the binary representation of a negative number with the bits inverted. Two’s compliment is the same, except that a negative number has its bits inverted and then one is added (for reasons of efficiency in hardware implementation).This representation is the physical implementation of an ADTdefined by the normal arithmetic operations, declarations, and other support given by the programming language for integers.An ADT for two-dimensional arrays might look as follows.Matrix add(Matrix M1, Matrix M2);Matrix multiply(Matrix M1, Matrix M2);Matrix transpose(Matrix M1);void setvalue(Matrix M1, int row, int col, int val);int getvalue(Matrix M1, int row, int col);List getrow(Matrix M1, int row);One implementation for the sparse matrix is described in Section Another implementationis a hash table whose search key is a concatenation of the matrix coordinates.Every problem certainly does not have an algorithm. As discussed in Chapter 15, there are a number of reasons why this might be the case. Some problems don’t have a sufficiently clear definition. Some problems, such as the halting problem,are non-computable. For some problems, such as one typically studied by artificial intelligence researchers, we simply don’t know a solution.We must assume that by “algorithm” we mean something composed of steps areof a nature that they can be performed by a computer. If so, than any algorithmcan be expressed in C++. In particular, if an algorithm can be expressed in anyother computer programming language, then it can be expressed in C++, since all (sufficiently general) computer programming languages compute the same set of functions.The primitive operations are (1) adding new words to the dictionary and (2) searchingthe dictionary for a given word. Typically, dictionary access involves some sortof 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. 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 insertand delete cities. These are the fundamental operations of any database system: search, insertion and deletion.A reasonable database has a time constraint that will satisfy the patience of a 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 supportoperations that process range queries efficiently by processing all cities in the range as a batch, rather than as a series of operations on individual cities. Students at this level are likely already familiar with binary search. Thus, they should typically respond with sequential search and binary search. Binary search should be described as better since it typically needs to make fewer comparisons (and thus is likely to be much faster).The answer to this question is discussed in Chapter 8. Typical measures of cost will be number of comparisons and number of swaps. Tests should include running timings on sorted, reverse sorted, and random lists of various sizes.Chap. 1 Data Structures and AlgorithmsThe first part is easy with the hint, but the second part is rather difficult to do withouta stack.a) bool checkstring(string S) {int count = 0;for (int i=0; i<length(S); i++)if (S[i] == ’(’) count++;if (S[i] == ’)’) {if (count == 0) return FALSE;count--;}}if (count == 0) return TRUE;else return FALSE;}b) int checkstring(String Str) {Stack S;int count = 0;for (int i=0; i<length(S); i++)if (S[i] == ’(’)(i);if (S[i] == ’)’) {if ()) return i;();}if ()) return -1;else return ();}Answers to this question are discussed in Section .This is somewhat different from writing sorting algorithms for a computer, since person’s “working space” is typically limited, as is their ability to physically manipulatethe pieces of paper. Nonetheless, many of the common sorting algorithms have their analogs to solutions for this problem. Most typical answers will be insertion sort, variations on mergesort, and variations on binsort.Answers to this question are discussed in Chapter 8.2Mathematical Preliminaries(a) Not reflexive if the set has any members. One could argue it is symmetric, antisymmetric, and transitive, since no element violate any ofthe rules.(b)Not reflexive (for any female). Not symmetric (consider a brother and sister). Not antisymmetric (consider two brothers). Transitive (for any3 brothers).(c)Not reflexive. Not symmetric, and is antisymmetric. Not transitive(only goes one level).(d)Not reflexive (for nearly all numbers). Symmetric since a+ b= b+ a,so not antisymmetric. Transitive, but vacuously so (there can be nodistinct a, b,and cwhere aRband bRc).(e)Reflexive. Symmetric, so not antisymmetric. Transitive (but sort of vacuous).(f)Reflexive – check all the cases. Since it is only true when x= y,itis technically symmetric and antisymmetric, but rather vacuous. Likewise,it is technically transitive, but vacuous.In general, prove that something is an equivalence relation by proving that it is reflexive, symmetric, and transitive.(a)This is an equivalence that effectively splits the integers into odd andeven sets. It is reflexive (x+ xis even for any integer x), symmetric(since x+ y= y+ x) and transitive (since you are always adding twoodd or even numbers for any satisfactory a, b,and c).(b)This is not an equivalence. To begin with, it is not reflexive for any integer.(c)This is an equivalence that divides the non-zero rational numbers into positive and negative. It is reflexive since x˙x>0. It is symmetric sincexy˙= yx˙. It is transitive since any two members of the given class satisfy the relationship.5Chap. 2 Mathematical Preliminaries(d)This is not an equivalance relation since it is not symmetric. For example, a=1and b=2.(e)This is an eqivalance relation that divides the rationals based on their fractional values. It is reflexive since for all a,=0. It is symmetricsince if=xthen=.x. It is transitive since any two rationalswith the same fractional value will yeild an integer.(f)This is not an equivalance relation since it is not transitive. For example, 4.2=2and 2.0=2,but 4.0=4.A relation is a partial ordering if it is antisymmetric and transitive.(a)Not a partial ordering because it is not transitive.(b)Is a partial ordering bacause it is antisymmetric (if ais an ancestor ofb, then bcannot be an ancestor of a) and transitive (since the ancestorof an ancestor is an ancestor).(c)Is a partial ordering bacause it is antisymmetric (if ais older than b,then bcannot be older than a) and transitive (since if ais older than band bis older than c, ais older than c).(d)Not a partial ordering, since it is not antisymmetric for any pair of sisters.(e)Not a partial ordering because it is not antisymmetric.(f)This is a partial ordering. It is antisymmetric (no violations exist) and transitive (no violations exist).A total ordering can be viewed as a permuation of the elements. Since there are n!permuations of nelements, there must be n!total orderings.This proposed ADT is inspired by the list ADT of Chapter 4.void clear();void insert(int);void remove(int);void sizeof();bool isEmpty();bool isInSet(int);This proposed ADT is inspired by the list ADT of Chapter 4. Note that while it is similiar to the operations proposed for Question , the behaviour is somewhat different.void clear();void insert(int);void remove(int);void sizeof();7bool isEmpty();long ifact(int n) {The iterative version requires careful examination to understand whatit does, or to have confidence that it works as claimed.(b)Fibr is so much slower than Fibi because Fibr re-computes thebulk of the series twice to get the two values to add. What is muchworse, the recursive calls to compute the subexpressions also re-computethe bulk of the series, and do so recursively. The result is an exponential explosion. In contrast, Fibicomputes each value in the seriesexactly once, and so its running time is proportional to n.void GenTOH(int n, POLE goal, POLE t1, POLE t2,POLE* curr) {if (curr[n] == goal) Put others on t1.GenTOH(n-1, t1, goal, t2, curr);move(t2, goal);GenTOH(n-1, goal, t1, t2, curr); In theory, this series approaches, but never reaches, 0, so it will go on forever. In practice, the value should become computationally indistinguishable from zero, and terminate. However, this is terrible programming practice.Chap. 2 Mathematical Preliminariesvoid allpermute(int array[], int n, int currpos) {if (currpos == (n-1)} {printout(array);return;}for (int i=currpos; i<n; i++) {swap(array, currpos, i);allpermute(array, n, currpos+1);swap(array, currpos, i); The idea is the print out theelements at the indicated bit positions within the set. If we do this for values in the range 0 to 2n.1, we will get the entire powerset.void powerset(int n) {for (int i=0; i<ipow(2, n); i++) {for (int j=0; j<n; j++)if (bitposition(n, j) == 1) cout << j << " ";cout << endl;}Proof: Assume that there is a largest prime number. Call it Pn,the nth largest prime number, and label all of the primes in order P1 =2, P2 =3,and so on. Now, consider the number Cformed by multiplying all of the nprime numbers together. The value C+1is not divisible by any of the nprime numbers. C+1is a prime number larger than Pn, a contradiction.Thus, we conclude that there is no largest prime number. .Note: This problem is harder than most sophomore level students can handle. √Proof: The proof is by contradiction. Assume that 2is rational. By definition,there exist integers pand qsuch that√p2=,qwhere pand qhave no common factors (that is, the fraction p/qis in lowestterms). By squaring both sides and doing some simple algebraic manipulation, we get2p2=2q222q= pSince p2 must be even, pmust be even. Thus,9222q=4(p)222q=2(p)2This implies that q2 is also even. Thus, pand qare both even, which contra√dicts the requirement that pand qhave no common factors. Thus, 2mustbe irrational. .The leftmost summation sums the integers from 1 to n. The second summation merely reverses this order, summing the numbers from n.1+1=ndown to n.n+1=1. The third summation has a variable substitution ofi, with a corresponding substitution in the summation bounds. Thus,it is also the summation of n.0=n.(n.1)=1.Proof:(a) Base case.For n=1, 12 = [2(1)3 +3(1)2 +1]/6=1. Thus, the formula is correct for the base case. (b) Induction Hypothesis.2(n.1)3 +3(n.1)2 +(n.1)i2 =.6i=1(c) Induction Step.i2 i2 +n2=i=1 i=12(n.1)3 +3(n.1)2 +(n.2=+n62n3 .6n2 +6n.2+3n2 .6n+3+n.1 2=+n62n3 +3n2 +n=.6Thus, the theorem is proved by mathematical induction. .Proof:(a) Base case.For n=1, 1/2=1.1/2=1/2. Thus, the formula iscorrect for the base case.(b) Induction Hypothesis.11=1.2 i=1Chap. 2 Mathematical Preliminaries(c) Induction Step.1 11=+iin222i=1 i=111=1.+n221=1..n2Thus, the theorem is proved by mathematical induction. . Proof:(a) Base case. For n=0, 20 =21 .1=1. Thus, the formula is correctfor the base case.(b) Induction Hypothesis.2i=2n.1.i=0(c) Induction Step.2i=2i+2ni=0 i=0n=2n.1+2n+1 .1=2.Thus, the theorem is proved by mathematical induction. .The closed form solution is 3n+, which I deduced by noting that 3F (n).2n+1 .3F(n)=2F(n)=3. Now, to verify that this is correct, use mathematical induction as follows.For the base case, F(1)=3= .The induction hypothesis is that =(3n.3)/2.i=1So,3i=3i+3ni=1 i=13n.3n= +32n+1 .33= .2Thus, the theorem is proved by mathematical induction.11nTheorem (2i)=n2 +n.i=1(a) Proof: We know from Example that the sum of the first noddnumbers is ith even number is simply one greater than the ithodd number. Since we are adding nsuch numbers, the sum must be n greater, or n2 +n. .(b) Proof: Base case: n=1yields 2=12 +1, which is true.Induction Hypothesis:2i=(n.1)2 +(n.1).i=1Induction Step: The sum of the first neven numbers is simply the sum of the first n.1even numbers plus the nth even number.2i=( 2i)+2ni=1 i=1=(n.1)2 +(n.1)+2n=(n2 .2n+1)+(n.1)+2n= n2 .n+2n= n2 +n.nThus, by mathematical induction, 2i=n2 +n. .i=1Proof:52Base case. For n=1,Fib(1) = 1 <n=2,Fib(2) = 1 <(5).3Thus, the formula is correct for the base case. Induction Hypothesis. For all positive integers i<n, 5 iFib(i)<().3Induction Step. Fib(n)=Fib(n.1)+Fib(n.2)and, by the InductionHypothesis, Fib(n.1)<(5) and Fib(n.2)<(5)3355Fib(n) < () +() 3355 5 <() +() 333Chap. 2 Mathematical Preliminaries85= ()3355<()2()33n5= .3Thus, the theorem is proved by mathematical induction. .Proof:12(1+1)23 =(a) Base case. For n=1, 1=1. Thus, the formula is correct4for the base case.(b) Induction Hypothesis.22(n1)ni3 = .4i=0(c) Induction Step. n2(n.1)n2i33=+n4i=02n4 .2n3 +n3=+n4n4 +2n3 +n2=4n2(n2 +2n+2)=2n2(n+1)=4Thus, the theorem is proved by mathematical induction..(a) Proof: By contradiction. Assume that the theorem is false. Then, each pigeonhole contains at most 1 pigeon. Since there are nholes, there isroom for only npigeons. This contradicts the fact that a total of n+1pigeons are within the nholes. Thus, the theorem must be correct. .(b) Proof:i. Base case.For one pigeon hole and two pigeons, there must betwo pigeons in the hole.ii. Induction Hypothesis.For npigeons in n.1holes, some holemust contain at least two pigeons.13iii. Induction Step. Consider the case where n+1pigeons are in nholes. Eliminate one hole at random. If it contains one pigeon, eliminate it as well, and by the induction hypothesis some other hole must contain at least two pigeons. If it contains no pigeons, then again by the induction hypothesis some other hole must contain at least two pigeons (with an extra pigeon yet to be placed). Ifit contains more than one pigeon, then it fits the requirements of the theorem directly..(a)When we add the nth line, we create nnew regions. But, we startwith one region even when there are no lines. Thus, the recurrence is F(n)=F(n.1)+n+1.(b) This is equivalent to the summation F(n)=1+ i=1 ni.(c) This is close to a summation we already know (equation .Base case: T(n.1)=1=1(1+1)/2.Induction hypothesis: T(n.1)=(n.1)(n)/2.Induction step:T(n)= T(n.1)+n=(n1)(n)/2+n= n(n+1)/2.Thus, the theorem is proved by mathematical induction.If we expand the recurrence, we getT(n)=2T(n.1)+1=2(2T(n.2)+1)+1)=4T(n.2+2+1.Expanding again yieldsT(n)=8T(n.3)+4+2+1.From this, we can deduce a pattern and hypothesize that the recurrence is equivalent tonT(n)= .12i=2n.1.i=0To prove this formula is in fact the proper closed form solution, we use mathematicalinduction.Base case: T(1)=21 .1=1.14Chap. 2 Mathematical PreliminariesInduction hypothesis: T(n.1)= .1.Induction step:T(n)=2T(n.1)+1= 2 .1) + 1=2n.1.Thus, as proved by mathematical induction, this formula is indeed the correct closed form solution for the recurrence.(a)The probability is for each choice.(b)The average number of “1” bits is n/2, since each position hasprobability of being “1.”(c)The leftmost “1” will be the leftmost bit (call it position 0) with probability; in position 1 with probability , and so on. The numberof positions we must examine is 1 in the case where the leftmost “1” isin position 0; 2 when it is in position 1, and so on. Thus, the expectedcost is the value of the summationni.2ii=1The closed form for this summation is 2 .n+2, or just less than two.2nThus, we expect to visit on average just less than two positions. (Studentsat this point will probably not be able to solve this summation,and it is not given in the book.)There are at least two ways to approach this problem. One is to estimate the volume directly. The second is to generate volume as a function of weight. This is especially easy if using the metric system, assuming that the human body is roughly the density of water. So a 50 Kilo person has a volume slightly less than 50 liters; a 160 pound person has a volume slightly less than 20 gallons.(a) Image representations vary considerably, so the answer will vary as a result. One example answer is: Consider VGA standard size, full-color(24 bit) images, which is 3 ×640 ×480, or just less than 1 Mbyte perimage. The full database requires some 30-35 CDs.(b)Since we needed 30-35 CDs before, compressing by a factor of 10 isnot sufficient to get the database onto one CD.[Note that if the student picked a smaller format, such as estimating the size of a “typical” gif image, the result might well fit onto a single CD.](I saw this problem in John Bentley’s Programming Pearls.) Approach 1:The model is Depth X Width X Flow where Depth and Width are in milesand Flow is in miles/day. The Mississippi river at its mouth is about 1/4 mile wide and 100 feet (1/50 mile) deep, with a flow of around 15 miles/hour =360 miles/day. Thus, the flow is about 2 cubic miles/day.Approach 2: What goes out must equal what goes in. The model is Area X Rainfall where Area is in square miles and Rainfall is in (linear) miles/day.The Mississipi watershed is about 1000 X 1000 miles, and the average rainfalis about 40 inches/year ≈.1 inches/day ≈.000002 miles/day (2 X .Thus, the flow is about 2 cubic miles/day.Note that the student should NOT be providing answers that look like they were done using a calculator. This is supposed to be an exercise in estimation! The amount of the mortgage is irrelevant, since this is a question about rates. However, to give some numbers to help you visualize the problem, pick a $100,000 mortgage. The up-front charge would be $1,000, and the savings would be 1/4% each payment over the life of the mortgage. The monthly charge will be on the remaining principle, being the highest at first and gradually reducing over time. But, that has little effect for the first few years.At the grossest approximation, you paid 1% to start and will save 1/4% each year, requiring 4 years. To be more precise, 8% of $100,000 is $8,000, while7 3/4% is $7,750 (for the first year), with a little less interest paid (and therefore saved) in following years. This will require a payback period of slightlyover 4 years to save $1000. If the money had been invested, then in 5 yearsthe investment would be worth about $1300 (at 5would be close to 5 1/2 years.Disk drive seek time is somewhere around 10 milliseconds or a little lessin 2000. RAM memory requires around 50 nanoseconds – much less thana microsecond. Given that there are about 30 million seconds in a year, a machine capable of executing at 100 MIPS would execute about 3 billion billion (3 .1018) instructions in a year.Typical books have around 500 pages/inch of thickness, so one million pages requires 2000 inches or 150-200 feet of bookshelf. This would be in excess of 50 typical shelves, or 10-20 bookshelves. It is within the realm of possibilitythat an individual home has this many books, but it is rather unusual.A typical page has around 400 words (best way to derive this is to estimate the number of words/line and lines/page), and the book has around 500 pages, so the total is around 200,000 words.16Chap. 2 Mathematical PreliminariesAn hour has 3600 seconds, so one million seconds is a bit less than 300 hours.A good estimater will notice that 3600 is about 10% greater than 3333, so the actual number of hours is about 10% less than 300, or close to 270. (The real value is just under 278). Of course, this is just over 11 days.Well over 100,000, depending on what you wish to classify as a city or town. The real question is what technique the student uses.(a) The time required is 1 minute for the first mile, then 60/59 minutesfor the second mile, and so on until the last mile requires 60/1=60 minutes. The result is the following summation.60 6060/i=60 1/i=60H60.i=1 i=1(b)This is actually quite easy. The man will never reach his destination,since his speed approaches zero as he approaches the end of the journey.3Algorithm AnalysisNote that nis a positive integer.5nlog nis most efficient for n=1.2nis most efficient when 2 ≤n≤4.10nis most efficient for all n>5. 20nand 2nare never moreefficient than the other choices.Both log3 nand log2 nwill have value 0 when n=1. Otherwise, 2 is the most efficient expression for all n>1. 2/32 3n2 log3nlog2 nn20n4nn!.(a)n+6 inputs (an additive amount, independent of n). (b)8ninputs (a multiplicative factor).(c)64ninputs.100n.10n.√About (actually, 3 100n).n+6.(a)These questions are quite hard. If f(n)=2n= x, then f(2n)=22n2(2n)2 = x.(b)The answer is 2(nlog2 3). Extending from part (a), we need some way tomake the growth rate even higher. In particular, we seek some way tolog2 3 =make the exponent go up by a factor of 3. Note that, if f(n)= n)=2log2 3log2 3 =3x y, then f(2nn. So, we combine this observationwith part (a) to get the desired answer.First, we need to find constants cand nosuch that 1 ≤c×1 for n>n0.This is true for any positive value c<1 and any positive value of n0 (since nplays no role in the equation).Next, we need to find constants cand n0 such that 1 ≤c×nfor n>n0.This is true for, say, c=1 and n0 =1.1718Chap. 3 Algorithm AnalysisOther values for n0 and care possible than what is given here.(a)The upper bound is O(n) for n0 >0 and c= c1. The lower bound is Ω(n) for n0 >0 and c= c1.(b)The upper bound is O(n3) for n0 >c3 and c= c2 +1. The lowerbound is Ω(n3) for n0 >c3 and c= c2.(c)The upper bound is O(nlog n) for n0 >c5 and c= c4 +1. The lower bound is Ω(nlog n) for n0 >c5 and c= c4.(d)The upper bound is O(2n) for n0 >c7100 and c= c6 +lower bound is Ω(2n) for n0 >c7100 and c= c6. (100 is used forconvenience to insure that 2n>n6)(a) f(n)=Θ(g(n)) since log n2 = 2 log n.(b)f(n) is in Ω(g(n)) since ncgrows faster than log ncfor any c.(c)f(n) is in Ω(g(n)). Dividing both sides by log n, we see that log n grows faster than 1.(d)f(n) is in Ω(g(n)). If we take both f(n) and g(n) as exponents for 2, 2we get 2non one side and 2log2 n=(2log n)2 = n2 on the other, and ngrows slower than 2n.(e)f(n) is in Ω(g(n)). Dividing both sides by log nand throwing away the low order terms, we see that ngrows faster than 1.(f)。

数据结构与算法分析课后习题答案

数据结构与算法分析课后习题答案

数据结构与算法分析课后习题答案【篇一:《数据结构与算法》课后习题答案】>2.3.2 判断题2.顺序存储的线性表可以按序号随机存取。

(√)4.线性表中的元素可以是各种各样的,但同一线性表中的数据元素具有相同的特性,因此属于同一数据对象。

(√)6.在线性表的链式存储结构中,逻辑上相邻的元素在物理位置上不一定相邻。

(√)8.在线性表的顺序存储结构中,插入和删除时移动元素的个数与该元素的位置有关。

(√)9.线性表的链式存储结构是用一组任意的存储单元来存储线性表中数据元素的。

(√)2.3.3 算法设计题1.设线性表存放在向量a[arrsize]的前elenum个分量中,且递增有序。

试写一算法,将x 插入到线性表的适当位置上,以保持线性表的有序性,并且分析算法的时间复杂度。

【提示】直接用题目中所给定的数据结构(顺序存储的思想是用物理上的相邻表示逻辑上的相邻,不一定将向量和表示线性表长度的变量封装成一个结构体),因为是顺序存储,分配的存储空间是固定大小的,所以首先确定是否还有存储空间,若有,则根据原线性表中元素的有序性,来确定插入元素的插入位置,后面的元素为它让出位置,(也可以从高下标端开始一边比较,一边移位)然后插入x ,最后修改表示表长的变量。

int insert (datatype a[],int *elenum,datatype x) /*设elenum为表的最大下标*/ {if (*elenum==arrsize-1) return 0; /*表已满,无法插入*/else {i=*elenum;while (i=0 a[i]x)/*边找位置边移动*/{a[i+1]=a[i];i--;}a[i+1]=x;/*找到的位置是插入位的下一位*/ (*elenum)++;return 1;/*插入成功*/}}时间复杂度为o(n)。

2.已知一顺序表a,其元素值非递减有序排列,编写一个算法删除顺序表中多余的值相同的元素。

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

数据结构与算法分析
实验三
班级:软件工程0901
姓名:邓佳欣
学号:U200917815
日期:2010/12/27
实验四构造树与遍历树
构造树
一、实验描述:
给出一棵二叉树的先序(或后序)遍历结果,以及中序遍历结果,如何构造这棵树?假定遍历结果以数组方式输入,请写出相应函数,判断是否存在生成同样遍历结果的树,如果存在,构造这棵树。

二、实验设计
1、要在给出的中序遍历序列中,找到先序遍历序列中的第一个元素,即,树根
(命名为树根1)。

2、经步骤1后,中序遍历序列中,树根1前所有元素是此树根的左子树,后面
的元素组成树根1的右子树。

3、递归调用函数构造树根1的左子树,以先序遍历序列的第二个元素为树根(命
名为树根2),在树根1的左子树中元素中寻找,则树根2前面的元素为树根2的左子树,后面的元素是树根2的右子树。

递归调用函数构造树根1的右子树,以树根1后面的元素为树根(命名为树根3),在树根1的右子树中元素中寻找,则树根3前面的元素为树根3的左子树,后面的元素是树根3的右子树。

4、不断构造子树,直到构造完成树叶。

Best case
树只有右子树,即先序的头结点也是中序的头结点。

递归调用+1次查找。

T(n) = T(n-1) + O(1)
复杂度为O(N)
Worse case
树只有左子树,即先序的头结点是中序的最后一个元素,每次查找要比较所有元素。

T(n) = T(n-1) + O(n)
复杂度为=O(N2)
Balance case 左右子树均有(平衡树)
T(n) = 2T(n/2) + O(n)
复杂度为O(nlogN)
三、实验实现过程:··
1. 定义clock_t变量start和end,用于记录函数执行前后的时间。

2. 用ConstructTree(char *a, char *b, int n),分别构造n = 1 ~ 20的best case ,worse case,balance case树,计算重复1000000次。

char *a char*b 分别为先序遍历,中序遍历序列的指针。

N为数组的长度
/trivial case
if( n == 0 )
return NULL;
root->left = CreateTree(a+1, b, num); 构造树根的左子树
root->right = CreateTree(a+num+1, b+num+1, n-num-1); 构造树根的右子树3.在函数执行前,加上代码:start=clock(); 函数执行后,加上代码:end=clock();
得到函数执行前的时间和执行后的时间。

5.time=(double)(end-start)/CLOCKS_PER_SEC,得到运行时间time,将该函数所得结果以及执行时间time打印在命令行中。

6.将执行时间的平均数据输入到Excel中,生成坐标图,横坐标为k,纵坐标为函数执行1,000,000次所需的时间。

四、实验结果:
坐标图如下:
五、实验结论:
由图像,并没有得出和分析一样的实验结论。

对于worse case没有很明显的成指数增加。

猜想可能由于比较长度较短所致,没有得出更加明显的实验结论。

而对于best case,图像很好的证明了我们的分析是正确。

时间复杂度符合O(N)。

测试过程中,如果循环10,000,000 在长度N=7时便会出现死机的情况,分析原因,可能是内存不够导致实验无法正常进行下去;经改正,在每次循环后用free释放内存,问题得到解决,提醒我们在以后的实验中要注意内存的使用问题。

二叉树的层序遍历
一、实验描述:使用队列作为辅助存储,按树的结点的深度,从根开始依次访问所有结点。

二、实验设计:
1.层序遍历,要求树根先入队列,再将它的左子树和右子树排入队列,打印树
根;再将左子树的左右子树插入,右子树的左右子树插入,以此递归,直到树叶。

2.对于队列,用front和rear表示队列的两端,size表示队列中元素的个数。

3.采用队列的形式,对于队列来讲,会有队列满了的情况。

根据书上介绍的方
法,只要front或rear达到数组尾端,让它绕回开头即可。

4.关于判断队列是否为满。

书上介绍的方法是,1)当队列为满时rear = front-1
2)利用size ,每插入一个元素,size+1
,反之size-1; 上课时候老师介绍了一种模除的方法,计算长度 ((front - rear ) + MAXQSIZE ) % MAXQSIZE
方法很巧妙,当且仅当上式=1时,即front – rear = 1 队列为满,满足上述分析。

其他时候,此式均不等于1,队列不满。

5. 关于判断为空。

初始化rear = front ,队列为空。

6. 书上利用结构体中的size 可判断队列是否为空,
三、 实验实现过程: 定义结构体 queue {
Int rear ; Int front ; Int size ; };
Enqueue(element x,queue q) Rear 后移1 Size+1
Dequeue(element x,queue q) Front 后移1 Size+1
Isempty( queue q) Isfull(queue q) Paint(node)
将树根插入队列,打印树根,再将它的左子树和右子树,插入队列
四、:实验结果
Rear front
实验结果正确
五、实验分析
层序遍历的时间复杂程度与树的高度成线性关系,即O(logN)
这次实验没有涉及序列,计算时间,画出时间图,以后有时间,将进行验证。

相关文档
最新文档