算法设计与分析基础课后习题答案solu3

合集下载

1.算法设计与分析习题及答案

1.算法设计与分析习题及答案

1.算法设计与分析习题及答案《计算机算法设计与分析》习题及答案2013 秋《计算机算法设计与分析》习题及答案一.选择题1、二分搜索算法是利用( A )实现的算法。

A、分治策略B、动态规划法C、贪心法D、回溯法2、下列不是动态规划算法基本步骤的是( A )。

A、找出最优解的性质B、构造最优解C、算出最优解D、定义最优解3、最大效益优先是( A )的一搜索方式。

A、分支界限法B、动态规划法C、贪心法D、回溯法4、在下列算法中有时找不到问题解的是( B )。

A、蒙特卡罗算法B、拉斯维加斯算法C、舍伍德算法D、数值概率算法5. 回溯法解旅行售货员问题时的解空间树是( A )。

A、子集树B、排列树C、深度优先生成树D、广度优先生成树6.下列算法中通常以自底向上的方式求解最优解的是( B )。

A、备忘录法B、动态规划法C、贪心法D、回溯法7、衡量一个算法好坏的标准是( C )。

A 运行速度快B 占用空间少C 时间复杂度低D 代码短8、以下不可以使用分治法求解的是( D )。

A 棋盘覆盖问题B 选择问题C 归并排序D 0/1背包问题9. 实现循环赛日程表利用的算法是( A )。

A、分治策略B、动态规划法C、贪心法D、回溯法10、下列随机算法中运行时有时候成功有时候失败的是( C )A 数值概率算法B 舍伍德算法C 拉斯维加斯算法D 蒙特卡罗算法11.下面不是分支界限法搜索方式的是( D )。

A、广度优先B、最小耗费优先C、最大效益优先D、深度优先12.下列算法中通常以深度优先方式系统搜索问题解的是( D )。

A、备忘录法B、动态规划法C、贪心法D、回溯法13.备忘录方法是那种算法的变形。

( B )A、分治法B、动态规划法C、贪心法D、回溯法14.哈夫曼编码的贪心算法所需的计算时间为( B )。

A、O(n2n)B、O(nlogn)C、O(2n)D、O(n)15.分支限界法解最大团问题时,活结点表的组织形式是(B )。

算法设计与分析基础课后习题答案

算法设计与分析基础课后习题答案

Program算法设计与分析基础中文版答案习题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)并且这种交换处理只发生一次..对于所有1≤m,n≤10的输入, Euclid算法最少要做几次除法?(1次)b. 对于所有1≤m,n≤10的输入, Euclid算法最多要做几次除法?(5次)gcd(5,8)习题1.(农夫过河)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)描述将十进制整数表达为二进制整数的标准算法a.用文字描述b.用伪代码描述解答:a.将十进制整数转换为二进制整数的算法输入:一个正整数n输出:正整数n相应的二进制数第一步:用n除以2,余数赋给Ki(i=0,1,2...),商赋给n第二步:如果n=0,则到第三步,否则重复第一步第三步:将Ki按照i从高到低的顺序输出b.伪代码算法 DectoBin(n).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])n-1]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.请分别描述一下应该如何实现下列对数组的操作,使得操作时间不依赖数组的长度.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., 0 for an array of positive numbers ) to mark the i th position is empty. (“lazy deletion”)第2章习题7.对下列断言进行证明:(如果是错误的,请举例)a. 如果t(n)∈O(g(n),则g(n)∈Ω(t(n))b.α>0时,Θ(αg(n))= Θ(g(n))解:a. 这个断言是正确的。

算法设计与分析习题解答

算法设计与分析习题解答

算法设计与分析习题解答第一章作业1.证明下列Ο、Ω和Θ的性质1)f=Ο(g)当且仅当g=Ω(f)证明:充分性。

若f=Ο(g),则必然存在常数c1>0和n0,使得?n≥n0,有f≤c1*g(n)。

由于c1≠0,故g(n) ≥ 1/ c1 *f(n),故g=Ω(f)。

必要性。

同理,若g=Ω(f),则必然存在c2>0和n0,使得?n≥n0,有g(n) ≥ c2 *f(n).由于c2≠0,故f(n) ≤ 1/ c2*f(n),故f=Ο(g)。

2)若f=Θ(g)则g=Θ(f)证明:若f=Θ(g),则必然存在常数c1>0,c2>0和n0,使得?n≥n0,有c1*g(n) ≤f(n) ≤ c2*g(n)。

由于c1≠0,c2≠0,f(n) ≥c1*g(n)可得g(n) ≤ 1/c1*f(n),同时,f(n) ≤c2*g(n),有g(n) ≥ 1/c2*f(n),即1/c2*f(n) ≤g(n) ≤ 1/c1*f(n),故g=Θ(f)。

3)Ο(f+g)= Ο(max(f,g)),对于Ω和Θ同样成立。

证明:设F(n)= Ο(f+g),则存在c1>0,和n1,使得?n≥n1,有F(n) ≤ c1 (f(n)+g(n))= c1 f(n) + c1g(n)≤ c1*max{f,g}+ c1*max{f,g}=2 c1*max{f,g}所以,F(n)=Ο(max(f,g)),即Ο(f+g)= Ο(max(f,g))对于Ω和Θ同理证明可以成立。

4)log(n!)= Θ(nlogn)证明:由于log(n!)=∑=ni i 1log ≤∑=ni n 1log =nlogn ,所以可得log(n!)= Ο(nlogn)。

由于对所有的偶数n 有,log(n!)= ∑=ni i 1log ≥∑=nn i i 2/log ≥∑=nn i n 2/2/log ≥(n/2)log(n/2)=(nlogn)/2-n/2。

算法设计与分析智慧树知到课后章节答案2023年下山东交通学院

算法设计与分析智慧树知到课后章节答案2023年下山东交通学院

算法设计与分析智慧树知到课后章节答案2023年下山东交通学院山东交通学院第一章测试1.解决一个问题通常有多种方法。

若说一个算法“有效”是指( )A:这个算法能在一定的时间和空间资源限制内将问题解决B:这个算法能在人的反应时间内将问题解决C:这个算法比其他已知算法都更快地将问题解决D:(这个算法能在一定的时间和空间资源限制内将问题解决)和(这个算法比其他已知算法都更快地将问题解决)答案:(这个算法能在一定的时间和空间资源限制内将问题解决)和(这个算法比其他已知算法都更快地将问题解决)2.农夫带着狼、羊、白菜从河的左岸到河的右岸,农夫每次只能带一样东西过河,而且,没有农夫看管,狼会吃羊,羊会吃白菜。

请问农夫能不能过去?()A:不一定B:不能过去 C:能过去答案:能过去3.下述()不是是算法的描述方式。

A:自然语言 B:E-R图 C:程序设计语言 D:伪代码答案:E-R图4.有一个国家只有6元和7元两种纸币,如果你是央行行长,你会设置()为自动取款机的取款最低限额。

A:40 B:29 C:30 D:42答案:305.算法是一系列解决问题的明确指令。

()A:对 B:错答案:对6.程序=数据结构+算法()A:对 B:错答案:对7.同一个问题可以用不同的算法解决,同一个算法也可以解决不同的问题。

()A:错 B:对答案:对8.算法中的每一条指令不需有确切的含义,对于相同的输入不一定得到相同的输出。

( )A:错 B:对答案:错9.可以用同样的方法证明算法的正确性与错误性 ( )A:错 B:对答案:错10.求解2个数的最大公约数至少有3种方法。

( )A:对 B:错答案:错11.没有好的算法,就编不出好的程序。

()A:对 B:错答案:对12.算法与程序没有关系。

( )A:错 B:对答案:错13.我将来不进行软件开发,所以学习算法没什么用。

( )A:错 B:对答案:错14.gcd(m,n)=gcd(n,m m od n)并不是对每一对正整数(m,n)都成立。

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

算法设计与分析-课后习题集答案
10.(1)当 时, ,所以,可选 , 。对于 , ,所以, 。
(2)当 时, ,所以,可选 , 。对于 , ,所以, 。
(3)由(1)、(2)可知,取 , , ,当 时,有 ,所以 。
11. (1)当 时, ,所以 , 。可选 , 。对于 , ,即 。
(2)当 时, ,所以 , 。可选 , 。对于 , ,即 。
(3)因为 , 。当 时, , 。所以,可选 , ,对于 , ,即 。
第二章
2-17.证明:设 ,则 。
当 时, 。所以, 。
第五章
5-4.SolutionType DandC1(int left,int right)
{while(!Small(left,right)&&left<right)
{int m=Divide(left,right);
所以n-1<=m<=n (n-1)/2;
O(n)<=m<=O(n2);
克鲁斯卡尔对边数较少的带权图有较高的效率,而 ,此图边数较多,接近完全图,故选用普里姆算法。
10.
T仍是新图的最小代价生成树。
证明:假设T不是新图的最小代价生成树,T’是新图的最小代价生成树,那么cost(T’)<cost(T)。有cost(T’)-c(n-1)<cost(t)-c(n-1),即在原图中存在一颗生成树,其代价小于T的代价,这与题设中T是原图的最小代价生成树矛盾。所以假设不成立。证毕。
13.template <class T>
select (T&x,int k)
{
if(m>n) swap(m,n);
if(m+n<k||k<=0) {cout<<"Out Of Bounds"; return false;}

算法设计与分析第二版课后习题解答

算法设计与分析第二版课后习题解答

算法设计与分析基础课后练习答案算法设计与分析基础课后练习答案习题1.1 4.设计一个计算的算法,n 是任意正整数。

除了赋值和比较运算,该算法只能用到基本的四则运算操作。

能用到基本的四则运算操作。

算法求//输入:一个正整数n 2 //输出:。

step1:a=1;step2:若a*a<n 转step 3,否则输出a ; step3:a=a+1转step 2; 5. a .用欧几里德算法求gcd (31415,14142)。

b. 用欧几里德算法求gcd (31415,14142),比检查min {m ,n }和gcd (m ,n )间连续整数的算法快多少倍?请估算一下。

a. gcd(31415, 14142) = gcd(14142, 3131) = gcd(3131, 1618) =gcd(1618, 1513) = gcd(1513, 105) = gcd(1513, 105) = gcd(105, 43) =gcd(43, 19) = gcd(19, 5) = gcd(5, 4) = gcd(4, 1) = gcd(1, 0) = 1. b.有a 可知计算gcd (31415,14142)欧几里德算法做了11次除法。

次除法。

连续整数检测算法在14142每次迭代过程中或者做了一次除法,或者两次除法,因此这个算法做除法的次数鉴于1·14142 和 2·14142之间,之间,所以欧几里德算法所以欧几里德算法比此算法快1·14142/11 ≈ 1300 与 2·14142/11 ≈ 2600 倍之间。

倍之间。

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

算法分析与设计(习题答案)

算法分析与设计(习题答案)

算法分析与设计教程习题解答第1章 算法引论1. 解:算法是一组有穷的规则,它规定了解决某一特定类型问题的一系列计算方法。

频率计数是指计算机执行程序中的某一条语句的执行次数。

多项式时间算法是指可用多项式函数对某算法进行计算时间限界的算法。

指数时间算法是指某算法的计算时间只能使用指数函数限界的算法。

2. 解:算法分析的目的是使算法设计者知道为完成一项任务所设计的算法的优劣,进而促使人们想方设法地设计出一些效率更高效的算法,以便达到少花钱、多办事、办好事的经济效果。

3. 解:事前分析是指求出某个算法的一个时间限界函数(它是一些有关参数的函数);事后测试指收集计算机对于某个算法的执行时间和占用空间的统计资料。

4. 解:评价一个算法应从事前分析和事后测试这两个阶段进行,事前分析主要应从时间复杂度和空间复杂度这两个维度进行分析;事后测试主要应对所评价的算法作时空性能分布图。

5. 解:①n=11; ②n=12; ③n=982; ④n=39。

第2章 递归算法与分治算法1. 解:递归算法是将归纳法的思想应用于算法设计之中,递归算法充分地利用了计算机系统内部机能,自动实现调用过程中对于相关且必要的信息的保存与恢复;分治算法是把一个问题划分为一个或多个子问题,每个子问题与原问题具有完全相同的解决思路,进而可以按照递归的思路进行求解。

2. 解:通过分治算法的一般设计步骤进行说明。

3. 解:int fibonacci(int n) {if(n<=1) return 1;return fibonacci(n-1)+fibonacci(n-2); }4. 解: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); } } 5. 解:①22*2)(−−=n n f n② )log *()(n n n f O =6. 解:算法略。

算法分析与设计第3章课后习题答案

算法分析与设计第3章课后习题答案

第3章作业解答设有4个矩阵连乘积ABCD ,设它们的维数分别为A:45×8,B:8×40,C:40×25,D:25×10,请求出它们的最优计算次序及对应的最少计算量。

解:设A 1=A, A 2=B, A 3=C, A 4=Dp 0=45,p 1=8,p 2=40,p 3=25,p 4=10 ,用两个二维数组m 和s 记录中间结果,其中,m[i][j]记录矩阵连乘积A[i:j]的最少计算量,s[i][j]记录A[i:j]的最优断开位置。

由动态规划思想,得递归式为:⎪⎩⎪⎨⎧<+++==-<≤j i p p p j k m k i m j i j i m j k i }],1[],[{min 0],[1jk i 其中,k 的取值有j-i 种可能:i,i+1,...,j-1. 计算过程如下: (1) m[i][i]=0, i=1,2,3,4 (2) 求m[i][i+1], i=1,2,3m[1][2]= p 0×p 1×p 2=45×8×40=14400 s[1][2]=1 m[2][3]= p 1×p 2×p 3=8×40×25=8000 s[2][3]=2 m[3][4]= p 2×p 3×p 4=40×25×10=10000 s[3][4]=3 (3) 求m[i][i+2], i=1,2m[1][3]=min{m[1][1]+m[2][3]+p 0×p 1×p 3, m[1][2]+m[3][3]+p 0×p 2×p 3 } =min{8000+45×8×25,14400+45×40×25} =min{17000, 59400} =17000 s[1][3]=1m[2][4]=min{m[2][2]+m[3][4]+p1×p2×p4, m[2][3]+m[4][4]+p1×p3×p4 }=min{10000+8×40×10,8000+8×25×10}=min{13200, 10000} =10000s[2][4]=3(4) 求m[i][i+3], i=1m[1][4]=min{m[1][1]+m[2][4]+p0×p1×p4 ,m[1][2]+m[3][4]+p0×p2×p4 ,m[1][3]+m[4][4]+p0×p3×p4 }=min{10000+45×8×10, 14400+10000+45×40×10, 17000+45×25×10 }=min{13600, 42400, 28250} =13600s[1][4]=1根据以上结果可得数组m, s如下:m[1][4]即A[1:4]的最少计算量,也即ABCD连乘积的最少计算量为13600。

算法设计与分析习题(3~5)

算法设计与分析习题(3~5)

算法设计和分析(第二版)习题答案(第三章)2010年06月15日星期二下午 03:51算法设计和分析(第二版)主编:吕国英习题答案第三章:1.#include<stdlib.h>#include<stdio.h>int main(int argc,char **argv){int n;int i,j,k;int *buf;printf("请输入n的数值:");scanf("%d",&n);buf=(int *)malloc(n*sizeof(int)); for(i=0;i<n;i++){buf[i]=2;}for(i=n-2;i>=0;i--)for(j=i;j>=0;j--){buf[j]+=2;}}for(k=0;k<=n-2;k++){if(buf[k]>=10){buf[k+1]+=buf[k]/10;buf[k]%=10;}}for(i=n-1;i>=0;i--)printf("%d",buf[i]); printf("\n");return 0;}2.#include<stdio.h>int main(int argc,char **argv)int buf[6][6];int i,j;printf("任意输入6个数字:");for(i=0;i<6;i++)scanf("%d",&buf[0][i]);for(i=0;i<5;i++){for(j=0;j<5;j++){buf[i+1][j+1]=buf[i][j];}buf[i+1][0]=buf[i][j];}for(i=0;i<6;i++){for(j=0;j<6;j++)printf("%d ",buf[i][j]);printf("\n");}return 0;}#include<stdio.h>#define N 7int main(int argc,char **argv) {int buf[N][N];int i,j,k,m,n;int a=0,b=N-1;int count=1;for(i=0;i<(N/2)+(N%2);i++) {for(j=a;j<=b;j++){buf[a][j]=count++;}for(k=a+1;k<=b;k++){buf[k][b]=count++;}for(m=b-1;m>=a;m--){buf[b][m]=count++;}for(n=b-1;n>a;n--){buf[n][a]=count++;}a++;b--;}for(i=0;i<N;i++){for(j=0;j<N;j++)printf("%5d",buf[i][j]);printf("\n");}return 0;}4.#include<stdio.h>#define N 5int main(int argc,char **argv) {int buf[N][N];int i,j,k;int count=1;int n=0;for(i=0;i<N;i++){for(k=0,j=n;j>=0;j--,k++) buf[j][k]=count++;n++;}for(i=0;i<N;i++){for(j=0;j<N-i;j++)printf("%5d",buf[i][j]);printf("\n");}return 0;}5.#include<stdio.h>#define N 5int main(int argc,char **argv) {int buf[N][N];int i,j;int a=0,b=N-1;int count=1;for(i=0;i<N/2+N%2;i++){for(j=a;j<=b;j++)buf[a][j]=count;for(j=a+1;j<=b;j++)buf[j][b]=count;for(j=b-1;j>=a;j--)buf[b][j]=count;for(j=b-1;j>a;j--)buf[j][a]=count;count++;a++;b--;}for(i=0;i<N;i++){for(j=0;j<N;j++)printf("%5d",buf[i][j]);printf("\n");}return 0;}6.#include<stdio.h>#include<stdlib.h>typedef struct s_node s_list;typedef s_list *link;struct s_node{char ch;int flag;link next;};link top;void push(char ch,int flag){link newnode;newnode=(link)malloc(sizeof(s_list)); newnode->ch=ch;newnode->flag=flag;newnode->next=NULL;if(top==NULL){top=newnode;}else{newnode->next=top;top=newnode;}}int pop(){int flag;link stack;if(top!=NULL){stack=top;top=top->next;flag=stack->flag;free(stack);}return flag;}int op(char ch){switch(ch){case '+':return 1;break;case '-':return 2;break;case '*':return 3;break;case '/':return 4;break;default:return 5;}}void nirnava(char *buf,int count)//count个数,buf数组{int bool=1;int min;int j;int i;int k;int flag;for(i=0;i<count;i++){if(buf[i]=='(')push(buf[i],i);if(buf[i]==')'){flag=pop();if(flag!=0){if((buf[flag-1]=='(')&&(buf[i+1]==')')) {buf[flag]='!';buf[i]='!';}min=op(buf[flag]);for(j=flag+1;j<i;j++) {if(buf[j]=='(') {push(buf[j],j);bool=0;continue;}elseif(buf[j]==')'){pop();bool=1;continue;}if(bool==1){if(min>op(buf[j]))min=op(buf[j]); }if(i<count-1){if((buf[i+1]=='+')||(buf[i+1]=='-')) {if(flag==0){buf[i]='!';buf[flag]='!';}elseif(op(buf[flag-1])<=min){buf[i]='!';buf[flag]='!';}}elseif((buf[i+1]=='*')||(buf[i+1]=='/')){if(flag==0){buf[i]='!';buf[flag]='!';}elseif((min>=op(buf[i+1])&&op(buf[flag-1])<=min)) {buf[i]='!';buf[flag]='!';}}}elseif(i==count-1){if(flag==0){buf[i]='!';buf[flag]='!';}elseif(op(buf[flag-1])<=min){buf[i]='!';buf[flag]='!';}}}}for(k=0;k<count;k++){if(buf[k]!='!') printf("%c",buf[k]);}printf("\n");}int main(void){char buf[255];int i;for(i=0;i<255;i++){scanf("%c",&buf[i]);if(buf[i]=='\n') break;}buf[i]='\0';nirnava(buf,i);return 0;}7.#include<stdio.h>#include<stdlib.h>int ack(int m,int n);int count=0;int main(int argc,char **argv) {int m,n;scanf("%d%d",&m,&n);printf("%d\n",ack(m,n));printf("%d\n",count);return 0;}int ack(int m,int n){count++;if(m==0)return n+1;elseif(n==0)return ack(m-1,1);elsereturn ack(m-1,ack(m,n-1));}8.#include<stdio.h>char buf[1024];int is_huiwen(int a,int count){if(a==count/2){return 1;}elseif(buf[a]==buf[count-a-1])return (is_huiwen(a-1,count))&&1;else{return 0;}}int main(void){int count;int i;for(i=0;i<1024;i++){scanf("%c",&buf[i]);if(buf[i]=='\n') break;}count=i;i--;printf("%d",is_huiwen(i,count)); return 0;}9.#include<stdio.h>char buf[100];int pos(int a,int b){if(b-a==1)return 1;elseif(b-a==0)return 1;elsereturn pos(a,b-1)+pos(a,b-2); }int main(void){int a,b;scanf("%d%d",&a,&b);printf("%d",pos(a,b));return 0;}10.#include<stdio.h>#define MAX 1024int buf[MAX];int main(void){int m,n;int i;scanf("%d%d",&m,&n);for(i=0;i<MAX;i++)buf[i]=0;i=0;while(buf[i%m]==0){buf[i%m]=1;i+=n;}for(i=0;i<m;i++){if(buf[i]==0) printf("%d ",i);}return 0;}11.#include<stdio.h>int main(void){int temp,temp1;int count=0;int n;int i;scanf("%d",&n);for(i=1;i<=n;i++){temp=i%10;if(temp==5)count++;elseif(temp==0){temp1=i;while((temp1%10)==0){temp1=temp1/10;count++;}}}printf("%d",count);return 0;}12.#include<stdio.h>int main(void){int count=0;int buf[53];int i,n;for(i=1;i<53;i++){buf[i]=1;}for(n=2;;n++){for(i=n;i<53;i+=n) {buf[i]=1-buf[i];count++;if(count>=104)break;}if(count>=104)}for(i=1;i<53;i++){if(buf[i]==1)printf("%d ",i);}printf("\n");return 0;}13.#include<stdio.h>int main(void){int a,b,c,d,e;for(a=1;a<=5;a++)for(b=1;b<=5;b++)if(a!=b)for(c=1;c<=5;c++)if(c!=a&&c!=b)for(d=1;d<=5;d++)if(d!=a&&d!=b&&d!=c)e=15-a-b-c-d;if(e!=a&&e!=b&&e!=c&&e!=d)if(((b==3)+(c==5)==1)&&((d==2)+(e==4)==1)&&((b==1) +(e==4)==1)&&((c==1)+(b==2)==1)&&((d==2)+(a==3)==1))printf("a=%d,b=%d,c=%d,d=%d,e=%d",a,b,c,d,e);}return 0;}14.#include<stdio.h>int main(void){int buf[3];int i;int mul;int temp;for(i=10;i<=31;i++){mul=i*i;temp=mul;buf[0]=temp%10;temp=temp/10;buf[1]=temp%10;temp=temp/10;buf[2]=temp;if((buf[0]==buf[1])||(buf[0]==buf[2])||(buf[1]==bu f[2])){printf("%d^2=%d\n",i,mul);}}return 0;}15.#include<stdio.h>int main(void){int a,b,c;for(a=1;a<=3;a++)for(b=1;b<=3;b++)if(a!=b){c=6-a-b;if(c!=a&&c!=b)if((a!=1)&&((c!=1)&&(c!=3))==1)printf("a=%d,b=%d,c=%d",a,b,c); }return 0;}16.#include<stdio.h>int main(void){int k;int n;scanf("%d",&n);k=(n%4==0)+(n%7==0)*2+(n%9==0)*4;switch(k){case 7:printf("all");break;case 6:printf("7 and 9");break;case 5:printf("4 and 9");break;case 4:printf("9");break;case 3:printf("4 and 7");break;case 2:printf("7");break;case 1:printf("4");break;case 0:printf("none");break;}return 0;}17.#include<stdio.h>int main(void){int a,b,c,d;printf("please think of a number between 1 and 100.\n"); printf("your number divided by 3 has a remainder of "); scanf("%d",&a);printf("your number divided by 4 has a remainder of "); scanf("%d",&b);printf("your number divided by 7 has a remainder of "); scanf("%d",&c);printf("let me think a moment...\n");d=36*c+28*a+21*b;while(d>84)d=d-84;printf("your number was %d\n",d);return 0;}18.#include<stdio.h>int main(void){int buf[10];int i,j;int mul;int temp1,temp2;int bool;for(i=5000;i<=9999;i++){bool=0;for(j=0;j<10;j++) buf[j]=0;temp1=i;while(temp1>0) {if((++buf[temp1%10])>1){bool=1;break;}temp1/=10;}if(bool==1) continue;mul=i*2;temp2=mul;while(temp2>0){if((++buf[temp2%10])>1){bool=1;break;}temp2/=10;}if(bool==1)continue;printf("2*%d=%d\n",i,mul);}return 0;}19.#include<stdio.h>#include<stdlib.h>int ppow(int a,int b){int mul=1;int i;for(i=0;i<b;i++){mul=a*mul;}return mul;}int main(void){int t;char buf[10];int i,j,k;int sum=0;for(i=0;i<10;i++){scanf("%c",&buf[i]);if(buf[i]=='\n') break;}buf[i]='\0';for(j=0;j<i;j++){if((buf[j]>='0')&&(buf[j]<='9')) buf[j]=buf[j]-48;elseif((buf[j]>='A')&&(buf[j]<='F'))buf[j]=buf[j]-55;elseexit(1);}k=0;for(j=i-1;j>=0;j--){t=ppow(16,k);sum=sum+t*(int)buf[j];k++;}printf("%d\n",sum);return 0;}20.#include<stdio.h>int main(void){int a;int b;int c;int i;int buf[10];for(a=10;a<=99;a++){for(i=0;i<10;i++)buf[i]=0;if((++buf[a%10]>1)||(++buf[a/10%10]>1)) continue;for(b=100;b<=999;b++){for(i=0;i<10;i++){if((i!=a%10)&&i!=a/10%10)buf[i]=0;}if((++buf[b%10]>1)||(++buf[b/10%10]>1)||(++buf[b/100%10] >1))continue;c=a*b;if(c<10000&&c>999){if((++buf[c%10]>1)||(++buf[c/10%10]>1)||(++buf[c /100%10]>1)||(++buf[c/1000%10]>1))continue;elseprintf("%d*%d=%d\n",a,b,c);}}}return 0;}21.#include<stdio.h>int main(void){int a;int b;int i;int t;int buf[10];int bool;for(a=317;a<1000;a++){bool=0;for(i=0;i<10;i++)buf[i]=0;if((++buf[a%10]>1)||(++buf[a/10%10]>1)||(++buf[a/1 00%10]>1))continue;b=a*a;t=b;for(i=0;i<6;i++){if(++buf[t%10]>1){bool=1;break;}t=t/10;}if(bool==1)continue;printf("%d^2=%d\n",a,b);}return 0;}22.#include<stdio.h>int main(void){int buf[100];int i;int n;int max;int temp;for(i=1;i<100;i++){scanf("%d",&buf[i]);if(buf[i]==0)break;}n=i;max=buf[1]+buf[2]+buf[3]+buf[4];for(i=2;i%10!=1;i++){temp=buf[i%10]+buf[(i+1)%10]+buf[(i+2)%10]+buf[(i+ 3)%10];if(temp>max)max=temp;}printf("max=%d\n",max);return 0;}23.#include<stdio.h>void nirnava(int n){if(n<10)printf("%d ",n);else{nirnava(n/10);printf("%d ",n%10);}}int main(void){int count=0;int n;int i;int t;scanf("%d",&n);t=n;while(t>0){printf("%d ",t%10);t=t/10;count++;}printf("\n");nirnava(n);printf("\n%d位数\n",count);}24.#include<stdio.h>int main(void){int buf[4]={2,3,5,7};int i,j,k,temp,m;int bool;int mul;for(i=0;i<4;i++)for(j=0;j<4;j++)for(k=0;k<4;k++)for(m=0;m<4;m++){bool=0;mul=(buf[i]+buf[j]*10+buf[k]*100)*buf[m];if(mul<1000)continue;temp=mul;while(temp>0){if((temp%10==2)||(temp%10==3)||(temp%10==5)||(temp%10==7 )){}else{bool=1;break;}temp/=10;}if(bool==0){printf("%d%d%d * %d= %d\n",buf[k],buf[j],buf[i],buf[m],mul);}}return 0;}25.#include<stdio.h>int main(void){int buf[4]={2,3,5,7};int i,j,k,m,n;int bool;int mul,mul1,mul2;int temp,temp1,temp2;for(i=0;i<4;i++)for(j=0;j<4;j++)for(k=0;k<4;k++)for(m=0;m<4;m++)for(n=0;n<4;n++){bool=0;mul=(buf[i]+buf[j]*10+buf[k]*100)*(buf[m]+buf[n] *10);mul1=(buf[i]+buf[j]*10+buf[k]*100)*buf[m];mul2=(mul-mul1)/10;if((mul<10000)||(mul1<1000)||(mul2<1000)) continue;temp=mul;temp1=mul1;temp2=mul2;while(temp>0){if((temp%10==2)||(temp%10==3)||(temp%10==5)||(temp%10= =7)){}else{bool=1;break;}temp/=10;}if(bool==0){while(temp1>0){if((temp1%10==2)||(temp1%10==3)||(temp1%10==5) ||(temp1%10==7)){}else{bool=1;break;}temp1/=10;}}if(bool==0)while(temp2>0){if((temp2%10==2)||(temp2%10==3)||(temp2%10==5)||(t emp2%10==7)){}else{bool=1;break;}temp2/=10;}if(bool==0){printf("第一行 : %d%d%d\n第二行 : %d%d\n第三行 : %d\n 第四行 : %d\n第五行 : %d\n\n\n\n\n",buf[i],buf[j],buf[k],buf[m],buf[n],mul1,mu l2,mul);}}return 0;}26.#include<stdio.h>//从a到b是不是循环节int is_xunhuan(int *buf,int a,int b) {int i;if(a==b){for(i=1;i<10;i++){if(buf[a]==buf[a+i]){}elsereturn 0;}}elsefor(i=a;i<=b;i++){if(buf[i]==buf[i+b-a+1]){}else{return 0;}return 1;}int main(void){int buf[1024];int yushu;int m,n;int i,j,k;scanf("%d%d",&m,&n); yushu=m;buf[0]=0;i=1;while(yushu!=0){yushu=yushu*10;buf[i]=yushu/n;yushu=yushu%n;i++;if(i==1024) break;if(i<1024){printf("有限小数\n");printf("%d.",buf[0]);for(j=1;j<i;j++)printf("%d",buf[j]);printf("\n");}else{printf("循环小数\n");for(i=1;i<100;i++)for(j=i;j<200;j++){if(is_xunhuan(buf,i,j)){printf("%d.",buf[0]);if(i>1){for(k=1;k<i;k++)printf("%d",buf[k]);printf("(");for(k=i;k<=j;k++)printf("%d",buf[k]);printf(")");printf("\n");return 0;}}}return 0;}27.#include<stdio.h>int main(void){int n;char eng[12][10]={"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};scanf("%d",&n);printf("%s\n",eng[n-1]);return 0;}算法设计和分析(第二版)主编:吕国英习题答案第四章1.#include<stdio.h>int main(void){int buf[100];int n;int i,j,k;scanf("%d",&n);for(i=0;i<n;i++)buf[i]=2;for(i=0;i<n-1;i++){for(j=0;j<n-i-1;j++) {buf[j]+=2;}}for(j=0;j<n;j++){if(buf[j]>=10){buf[j+1]+=buf[j]/10;buf[j]=buf[j]%10;}}for(i=n-1;i>=0;i--)printf("%d",buf[i]); printf("\n");return 0;}2.#include<stdio.h>int main(void){int n=2;int i;for(i=1;i<=9;i++){n=(n+2)*2;}printf("%d\n",n);return 0;}3.#include<stdio.h>int main(void){int a=54;int n;int m;printf("计算机先拿3张牌\n");a=a-3;while(a>=0){printf("还剩%d张牌\n",a);printf("你拿几张?请输入:");scanf("%d",&n);if(n>4||n<1||n>a){printf("错误!重新拿牌\n");continue;}a=a-n;printf("还剩%d张牌\n",a);if(a==0)break;m=5-n;printf("计算机拿%d\n",m);a=a-m;}return 0;}4.#include<stdio.h>int d;int a1,a2;int fun(int n);int main(void){int n;printf("n=?,d=?,a1=?,a2=?");scanf("%d%d%d%d\n",&n,&d,&a1,&a2); printf("%d\n",fun(n));return 0;}int fun(int n){if(n==1)return a1;if(n==2)return a2;return fun(n-2)-(fun(n-1)-d)*2;}5.#include<stdio.h>char chess[8][8];int is_safe(int row,int col);int queen(int row,int col,int n); int main(void){int i,j;for(i=0;i<8;i++)for(j=0;j<8;j++)chess[i][j]='X';queen(0,0,0);for(i=0;i<8;i++){for(j=0;j<8;j++)printf("%c ",chess[i][j]);printf("\n");}return 0;}int is_safe(int row,int col){int i,j;for(i=0;i<8;i++){if(chess[row][i]=='Q') return 0;。

算法设计与分析书后参考答案

算法设计与分析书后参考答案

参考答案第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)由于顶层设计和底层实现局部化,在设计中出现的差错也是局部的,因而容易查找也容易纠正,在设计中常常要做的增、删、改也都是局部的,因而也都容易进行。

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

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

算法分析与设计习题集基础篇1、算法有哪些特点?它有哪些特征?它和程序的主要区别是什么?特点:就是一组有穷的规则,它规定了解决某一特定类型问题的一系列运算(书上定义)特征:输入、输出、有穷性、明确性、有效性区别:算法是完成特定任务的有限指令集。

程序是用计算机语言编写的写成特定任务的指令序列。

2、算法的时间复杂度指的是什么?如何表示?算法的时间复杂度是一个函数,它定量描述了该算法的运行时间。

这是一个关于代表算法输入值的字符串的长度的函数。

时间复杂度常用大O符号表述,不包括这个函数的低阶项和首项系数。

(百度百科)3、算法的空间复杂度指的是什么?如何表示?一个程序的空间复杂度是指运行完一个程序所需内存的大小。

利用程序的空间复杂度,可以对程序的运行所需要的内存多少有个预先估计。

一个程序执行时除了需要存储空间和存储本身所使用的指令、常数、变量和输入数据外,还需要一些对数据进行操作的工作单元和存储一些为现实计算所需信息的辅助空间。

程序执行时所需存储空间包括以下两部分。

(1)固定部分。

这部分空间的大小与输入/输出的数据的个数多少、数值无关。

主要包括指令空间(即代码空间)、数据空间(常量、简单变量)等所占的空间。

这部分属于静态空间。

(2)可变空间,这部分空间的主要包括动态分配的空间,以及递归栈所需的空间等。

这部分的空间大小与算法有关。

一个算法所需的存储空间用f(n)表示。

S(n)=O(f(n))其中n为问题的规模,S(n)表示空间复杂度。

答:最坏情况时间复杂性:最好情况时间复杂性::I*是DN中使T(N, I*)达到Tmax(N)的合法输入;P(I)是在算法的应用中出现输入I的概率10、限界函数的功能是什么?答:用限界函数剪去得不到最优解的子树11、设某一函数定义如下:编写一个递归函数计算给定x的M(x)的值。

本函数是一个递归函数,其递归出口是:M(x)= x-10x>100递归体是:M(M(x+11))x ≤100实现本题功能的递归函数如下:intm ( intx ){ int y;if ( x>100 )return(x-10 );else {y =m(x+11) ;return (m (y ));}procedure M(x)if x>100 thenreturn(x-10)elsereturn M(M(x+11))endifend M12、已知一个顺序表中的元素按元素值非递减有序排列,编写一个函数删除表中多余的值相同的元素。

算法设计与分析基础第二版课后答案

算法设计与分析基础第二版课后答案

算法设计与分析基础第二版课后答案【篇一:算法设计与分析基础课后习题答案(中文版)】class=txt>习题1.15..证明等式gcd(m,n)=gcd(n,m mod n)对每一对正整数m,n都成立. hint:根据除法的定义不难证明:?如果 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=mgcd(m,n)=gcd(n,m)并且这种交换处理只发生一次.7.a.对于所有1≤m,n≤10的输入, euclid算法最少要做几次除法?(1次)b. 对于所有1≤m,n≤10的输入, euclid算法最多要做几次除法?(5次)gcd(5,8)习题1.2 1.(农夫过河)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//输出:实根或者无解信息if a≠0d←b*b-4*a*c if d0temp←2*ax1←(-b+sqrt(d))/temp x2←(-b-sqrt(d))/temp return x1,x2else if d=0 return –b/(2*a) else return “no real roots” else //a=0 if b≠0 return –c/b else //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=1 while 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 ith element with the last element and decreasethe array size of 1b. replace the ith element with a special symbol that cannot be a value of the arr ay’s element(e.g., 0 for an array of positive numbers ) to mark the ith position is empty. (―lazy deletion‖)第2章习题2.1a. 这个断言是正确的。

算法设计与分析课后习题

算法设计与分析课后习题

算法设计与分析课后习题(总8页)--本页仅作为文档封面,使用时请直接删除即可----内页可以根据需求调整合适字体及大小--第一章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)).第二章算法分析题2-3 设a[0:n-1]是已经排好序的数组。

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

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

第一章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 =。

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

Thisfile contains the exercises,hints,and solutions for Chapter3of the book”Introduction to the Design and Analysis of Algorithms,”2nd edition,by A.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 .Exercises3.11.a.Give an example of an algorithm that should not be considered anapplication of the brute-force approach.b.Give an example of a problem that cannot be solved by a brute-forcealgorithm.2.a.What is the efficiency of the brute-force algorithm for computing a nas a function of n?As a function of the number of bits in the binary representation of n?b.If you are to compute a n mod m where a>1and n is a large positiveinteger,how would you circumvent the problem of a very large magnitude of a n?3.For each of the algorithms in Problems4,5,and6of Exercises2.3,tellwhether or not the algorithm is based on the brute-force approach.4.a.Design a brute-force algorithm for computing the value of a polynomialp(x)=a n x n+a n−1x n−1+...+a1x+a0at a given point x0and determine its worst-case efficiency class.b.If the algorithm you designed is inΘ(n2),design a linear algorithmfor this problem.c.Is it possible to design an algorithm with a better than linear efficiencyfor this problem?5.Sort the list E,X,A,M,P,L,E in alphabetical order by selection sort.6.Is selection sort stable?(The definition of a stable sorting algorithm wasgiven in Section1.3.)7.Is it possible to implement selection sort for linked lists with the sameΘ(n2)efficiency as the array version?8.Sort the list E,X,A,M,P,L,E in alphabetical order by bubble sort.9.a.Prove that if bubble sort makes no exchanges on its pass through a list,the list is sorted and the algorithm can be stopped.1b.Write a pseudocode of the method that incorporates this improve-ment.c.Prove that the worst-case efficiency of the improved version is quadratic.10.Is bubble sort stable?11.Alternating disks You have a row of2n disks of two colors,n dark andn light.They alternate:dark,light,dark,light,and so on.You want to get all the dark disks to the right-hand end,and all the light disks to the left-hand end.The only moves you are allowed to make are those which interchange the positions of two neighboring disks.Design an algorithm for solving this puzzle and determine the number of moves it makes.[Gar99],p.752Hints to Exercises3.11.a.Think of algorithms that have impressed you with their efficiencyand/or sophistication.Neither characteristic is indicative of a brute-force algorithm.b.Surprisingly,it is not a very easy question to answer.Mathemati-cal problems(including those you have studied in your secondary school and college courses)are a good source of such examples.2.a.Thefirst question was all but answered in the section.Expressingthe answer as a function of the number of bits can be done by using the formula relating the two metrics.b.How can we compute(ab)mod m?3.It helps to have done the exercises in question.4.a.The most straightforward algorithm,which is based on substituting x0into the formula,is quadratic.b.Analyzing what unnecessary computations the quadratic algorithmdoes should lead you to a better(linear)algorithm.c.How many coefficients does a polynomial of degree n have?Can onecompute its value at an arbitrary point without processing all of them?5.Just trace the algorithm on the input given.(It was done for anotherinput in the section.)6.Although the majority of elementary sorting algorithms are stable,do notrush with your answer.A general remark about stability made in Section1.3,where the notion of stability is introduced,could be helpful,too. 7.Generally speaking,implementing an algorithm for a linked list poses prob-lems if the algorithm requires accessing the list’s elements not in a sequen-tial order.8.Just trace the algorithm on the input given.(See an example in thesection.)9.a.A list is sorted if and only if all its adjacent elements are in a correctorder.Why?b.Add a booleanflag to register the presence or absence of switches.c.Identify worst-case inputsfirst.10.Can bubble sort change the order of two equal elements in its input?311.Thinking about the puzzle as a sorting-like problem may and may notlead you to the most simple and efficient solution.4Solutions to Exercises3.11.a.Euclid’s algorithm and the standard algorithm forfinding the binaryrepresentation of an integer are examples from the algorithms previously mentioned in this book.There are,of course,many more examples in its other chapters.b.Solving nonlinear equations or computing definite integrals are ex-amples of problems that cannot be solved exactly(except for special in-stances)by any algorithm.2.a.M(n)=n≈2b where M(n)is the number of multiplications made bythe brute-force algorithm in computing a n and b is the number of bits in the n’s binary representation.Hence,the efficiency is linear as a function of n and exponential as a function of b.b.Perform all the multiplications modulo m,i.e.,a i mod m=(a i−1mod m·a mod m)mod m for i=1,...,n.3.Problem4(computes n1i2):yesProblem5(computes the range of an array’s values):yesProblem6(checks whether a matrix is symmetric):yes4.a.Here is a pseudocode of the most straightforward version:Algorithm BruteForcePolynomialEvaluation(P[0..n],x)//The algorithm computes the value of polynomial P at a given point x //by the“highest-to-lowest term”brute-force algorithm//Input:Array P[0..n]of the coefficients of a polynomial of degree n, //stored from the lowest to the highest and a number x//Output:The value of the polynomial at the point xp←0.0for i←n downto0dopower←1for j←1to i dopower←power∗xp←p+P[i]∗powerreturn pWe will measure the input’s size by the polynomial’s degree n.The ba-sic operation of this algorithm is a multiplication of two numbers;the number of multiplications M(n)depends on the polynomial’s degree only.5Although it is not difficult tofind the total number of multiplications in this algorithm,we can count just the number of multiplications in the algorithm’s inner-most loop tofind the algorithm’s efficiency class:M(n)=ni=0ij=11=ni=0i==n(n+1)2∈Θ(n2).b.The above algorithm is very inefficient:we recompute powers of x againand again as if there were no relationship among them.Thus,the obviousimprovement is based on computing consecutive powers more efficiently.If we proceed from the highest term to the lowest,we could computex i−1by using x i but this would require a division and hence a special treatment for x=0.Alternatively,we can move from the lowest term tothe highest and compute x i by using x i−1.Since the second alternativeuses multiplications instead of divisions and does not require any specialtreatment for x=0,it is both more efficient and cleaner.It leads to thefollowing algorithm:Algorithm BetterBruteForcePolynomialEvaluation(P[0..n],x)//The algorithm computes the value of polynomial P at a given point x//by the“lowest-to-highest term”algorithm//Input:Array P[0..n]of the coefficients of a polynomial of degree n,//from the lowest to the highest,and a number x//Output:The value of the polynomial at the point xp←P[0];power←1for i←1to n dopower←power∗xp←p+P[i]∗powerreturn pThe number of multiplications here isM(n)=ni=12=2n(while the number of additions is n),i.e.,we have a linear algorithm. Note:Horner’s Rule discussed in Section6.5needs only n multiplications (and n additions)to solve this problem.c.No,because any algorithm for evaluating an arbitrary polynomial of degree n at an arbitrary point x must process all its n+1coefficients. (Note that even when x=1,p(x)=a n+a n−1+...+a1+a0,which needs at least n additions to be computed correctly for arbitrary a n,a n−1,...,a0.)65.E X A M P L EA X E M P L EA E X M P L EA E E M P L XA E E L P M XA E E L M P XA E E L M P X6.Selection sort is not stable:In the process of exchanging elements that arenot adjacent to each other,the algorithm can reverse an ordering of equal elements.The list2 ,2 ,1is such an example.7.Yes.Both operations–finding the smallest element and swapping it–canbe done as efficiently with a linked list as with an array.8.E,X,A,M,P,L,EE↔X?↔A M P L EE A X↔M P L EE A M X↔P L EE A M P X↔L EE A M P L X↔EE A M P L E|XE↔A M P L EA E↔M?↔P?↔L EA E M L P↔EA E M L E|PA↔E?↔M?↔L EA E L M↔EA E L E|MA↔E?↔L?↔EA E E|LA↔E?↔E?↔LThe algorithm can be stopped here(see the next question).9.a.Pass i(0≤i≤n−2)of bubble sort can be represented by the followingdiagram:A0,...,A j↔A j+1,...,A n−i−1≤|A n−i≤...≤A n−1in theirfinal positions7If there are no swaps during this pass,thenA 0≤A 1≤...≤A j ≤A j +1≤...≤A n −i −1,with the larger (more accurately,not smaller)elements in positions n −i through n −1being sorted during the previous iterations.b.Here is a pseudocode for the improved version of bubble sort:Algorithm BetterBubbleSort (A [0..n −1])//The algorithm sorts array A [0..n −1]by improved bubble sort//Input:An array A [0..n −1]of orderable elements//Output:Array A [0..n −1]sorted in ascending ordercount ←n −1//number of adjacent pairs to be comparedsflag ←true //swap flagwhile sflag dosflag ←falsefor j ←0to count −1doif A [j +1]<A [j ]swap A [j ]and A [j +1]sflag ←truecount ←count −1c.The worst-case inputs will be strictly decreasing arrays.For them,the improved version will make the same comparisons as the original version,which was shown in the text to be quadratic.10.Bubble sort is stable.It follows from the fact that it swaps adjacentelements only,provided A [j +1]<A [j ].5.Here is a simple and efficient (in fact,optimal)algorithm for this problem:Starting with the first and ending with the last light disk,swap it with each of the i (1≤i ≤n )dark disks to the left of it.The i th iteration of the algorithm can be illustrated by the following diagram,in which 1s and 0s correspond to the dark and light disks,respectively.00..0 i −111..1 i −11010..10⇒00..00 i 11..11 i10..10The total number of swaps made is equal to n i =1i =n (n +1)/2.8Exercises3.21.Find the number of comparisons made by the sentinel version of sequentialsearcha.in the worst case.b.in the average case if the probability of a successful search is p(0≤p≤1).2.As shown in Section2.1,the average number of key comparisons made bysequential search(without a sentinel,under standard assumptions about its inputs)is given by the formulaC avg(n)=p(n+1)2+n(1−p),where p is the probability of a successful search.Determine,for afixed n, the values of p(0≤p≤1)for which this formula yields the largest value of C avg(n)and the smallest value of C avg(n).3.Gadgets testing Afirm wants to determine the highestfloor of its n-story headquarters from which a gadget can fall with no impact on the gadget’s functionality.Thefirm has two identical gadgets to experiment with.Design an algorithm in the best efficiency class you can to solve this problem.4.Determine the number of character comparisons made by the brute-forcealgorithm in searching for the pattern GANDHI in the textTHERE_IS_MORE_TO_LIFE_THAN_INCREASING_ITS_SPEED(Assume that the length of the text–it is47characters long–is known before the search starts.)5.How many comparisons(both successful and unsuccessful)are made by thebrute-force string-matching algorithm in searching for each of the following patterns in the binary text of1000zeros?a.00001b.10000c.010106.Give an example of a text of length n and a pattern of length m thatconstitutes the worst-case input for the brute-force string-matching al-gorithm.Exactly how many character comparisons are made for such input?7.Write a visualization program for the brute-force string-matching algo-rithm.98.In solving the string-matching problem,would there be any advantage incomparing pattern and text characters right-to-left instead of left-to-right?9.Consider the problem of counting,in a given text,the number of substringsthat start with an A and end with a B.(For example,there are four such substrings in CABAAXBYA.)(a)Design a brute-force algorithm for this problem and determine itsefficiency class.(b)Design a more efficient algorithm for this problem[Gin04].10.Word Find A popular diversion in the United States,Word Find,asksthe player tofind each of a given set of words in a square tablefilled with single letters.A word can read horizontally(left or right),vertically(up or down),or along a45degree diagonal(in any of the four directions), formed by consecutively adjacent cells of the table;it may wrap around the table’s boundaries but it must read in the same direction with no zigzagging.The same cell of the table may be used in different words, but,in a given word,the same cell may be used no more than once.Writea computer program for solving this puzzle.11.Battleship game Write a program for playing Battleship(a classic strat-egy game)on the computer which is based on a version of brute-force pattern matching.The rules of the game are as follows.There are two opponents in the game(in this case,a human player and the computer).The game is played on two identical boards(10-by-10tables of squares) on which each opponent places his or her ships,not seen by the opponent.Each player hasfive ships,each of which occupies a certain number of squares on the board:a destroyer(2squares),a submarine(3squares),a cruiser(3squares),a battleship(4squares),and an aircraft carrier(5squares).Each ship is placed either horizontally or vertically,with no two ships touching each other.The game is played by the opponents taking turns“shooting”at each other’s ships.A result of every shot is displayed as either a hit or a miss.In case of a hit,the player gets to go again and keeps playing until this player misses.The goal is to sink all the oppo-nent’s ships before the opponent succeeds in doing itfirst.(To sink a ship, all squares occupied by the ship must be hit.)10Hints to Exercises3.21.Modify the analysis of the algorithm’s version in Section2.1.2.As a function of p,what kind of function is C avg?3.Solve a simpler problem with a single gadgetfirst.Then design a betterthan linear algorithm for the problem with two gadgets.4.The content of this quote from Mahatma Gandhi is more thought provok-ing than this drill.5.For each input,one iteration of the algorithm yields all the informationyou need to answer the question.6.It will suffice to limit your search for an example to binary texts andpatterns.7.You may use either bit strings or a natural language text for the visual-ization program.It would be a good idea to implement,as an option,a search for all occurrences of a given pattern in a given text.8.The answer,surprisingly,is yes.9.a.For a given occurrence of A in the text,what are the substrings youneed to count?b.For a given occurrence of B in the text,what are the substrings youneed to count?10.Test your program thoroughly.Be especially careful about a possibilityof words read diagonally with wrapping around the table’s border.11.A(very)brute-force algorithm can simply shoot at adjacent feasible cellsstarting at,say,one of the corners of the board.Can you suggest a better strategy?(You can investigate relative efficiencies of different strategies by making two programs implementing them play each other.)Is your strategy better than the one that shoots at randomly generated cells of the opponent’s board?11Solutions to Exercises 3.21.a.C worst (n )=n +1.b.C avg (n )=(2−p )(n +1)2.In the manner almost identical to the analysis in Section 2.1,we obtainC avg (n )=[1·p n +2·p n +...+i ·p n +...+n ·p n ]+(n +1)·(1−p )=p n [1+2+...+i +...+n ]+(n +1)(1−p )=p n n (n +1)2+(n +1)(1−p )=(2−p )(n +1)2.2.The expressionp (n +1)2+n (1−p )=p n +12+n −np =n −p (n −n +12)=n −n −12p is a linear function of p .Since the p ’s coefficient is negative for n >1,the function is strictly decreasing on the interval 0≤p ≤1from n to (n +1)/2.Hence p =0and p =1are its maximum and minimum points,respectively,on this interval.(Of course,this is the answer we should expect:The average number of comparisons should be the largest when the probability of a successful search is 0,and it should be the smallest when the probability of a successful search is 1.)3.Drop the first gadget from floors √n ,2 √n ,and so on until either the floor i √n a drop from which makes the gadget malfunction is reached or no such floor in this sequence is encountered before the top of thebuilding is reached.In the former case,the floor to be found is higher than (i −1) √n and lower than i √n .So,drop the second gadget from floors (i −1) √n +1,(i −1) √n +2,and so on until the first floor a drop from which makes the gadget malfunction is reached.The floor immediately preceeding that floor is the floor in question.If no drop in the first-pass sequence resulted in the gadget’s failure,the floor in question ishigher than i √n ,the last tried floor of that sequence.Hence,continue the successive examination of floors i √n +1,i √n +2,and so on until either a failure is registered or the last floor is reached.The number of times the two gadgets are dropped doesn’t exceed √n + √n ,which puts it in O (√n ).4.43comparisons.The algorithm will make 47−6+1=42trials:In the first one,the G of the pattern will be aligned against the first T of the text;in the last one,it will be aligned against the last space.On each but one trial,the algorithm will make one unsuccessful comparison;on one trial–when the G of the pattern is aligned against the G of the text –it will make two12comparisons.Thus,the total number of character comparisons will be 41·1+1·2=43.5.a.For the pattern00001,the algorithm will make four successful and oneunsuccessful comparison on each of its trials and then shift the pattern one position to the right:000000000000000100001etc.00001 The total number of character comparisons will be C=5·996=4980.b.For the pattern10000,the algorithm will make one unsuccessful com-parison on each of its trials and then shift the pattern one position to the right:000000000001000010000etc.10000 The total number of character comparisons will be C=1·996=996.c.For the pattern01010,the algorithm will make one successful andone unsuccessful comparison on each of its trials and then shift the pat-tern one position to the right:000000000000101001010etc.01010 The total number of character comparisons will be C=2·996=1,992.6.The text composed of n zeros and the pattern0 01is an example ofm−1the worst-case input.The algorithm will make m(n−m+1)character comparisons on such input.7.n/aparing pairs of the pattern and text characters righ-to-left can allowfarther pattern shifts after a mismatch.This is the main insight the two string matching algoirthms discussed in Section7.2are based on.(As a specific example,consider searching for the pattern11111in the text of one thousand zeros.)139.a.Note that the number of desired substrings that starts with an A at agiven position i(0≤i<n−1)in the text is equal to the number of B’s to the right of that position.This leads to the follwing simple algorithm:Initialize the count of the desired substrings to0.Scan the text left to right doing the following for every character except the last one:If an A is encountered,count the number of all the B’s following it and add this number to the count of desired substrings.After the scan ends,return the last value of the count.For the worst case of the text composed of n A’s,the total number of character comparisons isn+(n−1)+...+2=n(n+1)/2−1∈Θ(n2).b.Note that the number of desired substrings that ends with a B ata given position i(0<i≤n−1)in the text is equal to the number of A’sto the left of that position.This leads to the follwing algorithm:Initialize the count of the desired substrings and the count of A’s en-countered to0.Scan the text left to right until the text is exhausted and do the following.If an A is encountered,increment the A’s count;if aB is encountered,add the current value of the A’s count to the desiredsubstring count.After the text is exhausted,return the last value of the desired substring count.Since the algorithm makes a single pass through a given text spending constant time on each of its characters,the algorihtm is linear.10.n/a11.n/a14Exercises3.31.Can you design a more efficient algorithm than the one based on the brute-force strategy to solve the closest-pair problem for n points x1,...,x n on the real line?2.Let x1<x2<...<x n be real numbers representing coordinates of nvillages located along a straight road.A post office needs to be built in one of these villages.a.Design an efficient algorithm tofind the post-office location minimizingthe average distance between the villages and the post office.b.Design an efficient algorithm tofind the post-office location minimizingthe maximum distance from a village to the post office.3.a. There are several alternative ways to define a distance between twopoints P1=(x1,y1)and P2=(x2,y2).In particular,the Manhattan distance is defined asd M(P1,P2)=|x1−x2|+|y1−y2|.Prove that d M satisfies the following axioms that every distance function must satisfy:(i)d M(P1,P2)≥0for any two points P1and P2and d M(P1,P2)=0if and only if P1=P2;(ii)d M(P1,P2)=d M(P2,P1);(iii)d M(P1,P2)≤d M(P1,P3)+d M(P3,P2)for any P1,P2,and P3.b.Sketch all the points in the x,y coordinate plane whose Manhattandistance to the origin(0,0)is equal to1.Do the same for the Euclidean distance.c. True or false:A solution to the closest-pair problem does not dependon which of the two metrics–d E(Euclidean)or d M(Manhattan)–is used.4.Odd piefight There are n≥3people positioned in afield(Euclideanplane)so that each has a unique nearest neighbor.Each person has a cream pie.At a signal,everybody hurles his or her pie at the nearest neighbor.Assuming that n is odd and that nobody can miss his or her target,true or false:There always remains at least one person not hit bya pie?[Car79].5.The closest-pair problem can be posed in k-dimensional space in whichthe Euclidean distance between two points P =(x 1,...,x k)and P =15(x 1,...,x k)is defined asd(P ,P )=ks=1(x s−x s)2.What is the time-efficiency class of the brute-force algorithm for the k-dimensional closest-pair problem?6.Find the convex hulls of the following sets and identify their extreme points(if they have any).a.a line segmentb.a squarec.the boundary of a squared.a straight line7.Design a linear-time algorithm to determine two extreme points of theconvex hull of a given set of n>1points in the plane.8.What modification needs to be made in the brute-force algorithm for theconvex-hull problem to handle more than two points on the same straight line?9.Write a program implementing the brute-force algorithm for the convex-hull problem.10.Consider the following small instance of the linear programming problem:maximize3x+5ysubject to x+y≤4x+3y≤6x≥0,y≥0a.Sketch,in the Cartesian plane,the problem’s feasible region de-fined as the set of points satisfying all the problem’s constraints.b.Identify the region’s extreme points.c.Solve the optimization problem given by using the following theorem:A linear programming problem with a nonempty bounded feasible regionalways has a solution,which can be found at one of the extreme points of its feasible region.16Hints to Exercises3.31.Sorting n real numbers can be done in O(n log n)time.2.a.Solving the problem for n=2and n=3should lead you to the criticalinsight.b.Where would you put the post office if it would not have to be atone of the village locations?3.a.Check requirements(i)—(iii)by using basic properties of absolute values.b.For the Manhattan distance,the points in question are defined byequation|x−0|+|y−0|=1.You can start by sketching the points in the positive quadrant of the coordinate system(i.e.,the points for which x,y≥0)and then sketch the rest by using the symmetries.c.The assertion is false.You can choose,say,P1(0,0),P2(1,0)andfind P3to complete a counterexample.4.True;prove it by mathematical induction.5.Your answer should be a function of two parameters:n and k.A specialcase of this problem(for k=2)was solved in the text.6.Review the examples given in the section.7.Some of the extreme points of a convex hull are easier tofind than others.8.If there are other points of a given set on the straight line through P i andP j,which of all these points need to be preserved for further processing?9.Your program should work for any set of n distinct points,including setswith many colinear points.10.a.The set of points satisfying inequality ax+by≤c is the half-plane ofthe points on one side of the straight line ax+by=c,including all the points on the line itself.Sketch such a half-plane for each of the inequal-ities andfind their intersection.b.The extreme points are the vertices of the polygon obtained in part a.pute and compare the values of the objective function at the ex-treme points.17Solutions to Exercises 3.31.Sort the numbers in ascending order,compute the differences between ad-jacent numbers in the sorted list,and find the smallest such difference.If sorting is done in O (n log n )time,the running time of the entire algorithm will be inO (n log n )+Θ(n )+Θ(n )=O (n log n ).2.a.If we put the post office at location x i ,the average distance between it and all the points x 1<x 2<...<x n is given by the formula 1n n j =1|x j −x i |.Since the number of points n stays the same,we can ignore the multiple 1n and minimizen j =1|x j −x i |.We’ll have to consider the cases of even and odd n separately.Let n be even.Consider first the case of n =2.The sum |x 1−x |+|x 2−x |is equal to x 2−x 1,the length of the interval with the endpoints at x 1and x 2,for any point x of this interval (including the endpoints),and it is larger than x 2−x 1for any point x outside of this interval.This implies that for any even n,the sumnj =1|x j −x |=[|x 1−x |+|x n −x |]+[|x 2−x |+|x n −1−x |]+...+[|x n/2−x |+|x n/2+1−x |]is minimized when x belongs to each of the intervals [x 1,x n ]⊃[x 2,x n −1]⊃...⊃[x n/2,x n/2+1].If x must be one of the points given,either x n/2or x n/2+1solves the problem.Let n >1be odd.Then,the sum n j =1|x j −x |is minimized when x =x n/2 ,the point for which the number of the given points to the left of it is equal to the number of the given points to the right of it.Note that the point x n/2 –the n/2 th smallest called the median –solves the problem for even n ’s as well.For a sorted list implemented as an array,the median can be found in Θ(1)time by simply returning the n/2 th.element of the array.(Section 5.6provides a more general discussion of algorithms for computing the median.)b.Assuming that the points x 1,x 2,...,x n are given in increasing order,the answer is the point x i that is the closest to m =(x 1+x n )/2,the middle point between x 1and x n .(The middle point would be the obvious solution if the post-post office didn’t have to be at one of the given locations.)Indeed,if we put the post office at any location x i to the left of m,the longest distance from a village to the post office would be x n −x i ;this distance is minimal for the rightmost among such points.If we put the post office at any location x i to the right of m,the longest distance from a village to the post office would be x i −x 1;this distance is minimal for the leftmost among such points.Algorithm PostOffice1(P )//Input:List P of n (n ≥2)points x 1,x 2,...,x n in increasing order18。

相关文档
最新文档