算法设计与分析9

合集下载

算法设计与分析复习题目及答案详解

算法设计与分析复习题目及答案详解

算法设计与分析复习题目及答案详解分治法1、二分搜索算法是利用(分治策略)实现的算法。

9.实现循环赛日程表利用的算法是(分治策略)27、Straen矩阵乘法是利用(分治策略)实现的算法。

34.实现合并排序利用的算法是(分治策略)。

实现大整数的乘法是利用的算法(分治策略)。

17.实现棋盘覆盖算法利用的算法是(分治法)。

29、使用分治法求解不需要满足的条件是(子问题必须是一样的)。

不可以使用分治法求解的是(0/1背包问题)。

动态规划下列不是动态规划算法基本步骤的是(构造最优解)下列是动态规划算法基本要素的是(子问题重叠性质)。

下列算法中通常以自底向上的方式求解最优解的是(动态规划法)备忘录方法是那种算法的变形。

(动态规划法)最长公共子序列算法利用的算法是(动态规划法)。

矩阵连乘问题的算法可由(动态规划算法B)设计实现。

实现最大子段和利用的算法是(动态规划法)。

贪心算法能解决的问题:单源最短路径问题,最小花费生成树问题,背包问题,活动安排问题,不能解决的问题:N皇后问题,0/1背包问题是贪心算法的基本要素的是(贪心选择性质和最优子结构性质)。

回溯法回溯法解旅行售货员问题时的解空间树是(排列树)。

剪枝函数是回溯法中为避免无效搜索采取的策略回溯法的效率不依赖于下列哪些因素(确定解空间的时间)分支限界法最大效益优先是(分支界限法)的一搜索方式。

分支限界法解最大团问题时,活结点表的组织形式是(最大堆)。

分支限界法解旅行售货员问题时,活结点表的组织形式是(最小堆)优先队列式分支限界法选取扩展结点的原则是(结点的优先级)在对问题的解空间树进行搜索的方法中,一个活结点最多有一次机会成为活结点的是(分支限界法).从活结点表中选择下一个扩展结点的不同方式将导致不同的分支限界法,以下除(栈式分支限界法)之外都是最常见的方式.(1)队列式(FIFO)分支限界法:按照队列先进先出(FIFO)原则选取下一个节点为扩展节点。

(2)优先队列式分支限界法:按照优先队列中规定的优先级选取优先级最高的节点成为当前扩展节点。

算法设计与分析_王红梅_课后答案网(部分)

算法设计与分析_王红梅_课后答案网(部分)

第六章动态规划法• P137 2 ,3, 4•2.解答:cost[i]表示从顶点i 到终点n-1 的最短路径,path[i]表示从顶点i 到终点n-1 的路径上顶点i 的下一个顶点。

cost[i]=min{cij+cost[j]}3 有5 个物品,其重量分别是{3, 2, 1, 4,5},价值分别为{25, 20, 15, 40, 50},背包的容量为6。

V[i][j]表示把前i 个物品装入容量为j 的背包中获得的最大价值。

最优解为(0,0,1,0,1)最优值为65. 4.序列A =(x, z , y , z , z , y,x ),B =(z , x , y , y , z , x , z ),建立两个(m+1)×(n+1)的二 维表L 和表S ,分别存放搜索过程中得到的子序列的长度和状态。

z , x , y , y , z,x , z )path[i]= 使 cij+cost[j] 最小的 j i 012345678 9 10 11 12 13 14 15 Cost[i] 18 13 16 13 10 9 12 7 6875943Path[i]145778911 11 11 13 14 14 15 15 0得到最短路径 0->1->4->7->11->14->15 , 长度为 18(a)长度矩阵L(b)状态矩阵S 。

第七章贪心算法2.背包问题:有7 个物品,背包容量W=15。

将给定物品按单位重量价值从大到小排序,结果如下:个物品,物品重量存放在数组w[n]中,价值存放在数组放在数组x[n]中。

按算法7.6——背包问题1.改变数组w 和v 的排列顺序,使其按单位重量价值v[i]/w[i]降序排列;2.将数组x[n]初始化为0;//初始化解向量3.i=1;4.循环直到( w[i]>C )4.1 x[i]=1; //将第i个物品放入背包4.2 C=C-w[i];4.3 i++;5. x[i]=C/w[i];得出,该背包问题的求解过程为:: x[1]=1;c=15-1=14 v=6 x[2]=1; c=14-2=12V=6+10=10 x[3]=1; c=12-4=8V=16+18=34 x[4]=1; c=8-5=3V=34+15=49 x[5]=1; c=3-1=2 V=49+3=52x[6]=2/3 ; c=0; V=52+5*2/3=156/3 最优值为156/3 最优解为(1,1,1,1,1,2/3,0)) (x[i]按排序后物品的顺序构造)5.可以将该问题抽象为图的着色问题,活动抽象为顶点,不相容的活动用边相连(也可以将该问题理解为最大相容子集问题,重复查找剩余活动的最大相容子集,子集个数为所求).具体参见算法7.3 算法7.3——图着色问题1.color[1]=1; //顶点1着颜色12.for (i=2; i<=n; i++) //其他所有顶点置未着色状态color[i]=0;3.k=0;4.循环直到所有顶点均着色4.1k++; //取下一个颜色4.2for (i=2; i<=n; i++) //用颜色k 为尽量多的顶点着色4.2.1 若顶点i已着色,则转步骤4.2,考虑下一个顶点;4.2.2 若图中与顶点i邻接的顶点着色与顶点i着颜色k 不冲突,则color[i]=k;5.输出k;第八章回溯法4.搜索空间(a) 一个无向图(b) 回溯法搜索空间最优解为(1,2,1,2,3)5.0-1 背包问题n∑w i x i≤c 1• 可行性约束函数:i =1• 上界函数:nr =∑Vi5 = 3A B *CD8 ** * 131 =12 =23 = 14 = 2 34215课后答案网()i=k+1 1第九章分支限界法5,解:应用贪心法求得近似解:(1,4,2,3),其路径代价为:3+5+7+6=21,这可以作为该问题的上界。

电大计算机本科_算法设计与分析

电大计算机本科_算法设计与分析

电大计算机本科_算法设计与分析
算法设计与分析是计算机科学和数学领域的重要课程。

它涉及到一系
列算法设计、分析和实现的方面,涉及到算法流程、语法、数据结构等多
方面。

在算法设计与分析这门课程中,学生首先要学习怎么设计一个算法,
怎么从实际问题中提取算法,怎么分析算法复杂度,怎么评价算法效率。

接下来要学习算法,基本排序算法和选择算法,分治算法,贪婪算法,动
态规划,回溯算法,朴素贝叶斯,马尔科夫链等等各种算法。

学生还要熟
悉现代算法建模工具(如Matlab、SAS、C++),熟悉算法的优化技巧,
掌握算法的编码实现方法,并研究其实际应用。

本课程可以使学生充分发挥自己的能力,培养学生的算法设计能力,
提高实践能力,掌握算法的基本原理及运用,把握算法分析及其优化技术。

它不仅帮助学生提高数学思维能力,同时也有助于他们在计算机编程方面
的能力。

学习算法设计与分析有助于学生全面掌握算法设计这一重要组成
部分,也可以拓展学生的应用领域,使学生更具有竞争力。

学习算法设计与分析也有其困难之处,首先是算法编程比较抽象,学
生需要有较强的理论功底和数学能力。

《算法设计与分析》(全)

《算法设计与分析》(全)
巢湖学院计算机科学与技术系
1.1、算法与程序
程序:是算法用某种程序设计语言的具体实现。 程序可以不满足算法的性质(4)。 例如操作系统,是一个在无限循环中执行的程序, 因而不是一个算法。 操作系统的各种任务可看成是单独的问题,每一个 问题由操作系统中的一个子程序通过特定的算法来实 现。该子程序得到输出结果后便终止。
渐近分析记号的若干性质
(1)传递性: ➢ f(n)= (g(n)), g(n)= (h(n)) f(n)= (h(n)); ➢ f(n)= O(g(n)), g(n)= O (h(n)) f(n)= O (h(n)); ➢ f(n)= (g(n)), g(n)= (h(n)) f(n)= (h(n)); ➢ f(n)= o(g(n)), g(n)= o(h(n)) f(n)= o(h(n)); ➢ f(n)= (g(n)), g(n)= (h(n)) f(n)= (h(n)); (2)反身性: ➢ f(n)= (f(n));f(n)= O(f(n));f(n)= (f(n)). (3)对称性: ➢ f(n)= (g(n)) g(n)= (f(n)) . (4)互对称性: ➢ f(n)= O(g(n)) g(n)= (f(n)) ; ➢ f(n)= o(g(n)) g(n)= (f(n)) ;
巢湖学院计算机科学与技术系
渐近分析记号的若干性质
规则O(f(n))+O(g(n)) = O(max{f(n),g(n)}) 的证明: ➢ 对于任意f1(n) O(f(n)) ,存在正常数c1和自然数n1,使得对
所有n n1,有f1(n) c1f(n) 。 ➢ 类似地,对于任意g1(n) O(g(n)) ,存在正常数c2和自然数
巢湖学院计算机科学与技术系
第1章 算法引论

算法设计与分析课后习题

算法设计与分析课后习题

第一章1. 算法分析题算法分析题1-1 求下列函数的渐进表达式(1). 3n^2 + 10n < 3n^2 + 10n^2 = 13n^2 = O(n^2)(2). n^2 / 10 + 2^n当n>5是,n^2 〈2 ^n所以,当n >= 1时,n^2/10 〈2 ^n故:n^2/10 + 2^n < 2 ^n + 2^n = 2*2^n = O(2^n)(3). 21 + 1/n < 21 + 1 = 22 = O(1)(4). log(n^3)=3log(n)=O(log(n))(5). 10log(3^n)= (10log3)n = O(n)算法分析题1—6(1)因为:f(n)=log(n^2) = 2log(n); g(n) = log(n) + 5所以:f(n)=Θ(log(n)+5)=Θ(g(n))(2)因为:log(n) 〈√n ; f(n)= 2log(n);g(n)=√n所以:f(n)= O(g(n))(3)因为:log(n)< n;f(n) = n;g(n) = log(n^2) = 2log(n)所以;f(n)= Ω(g(n))(4)因为:f(n) = nlogn +n; g(n) = logn所以:f(n) =Ω(g(n))(5)因为: f(n)= 10;g(n) = log(10)所以:f(n)=Θ(g(n))(6)因为: f(n)=log^2(n);g(n)= log(n)所以:f(n) ==Ω(g(n))(7)因为: f(n) = 2^n < 100*2^n; g(n)=100n^2; 2^n > n ^2所以:f(n)= Ω(g(n))(8)因为:f(n)= 2^n; g(n)= 3 ^n;2 ^n 〈3 ^n所以:f(n)= O(g(n))习题1-9 证明:如果一个算法在平均情况下的计算时间复杂性为Θ(f(n)),该算法在最坏情况下所需的计算时间为Ω(f(n)).分析与解答:因此,Tmax(N) = Ω(Tavg(N)) = Ω(Θ(f(n)))=Ω(f(n))。

算法设计与分析

算法设计与分析

算法设计与分析算法是计算机科学中的核心概念,它是解决问题的一系列步骤和规则的有序集合。

在计算机科学的发展中,算法设计和分析扮演着至关重要的角色。

本文将探讨算法设计和分析的相关概念、技术和重要性。

一、算法设计的基本原则在设计算法时,需要遵循一些基本原则来确保其正确性和有效性:1. 正确性:算法设计应确保能够正确地解决给定的问题,即输出与预期结果一致。

2. 可读性:设计的算法应具有清晰的结构和逻辑,易于理解和维护。

3. 高效性:算法应尽可能地减少时间和空间复杂度,以提高执行效率。

4. 可扩展性:算法应具备良好的扩展性,能够适应问题规模的变化和增长。

5. 可靠性:设计的算法应具备稳定性和鲁棒性,对不同的输入都能给出正确的结果。

二、常见的算法设计技术1. 枚举法:按照规定的顺序逐个尝试所有可能的解,直到找到满足条件的解。

2. 递归法:通过将一个大问题分解成若干个小问题,并通过递归地解决小问题,最终解决整个问题。

3. 贪心算法:在每个阶段选择最优解,以期望通过一系列局部最优解达到全局最优解。

4. 分治算法:将一个大问题划分成多个相互独立的子问题,逐个解决子问题,并将解合并得到整体解。

5. 动态规划:通过将一个大问题分解成多个小问题,并存储已解决子问题的结果,避免重复计算。

三、算法分析的重要性算法分析可以评估算法的效率和性能。

通过算法分析,可以:1. 预测算法在不同规模问题上的表现,帮助选择合适的算法解决具体问题。

2. 比较不同算法在同一问题上的性能,从而选择最优的算法。

3. 评估算法在不同硬件环境和数据集上的表现,选择最适合的算法实现。

四、常见的算法分析方法1. 时间复杂度:衡量算法所需执行时间的增长率,常用的时间复杂度有O(1)、O(log n)、O(n)、O(n log n)和O(n^2)等。

2. 空间复杂度:衡量算法所需占用存储空间的增长率,常用的空间复杂度有O(1)、O(n)和O(n^2)等。

3. 最坏情况分析:对算法在最不利情况下的性能进行分析,可以避免算法性能不稳定的问题。

《算法分析与设计》(李春葆版)课后选择题答案与解析

《算法分析与设计》(李春葆版)课后选择题答案与解析

《算法及其分析》课后选择题答案及详解第1 章——概论1.下列关于算法的说法中正确的有()。

Ⅰ.求解某一类问题的算法是唯一的Ⅱ.算法必须在有限步操作之后停止Ⅲ.算法的每一步操作必须是明确的,不能有歧义或含义模糊Ⅳ.算法执行后一定产生确定的结果A.1个B.2个C.3个D.4个2.T(n)表示当输入规模为n时的算法效率,以下算法效率最优的是()。

A.T(n)=T(n-1)+1,T(1)=1B.T(n)=2nC.T(n)= T(n/2)+1,T(1)=1D.T(n)=3nlog2n答案解析:1.答:由于算法具有有穷性、确定性和输出性,因而Ⅱ、Ⅲ、Ⅳ正确,而解决某一类问题的算法不一定是唯一的。

答案为C。

2.答:选项A的时间复杂度为O(n)。

选项B的时间复杂度为O(n)。

选项C 的时间复杂度为O(log2n)。

选项D的时间复杂度为O(nlog2n)。

答案为C。

第3 章─分治法1.分治法的设计思想是将一个难以直接解决的大问题分割成规模较小的子问题,分别解决子问题,最后将子问题的解组合起来形成原问题的解。

这要求原问题和子问题()。

A.问题规模相同,问题性质相同B.问题规模相同,问题性质不同C.问题规模不同,问题性质相同D.问题规模不同,问题性质不同2.在寻找n个元素中第k小元素问题中,如快速排序算法思想,运用分治算法对n个元素进行划分,如何选择划分基准?下面()答案解释最合理。

A.随机选择一个元素作为划分基准B.取子序列的第一个元素作为划分基准C.用中位数的中位数方法寻找划分基准D.以上皆可行。

但不同方法,算法复杂度上界可能不同3.对于下列二分查找算法,以下正确的是()。

A.intbinarySearch(inta[],intn,int x){intlow=0,high=n-1;while(low<=high){intmid=(low+high)/2;if(x==a[mid])returnmid;if(x>a[mid])low=mid;elsehigh=mid;}return –1;}B.intbinarySearch(inta[],intn,int x) { intlow=0,high=n-1;while(low+1!=high){intmid=(low+high)/2;if(x>=a[mid])low=mid;elsehigh=mid;}if(x==a[low])returnlow;elsereturn –1;}C.intbinarySearch(inta[],intn,intx) { intlow=0,high=n-1;while(low<high-1){intmid=(low+high)/2;if(x<a[mid])high=mid;elselow=mid;}if(x==a[low])returnlow;elsereturn –1;}D.intbinarySearch(inta[],intn,int x) {if(n>0&&x>=a[0]){intlow= 0,high=n-1;while(low<high){intmid=(low+high+1)/2;if(x<a[mid])high=mid-1;elselow=mid;}if(x==a[low])returnlow;}return –1;}答案解析:1.答:C。

算法设计与分析 王红梅 第二版 第9章 分支限界法

算法设计与分析 王红梅 第二版 第9章 分支限界法

6
分支限界法的设计思想
如果某孩子结点的目标函数可能取值超出目标函数的界,则 将其丢弃,因为从这个结点生成的解不会比目前已经得到的 解更好;否则,将其加入待处理结点表(表PT)
依次从表PT中选取使目标函数的值取极值的结点成为当前扩 展结点,重复上述过程,直到找到最优解。
目标函数的界[down, up]的确定
9
分支限界法的设计思想
PT表
2 w=4, v=40 ub=76
1 w=0, v=0 ub=100
3 w=0, v=0 ub=60

w=11 无效解
5 w=4, v=40 ub=70
6 w=9, v=65 ub=69
7 w=4, v=40 ub=64
8
×
w=12
无效解
9 w=9, v=65 ub=65
如TSP问题(图8.6)。
分支限界法
先确定一个合理的限界函数
由限界函数确定目标函数的界[down, up]
仍以穷举法的解空间树为基础,但以广度优先的原理搜 索该结点的所有孩子结点,分别估算这些孩子结点的目 标函数的可能取值
2020/1/12
Branch and Bound Method
2020/1/12
Branch and Bound Method
12
分支限界法的设计思想
在结点7 物品3不装入背包,w=4,v=40,与结点5相同 目标函数值为:ub=40 + (10-4)×4=64 将结点7加入表PT中
在表PT 中选取目标函数值取得极大的结点6 优先进行搜索
在结点8 物品4装入背包,w=12>W, 不满足约束条件,将结点8丢弃;
将结点2加入待处理结点表PT中

算法设计与分析复习题目及答案

算法设计与分析复习题目及答案

分治法1、二分搜索算法是利用(分治策略)实现的算法。

9. 实现循环赛日程表利用的算法是(分治策略)27、Strassen矩阵乘法是利用(分治策略)实现的算法。

34.实现合并排序利用的算法是(分治策略)。

实现大整数的乘法是利用的算法(分治策略)。

17.实现棋盘覆盖算法利用的算法是(分治法)。

29、使用分治法求解不需要满足的条件是(子问题必须是一样的)。

不可以使用分治法求解的是(0/1背包问题)。

动态规划下列不是动态规划算法基本步骤的是(构造最优解)下列是动态规划算法基本要素的是(子问题重叠性质)。

下列算法中通常以自底向上的方式求解最优解的是(动态规划法)备忘录方法是那种算法的变形。

(动态规划法)最长公共子序列算法利用的算法是(动态规划法)。

矩阵连乘问题的算法可由(动态规划算法B)设计实现。

实现最大子段和利用的算法是(动态规划法)。

贪心算法能解决的问题:单源最短路径问题,最小花费生成树问题,背包问题,活动安排问题,不能解决的问题:N皇后问题,0/1背包问题是贪心算法的基本要素的是(贪心选择性质和最优子结构性质)。

回溯法回溯法解旅行售货员问题时的解空间树是(排列树)。

剪枝函数是回溯法中为避免无效搜索采取的策略回溯法的效率不依赖于下列哪些因素(确定解空间的时间)分支限界法最大效益优先是(分支界限法)的一搜索方式。

分支限界法解最大团问题时,活结点表的组织形式是(最大堆)。

分支限界法解旅行售货员问题时,活结点表的组织形式是(最小堆)优先队列式分支限界法选取扩展结点的原则是(结点的优先级)在对问题的解空间树进行搜索的方法中,一个活结点最多有一次机会成为活结点的是( 分支限界法).从活结点表中选择下一个扩展结点的不同方式将导致不同的分支限界法,以下除( 栈式分支限界法)之外都是最常见的方式.(1)队列式(FIFO)分支限界法:按照队列先进先出(FIFO)原则选取下一个节点为扩展节点。

(2)优先队列式分支限界法:按照优先队列中规定的优先级选取优先级最高的节点成为当前扩展节点。

算法分析与设计 第二版 英文版 (潘彦 著) 清华大学出版社 课后答案--solu9

算法分析与设计 第二版 英文版 (潘彦 著) 清华大学出版社 课后答案--solu9

This file contains the exercises,hints,and solutions for Chapter 9of the book ”Introduction to the Design and Analysis of Algorithms,”2nd edition,byA.Levitin.The problems that might be challenging for at least some students are marked by ;those that might be difficult for a majority of students are marked by .Exercises 9.11.Give an instance of the change-making problem for which the greedy al-gorithm does not yield an optimal solution.2.Write a pseudocode of the greedy algorithm for the change-making prob-lem,with an amount n and coin denominations d 1>d 2>...>d m as its input.What is the time efficiency class of your algorithm?3.Consider the problem of scheduling n jobs of known durations t 1,...,t n for execution by a single processor.The jobs can be executed in any order,one job at a time.You want to find a schedule that minimizes the total time spent by all the jobs in the system.(The time spent by one job in the system is the sum of the time spent by this job in waiting plus the time spent on its execution.)Design a greedy algorithm for this problem. Does the greedy algo-rithm always yield an optimal solution?4.Design a greedy algorithm for the assignment problem (see Section 3.4).Does your greedy algorithm always yield an optimal solution?5.Bridge crossing revisited Consider the generalization of the bridge cross-ing puzzle (Problem 2in Exercises 1.2)in which we have n >1people whose bridge crossing times are t 1,t 2,...,t n .All the other conditions of the problem remain the same:at most two people at the time can cross the bridge (and they move with the speed of the slower of the two)and they must carry with them the only flashlight the group has.Design a greedy algorithm for this problem and find how long it willtake to cross the bridge by using this algorithm.Does your algorithm yields a minimum crossing time for every instance of the problem?If it does–prove it,if it does not–find an instance with the smallest number of people for which this happens.6.Bachet-Fibonacci weighing problem Find an optimal set of n weights {w 1,w 2,...,w n }so that it would be possible to weigh on a balance scale any integer load in the largest possible range from 1to W ,provided a. weights can be put only on the free cup of the scale.b. weights can be put on both cups of the scale.1课后答案网 w w w .k h d a w .c o m7.a.Apply Prim’s algorithm to the following graph.Include in the priority queue all the vertices not already in the tree.b.Apply Prim’s algorithm to the following graph.Include in the priority queue only the fringe vertices (the vertices not in the current tree which are adjacent to at least one tree vertex).8.The notion of a minimum spanning tree is applicable to a connected weighted graph.Do we have to check a graph’s connectivity before ap-plying Prim’s algorithm or can the algorithm do it by itself?9.a.How can we use Prim’s algorithm to find a spanning tree of a connected graph with no weights on its edges?b.Is it a good algorithm for this problem?10. Prove that any weighted connected graph with distinct weights hasexactly one minimum spanning tree.11.Outline an efficient algorithm for changing an element’s value in a min-heap.What is the time efficiency of your algorithm?2课后答案网 w h d a w .c o mHints to Exercises 9.11.As coin denominations for your counterexample,you may use,among a multitude of other possibilities,the ones mentioned in the text:d 1=7,d 2=5,d 3=1.2.You may use integer divisions in your algorithm.3.Considering the case of two jobs might help.Of course,after forming a hypothesis,you will have to either prove the algorithm’s optimality for an arbitrary input or find a specific counterexample showing that it is not the case.4.You can apply the greedy approach either to the entire cost matrix or to each of its rows (or columns).5.Simply apply the greedy approach to the situation at hand.You may assume that t 1≤t 2≤...≤t n .6.For both versions of the problem,it is not difficult to get to a hypothesis about the solution’s form after considering the cases of n =1,2,and 3.It is proving the solutions’optimality that is at the heart of this problem.7.a.Trace the algorithm for the graph given.An example can be found in the text of the section.b.After the next fringe vertex is added to the tree,add all the unseen vertices adjacent to it to the priority queue of fringe vertices.8.Applying Prim’s algorithm to a weighted graph that is not connected should help in answering this question.9.a.Since Prim’s algorithm needs weights on a graph’s edges,some weights have to be assigned.b.Do you know other algorithms that can solve this problem?10.Strictly speaking,the wording of the question asks you to prove two things:the fact that at least one minimum spanning tree exists for any weighted connected graph and the fact that a minimum spanning tree is unique if all the weights are distinct numbers.The proof of the former stems from the obvious observation about finiteness of the number of spanning trees for a weighted connected graph.The proof of the latter can be obtained by repeating the correctness proof of Prim’s algorithm with a minor adjustment at the end.11.Consider two cases:the key’s value was decreased (this is the case needed for Prim’s algorithm)and the key’s value was increased.3课后答案网 w w w .k h d a w .c o mSolutions to Exercises 9.11.Here is one of many such instances:For the coin denominations d 1=7,d 2=5,d 3=1and the amount n =10,the greedy algorithm yields one coin of denomination 7and three coins of denomination 1.The actual optimal solution is two coins of denomination 5.2.Algorithm Change (n,D [1..m ])//Implements the greedy algorithm for the change-making problem //Input:A nonnegative integer amount n and//a decreasing array of coin denominations D//Output:Array C [1..m ]of the number of coins of each denomination //in the change or the ”no solution”messagefor i ←1to m doC [i ]← n/D [i ]n ←n mod D [i ]if n =0return Celse return ”no solution”The algorithm’s time efficiency is in Θ(m ).(We assume that integer di-visions take a constant time no matter how big dividends are.)Note also that if we stop the algorithm as soon as the remaining amount becomes 0,the time efficiency will be in O (m ).3.a.Sort the jobs in nondecreasing order of their execution times and exe-cute them in that order.b.Yes,this greedy algorithm always yields an optimal solution.Indeed,for any ordering (i.e.,permutation)of the jobs i 1,i 2,...,i n ,the total time in the system is given by the formula t i 1+(t i 1+t i 2)+...+(t i 1+t i 2+...+t i n )=nt i 1+(n −1)t i 2+...+t i n .Thus,we have a sum of numbers n,n −1,...,1multiplied by “weights”t 1,t 2,...t n assigned to the numbers in some order.To minimize such a sum,we have to assign smaller t ’s to larger numbers.In other words,the jobs should be executed in nondecreasing order of their execution times.Here is a more formal proof of this fact.We will show that if jobs are ex-ecuted in some order i 1,i 2,...,i n ,in which t i k >t i k +1for some k,then the total time in the system for such an ordering can be decreased.(Hence,no such ordering can be an optimal solution.)Let us consider the other job ordering,which is obtained by swapping the jobs k and k +1.Obvi-ously,the time in the systems will remain the same for all but these two 4课后答案网 w w w .k h d a w .c o mjobs.Therefore,the difference between the total time in the system for the new ordering and the one before the swap will be[(k −1j =1t i j +t i k +1)+(k −1j =1t i j +t i k +1+t i k )]−[(k −1j =1t i j +t i k )+(k −1j =1t i j +t i k +t i k +1)]=t i k +1−t i k <0.4.a.The all-matrix version:Repeat the following operation n times.Select the smallest element in the unmarked rows and columns of the cost matrix and then mark its row and column.The row-by-row version:Starting with the first row and ending with the last row of the cost matrix,select the smallest element in that row which is not in a previously marked column.After such an element is selected,mark its column to prevent selecting another element from the same col-umn.b.Neither of the versions always yields an optimal solution.Here isa simple counterexample:C = 122100 5.Repeat the following step n −2times:Send to the other side the pair of two fastest remaining persons and then return the flashlight with the fastest person.Finally,send the remaining two people together.Assuming that t 1≤t 2≤...≤t n ,the total crossing time will be equal to (t 2+t 1)+(t 3+t 1)+...+(t n −1+t 1)+t n =ni =2t i +(n −2)t 1=n i =1t i +(n −3)t 1.Note:For an algorithm that always yields a minimal crossing time,seeGünter Rote,“Crossing the Bridge at Night,”EATCS Bulletin,vol.78(October 2002),241—246.The solution to the instance of Problem 2in Exercises 1.2shows that the greedy algorithm doesn’t always yield the minimal crossing time for n >3.No smaller counterexample can be given as a simple exhaustive check for n =3demonstrates.(The obvious solution for n =2is the one generated by the greedy algorithm as well.)5课后答案网 w w w .kh d a w .c o m6.a.Let’s apply the greedy approach to the first few instances of the problem in question.For n =1,we have to use w 1=1to balance weight 1.For n =2,we simply add w 2=2to balance the first previously unattainable weight of 2.The weights {1,2}can balance every integral weights up to their sum 3.For n =3,in the spirit of greedy thinking,we take the next previously unattainable weight:w 3=4.The three weights {1,2,4}allow to weigh any integral load l between 1and their sum 7,with l ’s binary expansion indicating the weights needed for load l :Generalizing these observations,we should hypothesize that for any posi-tive integer n the set of consecutive powers of 2{w i =2i −1,i =1,2,...n }makes it possible to balance every integral load in the largest possible range,which is up to and including n i =12i −1=2n −1.The fact that every integral weight l in the range 1≤l ≤2n −1can be balanced with this set of weights follows immediately from the binary expansion of l,which yields the weights needed for weighing l.(Note that we can obtain the weights needed for a given load l by applying to it the greedy algorithm for the change-making problem with denominations d i =2i −1,i =1,2,...n.)In order to prove that no set of n weights can cover a larger range of consecutive integral loads,it will suffice to note that there are just 2n −1nonempty selections of n weights and,hence,no more than 2n −1sums they yield.Therefore,the largest range of consecutive integral loads they can cover cannot exceed 2n −1.[Alternatively,to prove that no set of n weights can cover a larger range of consecutive integral loads,we can prove by induction on i that if any mul-tiset of n weights {w i ,i =1,...,n }–which we can assume without loss of generality to be sorted in nondecreasing order–can balance every integral load starting with 1,then w i ≤2i −1for i =1,2,...,n.The basis checks out immediately:w 1must be 1,which is equal to 21−1.For the general case,assume that w k ≤2k −1for every 1≤k <i.The largest weight the first i −1weights can balance is i −1k =1w k ≤ i −1k =12k −1=2i −1−1.If w i were larger than 2i ,then this load could have been balanced neither with the first i −1weights (which are too light even taken together)nor with the weights w i ≤...≤w n (which are heavier than 2i even individ-ually).Hence,w i ≤2i −1,which completes the proof by induction.This immediately implies that no n weights can balance every integral load up to the upper limit larger than n i =1w i ≤ n i =12i −1=2n −1,the limit attainable with the consecutive powers of 2weights.]b.If weights can be put on both cups of the scale,then a larger range can 6课后答案网 w w w .k h d a w .be reached with n weights for n >1.(For n =1,the single weight still needs to be 1,of course.)The weights {1,3}enable weighing of every integral load up to 4;the weights {1,3,9}enable weighing of every inte-gral load up to 13,and,in general,the weights {w i =3i −1,i =1,2,...,n }enable weighing of every integral load up to and including their sum of n i =13i −1=(3n −1)/2.A load’s expansion in the ternary system indicates the weights needed.If the ternary expansion contains only 0’s and 1’s,the load requires putting the weights corresponding to the 1’s on the opposite cup of the balance.If the ternary expansion of load l,l ≤(3n −1)/2,contains one or more 2’s,we can replace each 2by (3-1)to represent it in the form l =n i =1βi 3i −1,where βi ∈{0,1,−1},n = log 3(l +1) .In fact,every positive integer can be uniquely represented in this form,obtained from its ternary expansion as described above.For example,5=123=1·31+2·30=1·31+(3−1)·30=2·31−1·30=(3−1)·31−1·30=1·32−1·31−1·30.(Note that if we start with the rightmost 2,after a simplification,the new rightmost 2,if any,will be at some position to the left of the starting one.This proves that after a finite number of such replacements,we will be able to eliminate all the 2’s.)Using the representation l = n i =1βi 3i −1,we can weigh load l by placing all the weights w i =3i −1for negative βi ’s along with the load on one cup of the scale and all the weights w i =3i −1for positive βi ’s on the opposite cup.Now we’ll prove that no set of n weights can cover a larger range of con-secutive integral loads than (3n −1)/2.Each of the n weights can be either put on the left cup of the scale,or put on the right cup,or not to be used at all.Hence,there are 3n −1possible arrangements of the weights on the scale,with each of them having its mirror image (where all the weights are switched to the opposite pan of the scale).Eliminating this symmetry,leaves us withjust (3n −1)/2arrangements,which can weight at most (3n −1)/2different integral loads.Therefore,the largest range of consecutive integral loads they can cover cannot exceed (3n −1)/2.7.a.Apply Prim’s algorithm to the following graph:7课后答案网 w w w.k h d a w .c o mthe edges ae,eb,ec,and cd.b.Apply Prim’s algorithm to the following graph:the edges ab,be,ed,dc,ef,ei,ij,cg,gh,il,gk.8.There is no need to check the graph’s connectivity because Prim’s algo-rithm can do it itself.If the algorithm reaches all the graph’s vertices (via edges of finite lengths),the graph is connected,otherwise,it is not.9.a.The simplest and most logical solution is to assign all the edge weights to 1.8课a w .c o mb.Applying a depth-first search (or breadth-first search)traversal to get a depth-first search tree (or a breadth-first search tree),is conceptually simpler and for sparse graphs represented by their adjacency lists faster.10.The number of spanning trees for any weighted connected graph is a pos-itive finite number.(At least one spanning tree exists,e.g.,the one obtained by a depth-first search traversal of the graph.And the number of spanning trees must be finite because any such tree comprises a subset of edges of the finite set of edges of the given graph.)Hence,one can always find a spanning tree with the smallest total weight among the finite number of the candidates.Let’s prove now that the minimum spanning tree is unique if all the weights are distinct.We’ll do this by contradiction,i.e.,by assuming that there exists a graph G =(V,E )with all distinct weights but with more than one minimum spanning tree.Let e 1,...,e |V |−1be the list of edges com-posing the minimum spanning tree T P obtained by Prim’s algorithm with some specific vertex as the algorithm’s starting point and let T be an-other minimum spanning tree.Let e i =(v,u )be the first edge in the list e 1,...,e |V |−1of the edges of T P which is not in T (if T P =T ,such edge must exist)and let (v,u )be an edge of T connecting v with a vertex not in the subtree T i −1formed by {e 1,...,e i −1}(if i =1,T i −1consists of vertex v only).Similarly to the proof of Prim’s algorithms correctness,let us replace (v,u )by e i =(v,u )in T .It will create another spanning tree,whose weight is smaller than the weight of T because the weight of e i =(v,u )is smaller than the weight of (v,u ).(Since e i was chosen by Prim’s algorithm,its weight is the smallest among all the weights on the edges connecting the tree vertices of the subtree T i −1and the vertices adjacent to it.And since all the weights are distinct,the weight of (v,u )must be strictly greater than the weight of e i =(v,u ).)This contradicts the assumption that T was a minimum spanning tree.11.If a key’s value in a min-heap was decreased,it may need to be pushedup (via swaps)along the chain of its ancestors until it is smaller than or equal to its parent or reaches the root.If a key’s value in a min-heap was increased,it may need to be pushed down by swaps with the smaller of its current children until it is smaller than or equal to its children or reaches a leaf.Since the height of a min-heap with n nodes is equal to log 2n (by the same reason the height of a max-heap is given by this formula–see Section 6.4),the operation’s efficiency is in O (log n ).(Note:The old value of the key in question need not be known,of paring the new value with that of the parent and,if the min-heap condition holds,with the smaller of the two children,will suffice.)9课后答案网 w w w.k h d a w .c o mExercises 9.21.Apply Kruskal’s algorithm to find a minimum spanning tree of the follow-ing graphs.a.b.2.Indicate whether the following statements are true or false:a.If e is a minimum-weight edge in a connected weighted graph,it must be among edges of at least one minimum spanning tree of the graph.b.If e is a minimum-weight edge in a connected weighted graph,it must be among edges of each minimum spanning tree of the graph.c.If edge weights of a connected weighted graph are all distinct,the graph must have exactly one minimum spanning tree.d.If edge weights of a connected weighted graph are not all distinct,the graph must have more than one minimum spanning tree.3.What changes,if any,need to be made in algorithm Kruskal to make it find a minimum spanning forest for an arbitrary graph?(A minimum spanning forest is a forest whose trees are minimum spanning trees of the graph’s connected components.)10课后答案网h d a w .c o m4.Will either Kruskal’s or Prim’s algorithm work correctly on graphs that have negative edge weights?5.Design an algorithm for finding a maximum spanning tree –a spanning tree with the largest possible edge weight–of a weighted connected graph.6.Rewrite the pseudocode of Kruskal’s algorithm in terms of the operations of the disjoint subsets’ADT.7. Prove the correctness of Kruskal’s algorithm.8.Prove that the time efficiency of find (x )is in O (log n )for the union-by-size version of quick union.9.Find at least two Web sites with animations of Kruskal’s and Prim’s al-gorithms.Discuss their merits and demerits..10.Design and conduct an experiment to empirically compare the efficienciesof Prim’s and Kruskal’s algorithms on random graphs of different sizes and densities.11. Steiner tree Four villages are located at the vertices of a unit squarein the Euclidean plane.You are asked to connect them by the shortest network of roads so that there is a path between every pair of the villages along those roads.Find such a network.11课后答案网ww w.kh d aw .c omHints to Exercises 9.21.Trace the algorithm for the given graphs the same way it is done for another input in the section.2.Two of the four assertions are true,the other two are false.3.Applying Kruskal’s algorithm to a disconnected graph should help to an-swer the question.4.The answer is the same for both algorithms.If you believe that the algorithms work correctly on graphs with negative weights,prove this assertion;it you believe this is not to be the case,give a counterexample for each algorithm.5.Is the general trick of transforming maximization problems to their mini-mization counterparts (see Section6.6)applicable here?6.Substitute the three operations of the disjoint subsets’ADT–makeset (x ),find (x ),and union (x,y )–in the appropriate places of the pseudocode given in the section.7.Follow the plan used in Section 9.1to prove the correctness of Prim’s algorithm.8.The argument is very similar to the one made in the section for the union-by-size version of quick find.9.You may want to take advantage of the list of desirable characteristics in algorithm visualizations,which is given in Section 2.7.10.n/a11.The question is not trivial because introducing extra points (called Steinerpoints )may make the total length of the network smaller than that of a minimum spanning tree of the square.Solving first the problem for three equidistant points might give you an indication how a solution to the problem in question could look like.12课后答案网ww w.kh d aw .c omSolutions to Exercises9.21.a.后课13b.⇒⇒⇒⇒⇒⇒14课c⇒⇒⇒⇒⇒课2.a.True.(Otherwise,Kruskal’s algorithm would be invalid.)b.False.As a simple counterexample,consider a complete graph withthree vertices and the same weight on its three edgesc.True(Problem10in Exercises9.1).15d.False (see,for example,the graph of Problem 1a).3.Since the number of edges in a minimum spanning forest of a graph with |V |vertices and |C |connected components is equal to |V |−|C |(this for-mula is a simple generalization of |E |=|V |−1for connected graphs),Kruskal (G )will never get to |V |−1tree edges unless the graph is con-nected.A simple remedy is to replace the loop while ecounter <|V |−1with while k <|E |to make the algorithm stop after exhausting the sorted list of its edges.4.Both algorithms work correctly for graphs with negative edge weights.One way of showing this is to add to all the weights of a graph with negative weights some large positive number.This makes all the new weights positive,and one can “translate”the algorithms’actions on the new graph to the corresponding actions on the old one.Alternatively,you can check that the proofs justifying the algorithms’correctness do not depend on the edge weights being nonnegative.5.Replace each weight w (u,v )by −w (u,v )and apply any minimum spanning tree algorithm that works on graphs with arbitrary weights (e.g.,Prim’s or Kruskal’s algorithm)to the graph with the new weights.6.Algorithm Kruskal (G )//Kruskal’s algorithm with explicit disjoint-subsets operations //Input:A weighted connected graph G = V,E//Output:E T ,the set of edges composing a minimum spanning tree of G sort E in nondecreasing order of the edge weights w (e i 1)≤...≤w (e i |E |)for each vertex v ∈V make (v )E T ←∅;ecounter ←0//initialize the set of tree edges and its size k ←0//the number of processed edges while ecounter <|V |−1k ←k +1if find (u )=find (v )//u,v are the endpoints of edge e i kE T ←E T ∪{e i k };ecounter ←ecounter +1union (u,v )return E T 7.Let us prove by induction that each of the forests F i ,i =0,...,|V |−1,of Kruskal’s algorithm is a part (i.e.,a subgraph)of some minimum span-ning tree.(This immediately implies,of course,that the last forest in the sequence,F |V |−1,is a minimum spanning tree itself.Indeed,it contains all vertices of the graph,and it is connected because it is both acyclic and has |V |−1edges.)The basis of the induction is trivial,since F 0is16课后答案网ww w.kh d aw .c ommade up of |V |single-vertex trees and therefore must be a subgraph of any spanning tree of the graph.For the inductive step,let us assume that F i −1is a subgraph of some minimum spanning tree T .We need to prove that F i ,generated from F i −1by Kruskal’s algorithm,is also a part of a minimum spanning tree.We prove this by contradiction by assuming that no minimum spanning tree of the graph can contain F i .Let e i =(v,u )be the minimum weight edge added by Kruskal’s algorithm to forest F i −1to obtain forest F i .(Note that vertices v and u must belong to different trees of F i −1–otherwise,edge (v,u )would’ve created a cycle.)By our assumption,e i cannot belong to T .Therefore,if we add e i to T ,a cycle must be formed (see the figure below).In addition to edge e i =(v,u ),this cycle must contain another edge (v ,u )connecting a vertex v in the same tree of F i −1as v to a vertex u not in that tree.(It is possible that v coincides with v or u coincides with u but not both.)If we now delete the edge (v ,u )from this cycle,we will obtain another spanning tree of the entire graph whose weight is less than or equal to the weight of T since the weight of e i is less than or equal to the weight of (v ,u ).Hence,this spanning tree is a minimum spanning tree,which contradicts the assumption that no minimum spanning tree contains F i .This com-pletes the correctness proof of Kruskal’s algorithm.8.In the union-by-size version of quick-union ,each vertex starts at depth 0of its own tree.The depth of a vertex increases by 1when the tree it is in is attached to a tree with at least as many nodes during a union operation.Since the total number of nodes in the new tree containing the node is at least twice as much as in the old one,the number of such increases cannot exceed log 2n.Therefore the height of any tree (which is the largest depth of the tree’s nodes)generated by a legitimate sequence of unions will not exceed log 2n.Hence,the efficiency of find (x )is in O (log n )because find (x )traverses the pointer chain from the x ’s node to the tree’s root.9.n/a10.n/a17课后答案.kh d aw .c om11.The minimum Steiner tree that solves the problem is shown below.(Theother solution can be obtained by rotating the figure 90◦.)A popular discussion of Steiner trees can be found in “Last Recreations:Hydras,Eggs,and Other Mathematical Mystifications”by Martin Gard-ner.In general,no polynomial time algorithm is known for finding a minimum Steiner tree;moreover,the problem is known to be NP -hard (see Section 11.3).For the state-of-the-art information,see,e.g.,The Steiner Tree Page at /steiner/.18课后答案网ww w.kc omExercises 9.31.Explain what adjustments if any need to be made in Dijkstra’s algorithm and/or in an underlying graph to solve the following problems.a.Solve the single-source shortest-paths problem for directed weighted graphs.b.Find a shortest path between two given vertices of a weighted graph or digraph.(This variation is called the single-pair shortest-path prob-lem .)c.Find the shortest paths to a given vertex from each other vertex of a weighted graph or digraph.(This variation is called the single-destination shortest-paths problem .)d.Solve the single-source shortest-path problem in a graph with nonneg-ative numbers assigned to its vertices (and the length of a path defined as the sum of the vertex numbers on the path).2.Solve the following instances of the single-source shortest-paths problem with vertex a as the source:a.b.3.Give a counterexample that shows that Dijkstra’s algorithm may not work for a weighted connected graph with negative weights.19课案w w.kh d aw .c om4.Let T be a tree constructed by Dijkstra’s algorithm in the process of solving the single-source shortest-path problem for a weighted connected graph G .a.True or false:T is a spanning tree of G ?b.True or false:T is a minimum spanning tree of G ?5.Write a pseudocode of a simpler version of Dijkstra’s algorithm that finds only the distances (i.e.,the lengths of shortest paths but not shortest paths themselves)from a given vertex to all other vertices of a graph represented by its weight matrix.6. Prove the correctness of Dijkstra’s algorithm for graphs with positive weights.7.Design a linear-time algorithm for solving the single-source shortest-paths problem for dags (directed acyclic graphs)represented by their adjacency lists.8.Design an efficient algorithm for finding the length of a longest path in a dag.(This problem is important because it determines a lower bound on the total time needed for completing a project composed of precedence-constrained tasks.)9.Shortest-path modeling Assume you have a model of a weighted con-nected graph made of balls (representing the vertices)connected by strings of appropriate lengths (representing the edges).a.Describe how you can solve the single-pair shortest-path problem with this model .b.Describe how you can solve the single-source shortest-paths problem with this model .10.Revisit Problem 6in Exercises 1.3about determining the best route fora subway passenger to take from one designated station to another in a well-developed subway system like those in Washington,DC and London,UK.Write a program for this task.20课后答案网ww w.kh d aw .c om。

算法设计与分析ppt课件

算法设计与分析ppt课件
2
ACM国际大学生程序设计竞赛
ACM国际大学生程序设计竞赛(英文 全称:ACM International Collegiate Programming Contest(ACM-ICPC或 ICPC)是由美国计算机协会(ACM)主办 的,一项旨在展示大学生创新能力、团队 精神和在压力下编写程序、分析和解决问 题能力的年度竞赛。经过30多年的发展, ACM国际大学生程序设计竞赛已经发展成 为最具影响力的大学生计算机竞赛。赛事 目前由IBM公司赞助。
第3章 动态规划 3.1 矩阵连乘问题 3.2 动态规划算法的基本要素 3.3 最长公共子序列 3.4 最大子段和 3.5 凸多边形最优三角剖分 3.6 多边形游戏 3.7 图像压缩 3.8 电路布线 3.9 流水作业调度 3.10 0-1背包问题 3.11 最优二叉搜索树 3.12 动态规划加速原理
7
1.1 算法与程序
算法:是满足下述性质的指令序列。
输 入:有零个或多个外部量作为算法的输入。 输 出:算法产生至少一个量作为输出。 确定性:组成算法的每条指令清晰、无歧义。 有限性:算法中每条指令的执行次数有限,执行
每条指令的时间也有限。
程序:是算法用某种程序设计语言的具体实现。
4
教材与参考书
教 材:
◦ 算法设计与分析(第三版) 王晓东,2007年 5月,电子工业出版社。
参考书:
◦ 徐士良编,C常用算法程序集,华大学出版 社,1998年
◦ 霍红卫编,算法设计与分析 西安电子科技 大学出版社,2005年
◦ 卢开澄编,计算机算法导引,清华大学出 版社,2003年
5
部分目录
算法分析是计算机领域的“古老”而“前沿” 的课题。
10

计算机算法设计与分析-Chapter9计算机难解问题与NP-完全性

计算机算法设计与分析-Chapter9计算机难解问题与NP-完全性

0-1背包问题在经济规划和装载等应用领域中常常遇到,例如 ,它可以描述一个投资决策问题:有n项可投资的项目,每 个项目需要投入资金Si,可获利润为Pi,现有可用资金总数 为M,应选择哪些项目来投资,可获得最大利润。
9.1.3 子集合(Subset Sum)问题
已知:正整数C和正整数集合S={s1,s2,...,sn}。
合取范式(CNF)是命题公式(propositional formula)(亦称 Boolean表达式)的标准形式,它是由命题变元(或布尔变量) 、布尔常量(F或T)以及布尔运算符(与∧、或∨、非┐)组 成。
一个CNF形如:A1∧A2∧...∧Am,子句Ai形如:a1∨a2∨... ∨ak 。其中aj(1≤j≤k)为某一布尔变量或是该变量的非。
K = min {C(V) || C(V)为G的着色方案}。
图着色(Graph Coloring)问题,就是求图G=<V,E>的色数K。
除交通信号灯问题外,课程时间表问题也可归结为GC问题。 例如,有n门课的考试,每次考试用一个课时,如果课程i和课 程j有同一学生选修,则两门课的考试不能同时进行,希望用 最少的课时数(教室不限)完成n门考试。
无向图G=<V,E>的团集问题:求G的最大团集。
例如,在Fig9.1中的5顶点 无向图中,由V1、V2、 V4及相应的边组成一个三 点团集,它就是一个最大 团。
任何无向图的一个顶点是一个一点平凡团集,由一边连接的 两个顶点形成一个两点团集。问题的复杂性来源于,若图G有 一个k点团集,并且要证明它没有k+1点的完全子图。n个顶点 的k+1点子集的组合数是n的指数函数,因此无法设计出一个 多项式阶时间复杂度的函数判断图G是否包含一个k+1点完全 子图。

算法设计与分析报告习题

算法设计与分析报告习题

《算法设计与分析》习题第一章算法引论1、算法的定义?答:算法是指在解决问题时,按照某种机械步骤一定可以得到问题结果的处理过程。

通俗讲,算法:就是解决问题的方法或过程。

2、算法的特征?答:1)算法有零个或多个输入;2)算法有一个或多个输出; 3)确定性;4)有穷性3、算法的描述方法有几种?答:自然语言、图形、伪代码、计算机程序设计语言4、衡量算法的优劣从哪几个方面?答:(1) 算法实现所耗费的时间(时间复杂度);(2) 算法实现所所耗费的存储空间(空间复杂度);(3) 算法应易于理解,易于编码,易于调试等等。

5、时间复杂度、空间复杂度定义?答:指的是算法在运行过程中所需要的资源(时间、空间)多少。

6、时间复杂度计算:{i=1;while(i<=n)i=i*2; }答:语句①执行次数1次,语句②③执行次数f(n), 2^f(n)<=n,则f(n) <=log2n;算法执行时间: T(n)= 2log2n +1时间复杂度:记为O(log2n) ;7.递归算法的特点?答:①每个递归函数都必须有非递归定义的初值;否则,递归函数无法计算;(递归终止条件)②递归中用较小自变量函数值来表达较大自变量函数值;(递归方程式)8、算法设计中常用的算法设计策略?答:①蛮力法;②倒推法;③循环与递归;④分治法;⑤动态规划法;⑥贪心法;⑦回溯法;⑧分治限界法9、设计算法:递归法:汉诺塔问题?兔子序列(上楼梯问题)?整数划分问题?蛮力法:百鸡百钱问题?倒推法:穿越沙漠问题?答:算法如下: (1) 递归法● 汉诺塔问题void hanoi(int n, int a, int b, int c) {if (n > 0) {hanoi(n-1, a, c, b); move(a,b);hanoi(n-1, c, b, a); } }● 兔子序列(fibonaci 数列 )递归实现:Int F(int n) {if(n<=2) return 1; elsereturn F(n-1)+ F(n-2); }● 上楼梯问题 Int F(int n) {if(n=1) return 1 if(n=2) return 2; elsereturn F(n-1)+ F(n-2); }● 整数划分问题问题描述:将正整数n 表示成一系列正整数之和,n=n1+n1+n3+…将最大加数不大于m 的划分个数,记作q(n,m)。

田翠华著《算法设计与分析》课后习题参考答案

田翠华著《算法设计与分析》课后习题参考答案

参考答案第1章一、选择题1. C2. A3. C4. C A D B5. B6. B7. D 8. B 9. B 10. B 11. D 12. B二、填空题1. 输入;输出;确定性;可行性;有穷性2. 程序;有穷性3. 算法复杂度4. 时间复杂度;空间复杂度5. 正确性;简明性;高效性;最优性6. 精确算法;启发式算法7. 复杂性尽可能低的算法;其中复杂性最低者8. 最好性态;最坏性态;平均性态9. 基本运算10. 原地工作三、简答题1. 高级程序设计语言的主要好处是:(l)高级语言更接近算法语言,易学、易掌握,一般工程技术人员只需要几周时间的培训就可以胜任程序员的工作;(2)高级语言为程序员提供了结构化程序设计的环境和工具,使得设计出来的程序可读性好,可维护性强,可靠性高;(3)高级语言不依赖于机器语言,与具体的计算机硬件关系不大,因而所写出来的程序可移植性好、重用率高;(4)把复杂琐碎的事务交给编译程序,所以自动化程度高,发用周期短,程序员可以集中集中时间和精力从事更重要的创造性劳动,提高程序质量。

2. 使用抽象数据类型带给算法设计的好处主要有:(1)算法顶层设计与底层实现分离,使得在进行顶层设计时不考虑它所用到的数据,运算表示和实现;反过来,在表示数据和实现底层运算时,只要定义清楚抽象数据类型而不必考虑在什么场合引用它。

这样做使算法设计的复杂性降低了,条理性增强了,既有助于迅速开发出程序原型,又使开发过程少出差错,程序可靠性高。

(2)算法设计与数据结构设计隔开,允许数据结构自由选择,从中比较,优化算法效率。

(3)数据模型和该模型上的运算统一在抽象数据类型中,反映它们之间内在的互相依赖和互相制约的关系,便于空间和时间耗费的折衷,灵活地满足用户要求。

(4)由于顶层设计和底层实现局部化,在设计中出现的差错也是局部的,因而容易查找也容易2 算法设计与分析纠正,在设计中常常要做的增、删、改也都是局部的,因而也都容易进行。

算法设计与分析_北京航空航天大学中国大学mooc课后章节答案期末考试题库2023年

算法设计与分析_北京航空航天大学中国大学mooc课后章节答案期末考试题库2023年

算法设计与分析_北京航空航天大学中国大学mooc课后章节答案期末考试题库2023年1.对如下所示连通无向图【图片】,其最小生成树的权重为【图片】参考答案:232.对如下所示有向图,从【图片】点开始进行深度优先搜索(DFS),搜索时按照字典序遍历某一节点的相邻节点。

在得到的深度优先搜索树中,包含如下哪些类别的边(多选)【图片】参考答案:树边_前向边_后向边_横向边3.在0-1背包问题中,若背包容量为20,5个物品的体积分别为【图片】,价格分别为【图片】。

则该背包能容纳物品的最大总价格为____参考答案:254.设计动态规划算法的一般步骤为____参考答案:问题结构分析→递推关系建立→自底向上计算→最优方案追踪5.给定两个序列分别为“algorithm”和“glorhythm”。

则以下分别为两序列的最长公共子序列和最长公共子串的选项是____参考答案:gorthm thm6.在最长公共子串问题的递推式中,【图片】表示____参考答案:和中以和结尾的最长公共子串的长度7.在支持插入、删除、替换三种操作的最小编辑距离问题中,用【图片】数组来记录编辑方案。

则【图片】数组中的"L","U","LU"分别代表哪种操作___参考答案:插入删除替换/空操作8.字符串“algorithm”到字符串“altruistic”的最小编辑距离为___参考答案:69.数组【图片】中的逆序对个数为____参考答案:510.在上题中,均不在搜索树中的边有哪些____(多选)参考答案:_11.在扇形图(Fan Graph)【图片】中,其邻接表和结构如下第一张图所示。

从顶点【图片】开始进行广度优先搜索(BFS),搜索时按照邻接表顺序遍历某一节点的相邻节点。

得到搜索树如下第二张图,该搜索树并未画全,应从虚线中选择____补全。

(多选)【图片】【图片】参考答案:①_②12.同上题,在扇形图(Fan Graph)【图片】中,其邻接表和结构如下图所示。

算法设计与分析课后答案

算法设计与分析课后答案

5..证明等式gcd(m,n)=gcd(n,m mod n)对每一对正整数m,n都成立.Hint:根据除法的定义不难证明:●如果d整除u和v, 那么d一定能整除u±v;●如果d整除u,那么d也能够整除u的任何整数倍ku.对于任意一对正整数m,n,若d能整除m和n,那么d一定能整除n和r=m mod n=m-qn;显然,若d能整除n和r,也一定能整除m=r+qn和n。

数对(m,n)和(n,r)具有相同的公约数的有限非空集,其中也包括了最大公约数。

故gcd(m,n)=gcd(n,r)6.对于第一个数小于第二个数的一对数字,欧几里得算法将会如何处理?该算法在处理这种输入的过程中,上述情况最多会发生几次?Hint:对于任何形如0<=m<n的一对数字,Euclid算法在第一次叠代时交换m和n, 即gcd(m,n)=gcd(n,m)并且这种交换处理只发生一次.7.a.对于所有1≤m,n≤10的输入, Euclid算法最少要做几次除法?(1次)b. 对于所有1≤m,n≤10的输入, Euclid算法最多要做几次除法?(5次)gcd(5,8)习题1.21.(农夫过河)P—农夫W—狼G—山羊C—白菜2.(过桥问题)1,2,5,10---分别代表4个人, f—手电筒4. 对于任意实系数a,b,c, 某个算法能求方程ax^2+bx+c=0的实根,写出上述算法的伪代码(可以假设sqrt(x)是求平方根的函数)算法Quadratic(a,b,c)//求方程ax^2+bx+c=0的实根的算法//输入:实系数a,b,c//输出:实根或者无解信息D←b*b-4*a*cIf D>0temp←2*ax1←(-b+sqrt(D))/tempx2←(-b-sqrt(D))/tempreturn x1,x2else if D=0 return –b/(2*a)else return “no real roots”else //a=0if b≠0 return –c/belse //a=b=0if c=0 return “no real numbers”else return “no real roots”5.描述将十进制整数表达为二进制整数的标准算法a.用文字描述b.用伪代码描述解答:a.将十进制整数转换为二进制整数的算法输入:一个正整数n输出:正整数n相应的二进制数第一步:用n除以2,余数赋给Ki(i=0,1,2...),商赋给n第二步:如果n=0,则到第三步,否则重复第一步第三步:将Ki按照i从高到低的顺序输出b.伪代码算法DectoBin(n)//将十进制整数n转换为二进制整数的算法//输入:正整数n//输出:该正整数相应的二进制数,该数存放于数组Bin[1...n]中i=1while n!=0 do {Bin[i]=n%2;n=(int)n/2;i++;}while i!=0 do{print Bin[i];i--;}9.考虑下面这个算法,它求的是数组中大小相差最小的两个元素的差.(算法略) 对这个算法做尽可能多的改进.算法MinDistance(A[0..n-1])//输入:数组A[0..n-1]//输出:the smallest distance d between two of its elements习题1.31.考虑这样一个排序算法,该算法对于待排序的数组中的每一个元素,计算比它小的元素个数,然后利用这个信息,将各个元素放到有序数组的相应位置上去.a.应用该算法对列表‖60,35,81,98,14,47‖排序b.该算法稳定吗?c.该算法在位吗?解:a. 该算法对列表‖60,35,81,98,14,47‖排序的过程如下所示:b.该算法不稳定.比如对列表‖2,2*‖排序c.该算法不在位.额外空间for S and Count[]4.(古老的七桥问题)习题1.41.请分别描述一下应该如何实现下列对数组的操作,使得操作时间不依赖数组的长度. a.删除数组的第i 个元素(1<=i<=n)b.删除有序数组的第i 个元素(依然有序) hints:a. Replace the i th element with the last element and decrease the array size of 1b. Replace the ith element with a special symbol that cannot be a value of the array ’s element(e.g., 0 for an array of positive numbers ) to mark the i th position is empty. (―lazy deletion ‖)第2章 习题2.17.对下列断言进行证明:(如果是错误的,请举例) a. 如果t(n )∈O(g(n),则g(n)∈Ω(t(n)) b.α>0时,Θ(αg(n))= Θ(g(n)) 解:a. 这个断言是正确的。

第9章 图算法设计-算法设计与分析(第2版)-李春葆-清华大学出版社

第9章 图算法设计-算法设计与分析(第2版)-李春葆-清华大学出版社

{ lowcost[j]=g.edges[k][j];
closest[j]=k;
}
}
}
Prim()算法中有两重for循环,所以时间复杂度为O(n2),其中n为 图的顶点个数。
3. 普里姆算法的正确性证明
普里姆算法是一种贪心算法。对于带权连通无向图G=(V,E),采用 通过对算法步骤的归纳来证明普里姆算法的正确性。
8
2
4
3
6
lowcost[1]最小,将k=1添加到U中
U
0
6
1
仅修改V-U中顶点j:
1
4 3
g.edges[k][j]<lowcost[j] 调整
5
6
2
lowcost[j]=g.edges[k][j]
7
5
8
4
3
6
2
V-U
closest[j]=k
Prim(g,v)算法利用上述过程构造最小生成树,其中参数g为带权 邻接矩阵,v为起始顶点的编号。
k=j;
//k记录最近顶点的编号
}
printf(" 边(%d,%d)权为:%d\n",closest[k],k,mincost);
lowcost[k]=0;
//标记k已经加入U
for (j=0;j<g.n;j++)
//修改数组lowcost和closest
if (g.edges[k][j]!=0 && g.edges[k][j]<lowcost[j])
void Prim(MGraph g,int v)
//Prim算法
{ int lowcost[MAXV];

算法设计与分析-课后习题集答案

算法设计与分析-课后习题集答案

第一章3. 最大公约数为1。

快1414倍。

程序1-2的while 循环体做了10次,程序1-3的while 循环体做了14141次(14142-2循环)8.(1)画线语句的执行次数为log n ⎡⎤⎢⎥。

(log )n O 。

(2)画线语句的执行次数为111(1)(21)16jnii j k n n n ===++=∑∑∑。

3()n O 。

(3)画线语句的执行次数为。

O 。

(4)当n 为奇数时画线语句的执行次数为(1)(1)4n n +-, 当n 为偶数时画线语句的执行次数为 (2)4n n +。

2()n O 。

10.(1) 当 1n ≥ 时,225825n n n -+≤,所以,可选 5c =,01n =。

对于0n n ≥,22()5825f n n n n =-+≤,所以,22582()-+=O n n n 。

(2) 当 8n ≥ 时,2222582524n n n n n -+≥-+≥,所以,可选 4c =,08n =。

对于0n n ≥,22()5824f n n n n =-+≥,所以,22582()-+=Ωn n n 。

(3) 由(1)、(2)可知,取14c =,25c =,08n =,当0n n ≥时,有22212582c n n n c n ≤-+≤,所以22582()-+=Θn n n 。

11. (1) 当3n ≥时,3log log n n n <<,所以()20log 21f n n n n =+<,3()log 2g n n n n =+>。

可选212c =,03n =。

对于0n n ≥,()()f n cg n ≤,即()(())f n g n =O 。

(2) 当 4n ≥ 时,2log log n n n <<,所以 22()/log f n n n n =<,22()log g n n n n =≥。

可选 1c =,04n =。

算法设计与分析(第3版)

算法设计与分析(第3版)
在为各种算法设计策略选择用于展示其设计思想与技巧的具体应用问题时,该教材有意重复选择某些经典问 题,使读者能体会到一个问题可以用多种设计策略求解。同时,通过对解同一问题的不同算法的比较,更容易体 会到每一个具体算法的设计要点。随着该教材内容的逐步展开,读者也将进一步感受到综合应用多种设计策略可 以更有效地解决问题。
该教材采用面向对象的Java语言作为表述手段,在保持Java优点的同时,尽量使算法的描述简明。为了加深 对知识的理解,各章配有难易适当的习题,以适应不同程度读者练习的需要。
作者简介
王晓东,男,1957年出生,山东人,中共党员,现任福建工程学院副院长、教授、博士生导师。先后担任福 州大学计算机系主任、数学与计算机科学学院院长,2007年8月起担任泉州师范学院副院长,2014年8月起任现 职。
全书共分11章。该教材以算法设计策略为知识单元,介绍了计算机算法的设计方法与分析技巧。
成书过程
修订过程
出版工作
该教材是为了适应培养中国21世纪计算机各类人才的需要,结合中国高等学校教育工作的现状,立足培养学 生能跟上国际计算机科学技术的发展水平,更新教学内容和教学方法,提高教学质量的基础上编写而成。
谢谢观看
该教材由王晓东编著。在编写过程中,得到教育部高等学校计算机类专业教学指导委员会的支持。福州大学 “211工程”计算机与信息工程重点学科实验室为该教材的写作提供了设备与工作环境。南京大学宋方敏教授和 福州大学傅清祥教授审阅了全书,提出了改进意见。
2014年1月1日,该教材由清华大学出版社出版。
内容简介
该教材以算法设计策略为知识单元,介绍了计算机算法的设计方法与分析技巧。 全书共分11章。 在第1章中首先介绍算法的基本概念,接着简要阐述算法的计算复杂性和算法的描述,然后围绕设计算法常用 的基本设计策略组织第2章至第10章的内容。 第2章介绍递归与分治策略,这是设计有效算法最常用的策略。 第3章是动态规划算法,以具体实例详述动态规划算法的设计思想、适用性以及算法的设计要点。 第4章介绍贪心算法,这也是一种重要的算法设计策略,它与动态规划算法的设计思想有一定的,但其效率更 高。按贪心算法设计出的许多算法能导致最优解。 第5章和第6章分别介绍回溯法和分支限界法。这两章所介绍的算法适合于处理难解问题。 第7章介绍概率算法,对许多难解问题提供高效的解决途径,是有较高实用价值的算法设计策略。 第8章介绍NP完全性理论。首先介绍计算模型、确定性和非确定性图灵机,然后进一步介绍NP完全性理论。 第9章介绍了解NP难问题的近似算法,这是计算机算法领域的热门研究课题,具有较高的实用价值。
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

P类与 类问题 类与NP类问题 类与
P ? P
P类 类
如果一个算法, 如果一个算法,它能在以输入规模为参变量的 某个多项式的时间内给出答案,则称它为多项 某个多项式的时间内给出答案,则称它为多项 式时间算法。 式时间算法。 P类问题是一类用 确定性 算法在多项式的时 类问题是一类用(确定性 类问题是一类用 确定性) 间内求解的判定问题 判定问题。 间内求解的判定问题。 P类问题指在确定性图灵机上的具有多项式算 类问题指在确定性图灵机 类问题指在确定性图灵机上的具有多项式算 法的问题集合。 法的问题集合。
NP完全问题 完全问题
NP里面有无数个不同的问题,我们是否要一个一个 里面有无数个不同的问题, 里面有无数个不同的问题 地判定它们是否属于P呢 地判定它们是否属于 呢? NP完全 完全(NP Complete,简记为 问题, 完全 ,简记为NPC)问题,指的是 问题 那些NP中最难的那些问题 所有其它的NP问题都可 中最难的那些问题: 那些 中最难的那些问题:所有其它的 问题都可 以归约到这些NP完全问题 完全问题。 以归约到这些 完全问题。
NP完全问题 完全问题
NP完全问题的近似算法 完全问题的近似算法
迄今为止,所有的 完全问题都还没有多项式时 迄今为止,所有的NP完全问题都还没有多项式时 间算法。对于这类问题,通常可采取以下几种解题 间算法。对于这类问题, 策略: 策略:
(1)只对问题的特殊实例求解 只对问题的特殊实例求解 (2)用动态规划法或分支限界法求解 用动态规划法或分支限界法求解 (3)用概率算法求解 用概率算法求解 (4)只求近似解 只求近似解 (5)用启发式方法求解 用启发式方法求解
NP类 类
NP类问题是一类可以用不确定多项式算 类问题是一类可以用不确定多项式算 类问题是一类可以用不确定多项式 法求解的判定问题。 法求解的判定问题。 NP类问题指非确定型图灵机上具有多项 类问题指非确定型图灵机上具有多项 类问题 式算法的问题集合
NP问题
P NP
P=NP?
P vs NP问题指P是否完全等于NP,即确定 型图灵机和非确定图灵机的性能是否一样。
P
NPC
NPH
NP
第9章 问题的复杂性
P类与 类问题 类与NP类问题 类与
一般地说, 一般地说,将可由多项式时间算法求解的问题看作是易处 理的问题,而将需要超多项式时间才能求解的问题看作是 理的问题, 难处理的问题。 难处理的问题。 有许多问题, 有许多问题,从表面上看似乎并不比排序或图的搜索等问 题更困难, 题更困难,然而至今人们还没有找到解决这些问题的多项 式时间算法, 式时间算法,也没有人能够证明这些问题需要超多项式时 间下界。 间下界。 在图灵机计算模型下,这类问题的计算复杂性至今未知。 在图灵机计算模型下,这类问题的计算复杂性至今未知。 为了研究这类问题的计算复杂性, 为了研究这类问题的计算复杂性,人们提出了另一个能力 更强的计算模型,即非确定性图灵机计算模型, 更强的计算模型,即非确定性图灵机计算模型,简记为 NDTM(Nondeterministic Turing Machine)。 。 在非确定性图灵机计算模型下, 在非确定性图灵机计算模型下,许多问题可以在多项式时 间内求解。 间内求解。
相关文档
最新文档