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

合集下载

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

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

第一章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.14.设计一个计‎算的算法,n是任意正‎整数。

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

算法求//输入:一个正整数‎n2//输出:。

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

b. 用欧几里德‎算法求gc‎d(31415‎,14142‎),比检查mi‎n{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可知计‎算g cd(31415‎,14142‎)欧几里德算‎法做了11‎次除法。

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

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

算法设计与分析第二版课后习题及解答(可编辑)

算法设计与分析第二版课后习题及解答(可编辑)

算法设计与分析第二版课后习题及解答算法设计与分析基础课后练习答案习题1.14.设计一个计算的算法,n是任意正整数。

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

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

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

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

a. gcd31415, 14142 gcd14142, 3131 gcd3131, 1618 gcd1618, 1513 gcd1513, 105 gcd1513, 105 gcd105, 43 gcd43, 19 gcd19, 5 gcd5, 4 gcd4, 1 gcd1, 0 1.b.有a可知计算gcd(31415,14142)欧几里德算法做了11次除法。

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

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

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

故gcdm,ngcdn,r7.对于第一个数小于第二个数的一对数字,欧几里得算法将会如何处理?该算法在处理这种输入的过程中,上述情况最多会发生几次?Hint:对于任何形如0mn的一对数字,Euclid算法在第一次叠代时交换m和n, 即gcdm,ngcdn,m并且这种交换处理只发生一次.8.a.对于所有1≤m,n≤10的输入, Euclid算法最少要做几次除法?1次b. 对于所有1≤m,n≤10的输入, Euclid算法最多要做几次除法?5次gcd5,8习题1.21.农夫过河P?农夫W?狼 G?山羊 C?白菜2.过桥问题1,2,5,10---分别代表4个人, f?手电筒4. 对于任意实系数a,b,c, 某个算法能求方程ax^2+bx+c0的实根,写出上述算法的伪代码可以假设sqrtx是求平方根的函数算法Quadratica,b,c//求方程ax^2+bx+c0的实根的算法//输入:实系数a,b,c//输出:实根或者无解信息If a≠0D←b*b-4*a*cIf D0temp←2*ax1←-b+sqrtD/tempx2←-b-sqrtD/tempreturn x1,x2else if D0 return ?b/2*ael se return “no real roots”else //a0if b≠0 return ?c/belse //ab0if c0 return “no real numbers”else return “no real roots”5. 描述将十进制整数表达为二进制整数的标准算法a.用文字描述b.用伪代码描述解答:a.将十进制整数转换为二进制整数的算法输入:一个正整数n输出:正整数n相应的二进制数第一步:用n除以2,余数赋给Kii0,1,2,商赋给n第二步:如果n0,则到第三步,否则重复第一步第三步:将Ki按照i从高到低的顺序输出b.伪代码算法 DectoBinn//将十进制整数n转换为二进制整数的算法//输入:正整数n//输出:该正整数相应的二进制数,该数存放于数组Bin[1n]中i1while n!0 doBin[i]n%2;nintn/2;i++;while i!0 doprint Bin[i];i--;9.考虑下面这个算法,它求的是数组中大小相差最小的两个元素的差.算法略对这个算法做尽可能多的改进.算法 MinDistanceA[0..n-1]//输入:数组A[0..n-1]//输出:the smallest distance d between two of its elements 习题1.3考虑这样一个排序算法,该算法对于待排序的数组中的每一个元素,计算比它小的元素个数,然后利用这个信息,将各个元素放到有序数组的相应位置上去.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.古老的七桥问题第2章习题2.17.对下列断言进行证明:如果是错误的,请举例a. 如果tn∈Ogn,则gn∈Ωtnb.α0时,Θαgn Θgn解:a这个断言是正确的。

算法设计与分析(第2版)-王红梅-胡明-习题答案(1)

算法设计与分析(第2版)-王红梅-胡明-习题答案(1)

算法设计与分析(第2版)-王红梅-胡明-习题答案习题11. 图论诞生于七桥问题。

出生于瑞士的伟大数学家欧拉(Leonhard Euler ,1707—1783)提出并解决了该问题。

七桥问题是这样描述的:一个人是否能在一次步行中穿越哥尼斯堡(现在叫加里宁格勒,在波罗的海南岸)城中全部的七座桥后回到起点,且每座桥只经过一次,图 1.7是这条河以及河上的两个岛和七座桥的草图。

请将该问题的数据模型抽象出来,并判断此问题是否有解。

七桥问题属于一笔画问题。

输入:一个起点输出:相同的点1, 一次步行2, 经过七座桥,且每次只经历过一次3, 回到起点该问题无解:能一笔画的图形只有两类:一类是所有的点都是偶点。

另一类是只有二个奇点的图形。

2.在欧几里德提出的欧几里德算法中(即最初的欧几里德算法)用的不是除法而是减法。

请用伪代码描述这个版本的欧几里德算法1.r=m-n2.循环直到r=02.1 m=n图1.7 七桥问题2.2 n=r2.3 r=m-n3 输出m3.设计算法求数组中相差最小的两个元素(称为最接近数)的差。

要求分别给出伪代码和C++描述。

//采用分治法//对数组先进行快速排序//在依次比较相邻的差#include <iostream>using namespace std;int partions(int b[],int low,int high){int prvotkey=b[low];b[0]=b[low];while (low<high){while (low<high&&b[high]>=prvotkey)--high;b[low]=b[high];while (low<high&&b[low]<=prvotkey)++low;b[high]=b[low];}b[low]=b[0];return low;}void qsort(int l[],int low,int high){int prvotloc;if(low<high){prvotloc=partions(l,low,high); //将第一次排序的结果作为枢轴qsort(l,low,prvotloc-1); //递归调用排序由low 到prvotloc-1qsort(l,prvotloc+1,high); //递归调用排序由 prvotloc+1到 high}}void quicksort(int l[],int n){qsort(l,1,n); //第一个作为枢轴,从第一个排到第n个}int main(){int a[11]={0,2,32,43,23,45,36,57,14,27,39};int value=0;//将最小差的值赋值给valuefor (int b=1;b<11;b++)cout<<a[b]<<' ';cout<<endl;quicksort(a,11);for(int i=0;i!=9;++i){if( (a[i+1]-a[i])<=(a[i+2]-a[i+1]) )value=a[i+1]-a[i];elsevalue=a[i+2]-a[i+1];}cout<<value<<endl;return 0;}4.设数组a[n]中的元素均不相等,设计算法找出a[n]中一个既不是最大也不是最小的元素,并说明最坏情况下的比较次数。

算法分析与设计第二版习题答案-第三章到第五章

算法分析与设计第二版习题答案-第三章到第五章

算法设计与分析(第二版)习题答案主编:吕国英算法设计与分析(第二版)习题答案(第三章)第三章: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;}3.#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;intcount=1;for(i=0;i<(N/2)+(N%2);i++){ for(j=a;j<=b;j++) { buf[a][j]=count++; } f or(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("]",buf[i][j]); printf("\n");}return 0;}4.#include<stdio.h>#define N 5int main(int argc,char **argv){int buf[N][N];inti,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("]",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;intcount=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("]",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;linkstack;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,intcount)//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){intm,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;else if(n==0) return ack(m-1,1); else return ack(m-1,ack(m,n-1));}8.#include<stdio.h>char buf[1024];intis_huiwen(int a,int count){if(a==count/2) { return1; }else if(buf[a]==buf[count-a-1]) return (is_huiwen(a-1,count))&&1; else {return 0; }}int main(void){int count;inti;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;else if(b-a==0) return 1; else return pos(a,b-1)+pos(a,b-2);}int main(void){inta,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;inti;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;inti;scanf("%d",&n);for(i=1;i<=n;i++) { temp=i; if(temp==5)count++; elseif(te mp==0) { temp1=i; while((temp1)==0) { temp1=temp1/10; count++; } } }printf("%d",count);return 0;}12.#include<stdio.h>int main(void){int count=0;int buf[53];inti,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)break; }for(i=1;i<53;i ++) { if(buf[i]==1)printf("%d ",i); }printf("\n");return 0;}13.#include<stdio.h>int main(void){inta,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;inttemp;for(i=10;i<=31;i++) { mul=i*i; temp=mul; buf[0]=temp; temp=temp /10; buf[1]=temp; temp=temp/10; buf[2]=temp; if((buf[0]==buf[1])||(buf[0] ==buf[2])||(buf[1]==buf[2])){ printf("%d^2=%d\n",i,mul);} }return0;}15.#include<stdio.h>int main(void){inta,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;intn;scanf("%d",&n);k=(n%4==0)+(n%7==0)*2+(n%9==0)*4;switch(k) { case7: printf("all"); break; case 6: printf("7 and 9"); break; case5: printf("4 and 9"); break; case 4: printf("9"); break; case 3: printf("4 and 7"); break; case 2: printf("7"); break; case1: printf("4"); break; case 0: printf("none"); break; }return0;}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 amoment...\n");d=36*c+28*a+21*b;while(d>84) d=d-84;printf("your numberwas %d\n",d);return 0;}18.#include<stdio.h>int main(void){int buf[10];int i,j;int mul;int temp1,temp2;intbool;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])>1) { bool=1; break; } temp1/=10; } if(bool==1)continue; mul=i*2; temp2=mul; while(temp2>0){ if((++buf[t emp2])>1) { bool=1; break; } temp2/=10;} if(bool==1)continue; pri ntf("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;intsum=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;else exit(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;intbuf[10];for(a=10;a<=99;a++) { for(i=0;i<10;i++)buf[i]=0; if((++buf[a]>1)||(++b uf[a/10]>1))continue; for(b=100;b<=999;b++){ for(i=0;i<10;i++) { if((i!=a)& &i!=a/10) buf[i]=0; } if((++buf[b]>1)||(++buf[b/10]>1)||(++buf[b/100]>1)) conti nue; c=a*b; if(c<10000&&c>999) { if((++buf[c]>1)||(++buf[c/10]>1)||(++buf[c /100]>1)||(++buf[c/1000]>1)) continue; else printf("%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]>1)||(++buf[a/10]>1)||(++buf[a/100]>1))continue; b=a*a; t=b; for(i=0;i<6;i++ ){ if(++buf[t]>1) { bool=1; break; } t=t/10;} if(bool==1)continue; p rintf("%d^2=%d\n",a,b); }return 0;}22.#include<stdio.h>int main(void){intbuf[100];int i;int n;int max;inttemp;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!=1;i++) { temp=buf[i]+buf[(i+1)]+buf[(i+2 )]+buf[(i+3)]; if(temp>max)max=temp; }printf("max=%d\n",max);return0;}23.#include<stdio.h>void nirnava(int n){if(n<10) printf("%d",n);else { nirnava(n/10); printf("%d ",n); }}int main(void){int count=0;int n;int i;int t;scanf("%d",&n);t=n;while(t>0) { printf("%d",t); 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==2)||(temp==3)||(temp==5)||(temp==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==2)||(temp==3)||(temp==5)||(temp==7)){}else{bool=1;break;}temp/=10;}if(bool==0){while(temp1>0){if((temp1==2)||(temp1==3)||(temp1==5)||(temp1==7)){}else{bool=1;break;}temp1/=10;}}if(bool==0)while(temp2>0){if((temp2==2)||(temp2==3)||(temp2==5)||(temp2==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,mul2,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];}}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; if(chess[i][col]=='Q')return 0; }i=row;j=col;while(i!=-1&&j!=-1) { if(chess[i--][j--]=='Q')return 0; }i=row;j=col;while(i!=-1&&j!=8) { if(chess[i--][j++]=='Q')return 0; }i=row;j=col;while(i!=8&&j!=-1) { if(chess[i++][j--]=='Q')return0; }i=row;j=col;while(i!=8&&j!=8) { if(chess[i++][j++]=='Q')return 0; }return 1;}int queen(int row,int col,int n){int i,j;int result=0;if(n==8) return1;else if(is_safe(row,col)) {chess[row][col]='Q';for(i=0;i<8;i++) for(j=0;j<8;j++) { result+=queen(i,j,n+1); if(result>0) break; }if(result>0) return1;else { chess[row][col]='X'; return 0; } } else return0;}6.#include<stdio.h>int main(void){inti,j,k;for(i=1;i<=33;i++) for(j=1;j<=50;j++) {k=100-i-j;if(k%2==0) { if(3*i+2*j+k/2==100) printf("大马%d\n中马%d\n小马%d\n\n\n",i,j,k);}}return 0;}7.#include<stdio.h>int main(void){int i;for(i=1;i<=10000;i++){if(i%2==1&&i%3==2&&i%5==4&&i%6==5&&i%7==0) printf("%d\n",i);}return 0;}8.#include<stdio.h>int main(void){int i;int sum;int a1,a2,a3,a4;for(i=1000;i<=9999;i++){a1=i;a2=i/10;if(a1!=a2){a3=i/100;if(a1!=a3&&a2!=a3){a4=i/1000;if(a1!=a4&&a2!=a4&&a3!=a4){sum=(a1+a2+a3+a4)*(a1+a2+a3+a4);if(i%sum==0)printf("%d\n",i);}}}}return 0;}9.#include<stdio.h>#define N 10void max_min(int *a,int m,int n,int *min1,int *min2,int *max1,int *max2);int main(void){int a[N]={2,3,4,5,34,7,9,6,43,21};int min1,min2;int max1,max2;max_min(a,0,N-1,&min1,&min2,&max1,&max2);printf("min1=%d\nmin2=%d\nmax1=%d\nmax2=%d\n",min1,min2,max1,max2); return 0;}void max_min(int *a,int m,int n,int *min1,int *min2,int *max1,int *max2){int lmin1,lmin2,lmax1,lmax2;int rmin1,rmin2,rmax1,rmax2;int mid;if(m==n){*min1=*min2=*max1=*max2=a[m];}elseif(m==n-1){if(a[m]<a[n]){*min1=a[m];*min2=a[n];*max1=a[n];*max2=a[m];}else{*min1=a[n];*min2=a[m];*max1=a[m];*max2=a[n];}}else{mid=(m+n)/2;max_min(a,m,mid,&lmin1,&lmin2,&lmax1,&lmax2);max_min(a,mid+1,n,&rmin1,&rmin2,&rmax1,&rmax2);if(lmin1<rmin1){if(lmin2<rmin1){*min1=lmin1;*min2=lmin2;}else{*min1=lmin1;*min2=rmin1;}}elseif(rmin2<lmin1) {*min1=rmin1; *min2=rmin2; }else{*min1=rmin1; *min2=lmin1; }if(lmax1>rmax1){if(lmax2>rmax1) {*max1=lmax1;*max2=lmax2;}else{*max1=lmax1;*max2=rmax1;}}elseif(rmax2>lmax1) {*max1=rmax1; *max2=rmax2; }else{*max1=rmax1; *max2=lmax1; }}}10.#include<stdio.h>int add(int *a,int flag,int right);int main(void){int a[10]={1,2,3,4,5,6,7,8,9,10};int sum=add(a,0,9);printf("%d\n",sum);return 0;}int add(int *a,int flag,int right){int mid;if(flag==right){return a[flag];}elseif(flag==right-1){return a[flag]+a[right];}else{mid=(flag+right)/2;return add(a,flag,mid)+add(a,mid+1,right); }}11.#include<stdio.h>int main(void){int a[5][3]={{-50,17,-42},{-47,-19,-3},{36,-34,-43},{-30,-43,34},{-23,-8,-45}};int i,j;int max,n;int sum=0;for(i=0;i<5;i++){max=a[i][0];n=0;for(j=1;j<3;j++){if(a[i][j]>max){max=a[i][j];n=j;}}sum+=max;printf("a[%d][%d]=%d\n",i,n,max);}printf("%d\n",sum);return 0;}12.#include<stdio.h>#include<stdlib.h>#define N 4void matrix_mul(int *mul1,int*mul2,int *mul3,int length);void matrix_add_sub(int * A,int * B,int * C,int m,char ch);void update_half_value(int * A,int * B,int m);void get_half_value(int * A,int * B,int m);int main(void){int i,j;int mul1[N*N]={1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6};intmul2[N*N]={7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2};intmul3[N*N];matrix_mul(mul1,mul2,mul3,N);for(i=0;i<N*N;i++) { printf("]",mul3[ i]); if((i+1)%N==0) printf("\n"); }return 0;}void matrix_add_sub(int * A,int * B,int * C,int m,char ch){ inti; for(i=0;i<m*m;i++) { if(ch=='+') C[i]=A[i]+B[i]; else C[i]= A[i]-B[i]; }}void update_half_value(int * A,int * B,int m){ inti,j; for(i=0;i<m/2;i++) { for(j=0;j<m/2;j++) { B[i*m+j]=A[i*m/2+j]; } }}void get_half_value(int * A,int * B,int m){ inti,j; for(i=0;i<m/2;i++) { for(j=0;j<m/2;j++) { A[i*m/2+j]=B[i*m+j]; } }}void matrix_mul(int *A,int *B,int *C,int m){if(m==2) { intD,E,F,G,H,I,J; D=A[0]*(B[1]-B[3]); E=A[3]*(B[2]-B[0]); F=(A[2]+A[3])*B[0]; G=(A[0]+A[1])*B[3]; H=(A[2]-A[0])*(B[0]+B[1]); I=(A[1]-A[3])*(B[2]+B[3]); J=(A[0]+A[3])*(B[0]+B[3]); C[0]=E+I+J-G; C[1]=D+G; C[2]=E+F; C[3]=D+H+J-F; return ; }else { intA1[m*m/4],A2[m*m/4],A3[m*m/4],A4[m*m/4]; intB1[m*m/4],B2[m*m/4],B3[m*m/4],B4[m*m/4]; intC1[m*m/4],C2[m*m/4],C3[m*m/4],C4[m*m/4]; intD[m*m/4],E[m*m/4],F[m*m/4],G[m*m/4],H[m*m/4],I[m*m/4],J[m*m/4]; int temp1[m*m/4],temp2[m*m/4]; get_half_value(A1,&A[0],m); get_half_value(A2, &A[m/2],m); get_half_value(A3,&A[m*m/2],m); get_half_value(A4,&A[m*m/2 +m/2],m); get_half_value(B1,&B[0],m); get_half_value(B2,&B[m/2],m); get_ half_value(B3,&B[m*m/2],m); get_half_value(B4,&B[m*m/2+m/2],m); matrix_a dd_sub(B2,B4,temp1,m/2,'-'); matrix_mul(A1,temp1,D,m/2); matrix_add_sub(B3,B1,temp1,m/2,'-'); matrix_mul(A4,temp1,E,m/2); matrix_add_sub(A3,A4,temp1,m/2,'+'); matri x_mul(temp1,B1,F,m/2); matrix_add_sub(A1,A2,temp1,m/2,'+'); matrix_mul(temp1,B4,G,m/2); matrix_add_sub(A3,A1,temp1,m/2,'-'); matrix_add_sub(B1,B2,temp2,m/2,'+'); matrix_mul(temp1,temp2,H,m/2); m atrix_add_sub(A2,A4,temp1,m/2,'-'); matrix_add_sub(B3,B4,temp2,m/2,'+'); matrix_mul(temp1,temp2,I,m/2); ma trix_add_sub(A1,A4,temp1,m/2,'+'); matrix_add_sub(B1,B4,temp2,m/2,'+'); matri x_mul(temp1,temp2,J,m/2); matrix_add_sub(E,I,temp1,m/2,'+'); matrix_add_sub(J ,G,temp2,m/2,'-'); matrix_add_sub(temp1,temp2,C1,m/2,'+'); matrix_add_sub(D,G,C2,m/2,'+'); matrix_add_sub(E,F,C3,m/2,'+'); matrix_add_sub(D,H,temp1,m/2,'+'); matrix_add _sub(J,F,temp2,m/2,'-'); matrix_add_sub(temp1,temp2,C4,m/2,'+'); update_half_value(C1,&C[0],m); update_half_value(C2,&C[m/2],m); update_half_value(C3,&C[m*m/2],m); updat e_half_value(C4,&C[m*m/2+m/2],m); return ; }}13.#include<stdio.h>intmain(void){int a[6][7]={ {16,4,3,12,6,0,3}, {4,-5,6,7,0,0,2}, {6,0,-1,-2,3,6,8}, {5,3,4,0,0,-2,7}, {-1,7,4,0,7,-5,6}, {0,-1,3,4,12,4,2}};intb[6][7],c[6][7];int i,j,k;int max;int flag;inttemp;for(i=0;i<6;i++) for(j=0;j<7;j++) {b[i][j]=a[i][j];c[i][j]=-1; }for(i=1;i<5;i++) { for(j=0;j<7;j++){ max=0; for(k=j-2;k<=j+2;k++) { if(k<0) continue; else if(k>6) break; else { if(b[i][j ]+b[i-1][k]>max) { max=b[i][j]+b[i-1][k]; flag=k; } } } b[i][j]=max; c[i][j]=flag;} }for(j=1;j<=5;j++) { max=0; for(k=j-2;k<=j+2;k++){ if(k<0) continue; else if(k>6) break; else { if(b[i][j]+ b[i-1][k]>max) { max=b[i][j]+b[i-1][k]; flag=k; } }} b[i][j]=max; c[i][j]=flag; }max=0;for(j=1;j<=5;j++) { if(b[i][j]>max){ max=b[i][j]; flag=j;} }printf("%d\n",max);temp=c[i][flag];pri ntf("]",a[i][temp]);for(j=i;j>0;j--) { temp=c[j][temp]; printf("]",a[j-1][temp]); }printf("\n");return 0;}14.#include<stdio.h>int main(void){intA[6]={0,3,7,9,12,13};int B[6]={0,5,10,11,11,11};int C[6]={0,4,6,11,12,12};intAB[6][6];int temp[6];int abc[6];int max;int flag;inti,j,k;for(i=0;i<=5;i++) { max=0; for(j=0;j<=i;j++){ AB[i][j]=A[i-j]+B[j]; if(AB[i][j]>max) max=AB[i][j];} temp[i]=max; }max=0;for(i=0;i<=5;i ++) { abc[i]=temp[i]+C[5-i]; if(abc[i]>max){ max=abc[i]; flag=i;} }printf("max=%d\n",max);printf("c=%d \n",5-flag);max=max-C[5-flag];for(i=0;i<=flag;i++) { if(AB[flag][i]==max){ printf("b=%d\n",i); printf("a= %d\n",flag-i); break;} }return 0;}16.#include<stdio.h>#define N 100int search(int*a,int left,int right);int sum_buf(int *a,int left,int right);int main(void){int a[N];int i;int s;for(i=0;i<N;i++) a[i]=1;a[24]=2;s=search(a,0,N-1);printf("%d\n",s);return 0;}int sum_buf(int *a,int left,int right){int i;intsum=0;for(i=left;i<=right;i++) sum+=a[i];return sum;}int search(int *a,int left,int right){int mid=(left+right)/2;if(left==right-1) { if(a[left]<a[right])returnright; elsereturn left; }if(mid*2!=(right+left-1)) { if(sum_buf(a,left,mid-1)>sum_buf(a,mid+1,right)){ return search(a,left,mid-1);} elseif(sum_buf(a,left,mid-1)<sum_buf(a,mid+1,right)) { returnsearch(a,mid+1,right); }else returnmid; }else { if(sum_buf(a,left,mid)>sum_buf(a,mid+1,right))returnsearch(a,left,mid); elsereturn search(a,mid+1,right); }}17.#include<stdio.h>int job[6][2]={{3,8},{12,10},{5,9},{2,6},{9.3},{11,1}};intx[6],bestx[6],f1=0,bestf,f2[7]={0};void try(int i);void swap(int a,int b);intmain(void){inti,j;bestf=32767;for(i=0;i<6;i++) x[i]=i;try(0);for(i=0;i<6;i++) printf("%d",bestx[i]);printf("\nbestf=%d\n",bestf);return 0;}void try(int i){intj;if(i==6) { for(j=0;j<6;j++)bestx[j]=x[j]; bestf=f2[i]; }else { for(j=i;j<6;j ++){ f1=f1+job[x[j]][0]; if(f2[i]>f1) f2[i+1]=f2[i]+job[x[j]][1]; else f2[i+1]=f1 +job[x[j]][1]; if(f2[i+1]<bestf) { swap(i,j); try(i+1); swap(i,j); } f1=f1 -job[x[j]][0];} }}void swap(int i,int j){inttemp;temp=x[i];x[i]=x[j];x[j]=temp;}18.#include<stdio.h>#define N 5 //N个数字#define M 2 //M个加号char buf[N];int a[N];char b[M+1][N];int c[M+1];int try(int t);void swap(int t1,int t2);int add();void output();int min=99999;int main(){int i;for(i=0;i<N;i++){scanf("%c",&buf[i]);}a[0]=0;for(i=1;i<=M;i++){a[i]=1;}for(;i<N;i++){a[i]=0;}try(1);output();printf("%d\n",min);return 0;}int try(int t){int j;int i;int sum;if(t>=N){sum=add();if(sum<min){min=sum;for(i=0;i<M+1;i++) {c[i]=atoi(b[i]);}}}else{for(j=t;j<N;j++) {//if(a[t]!=a[j]){swap(t,j);try(t+1);swap(t,j);}//else//try(t+1);}}}void swap(int t1,int t2) {int t;t=a[t1];a[t1]=a[t2];a[t2]=t;}int add(){int sum=0;int i=0;int j;int k=0;int h=0;for(i=0;i<M+1;i++)for(j=0;j<N;j++)b[i][j]='Q';i=0;j=0;h=0;k=0;for(j=0;j<N;j++){if(a[j]==1){h=0;i++;b[i][h]=buf[j];//printf("%d ",atoi(b[i]));//printf("%d %d %c \n",i,h,b[i][h]);h++;}else{b[i][h]=buf[j];//printf("%d %d %c \n",i,h,b[i][h]);//printf("%d ",atoi(b[i]));h++;}}for(i=0;i<M+1;i++){sum+=atoi(b[i]);}return sum;}void output(){int i;for(i=0;i<M+1;i++){printf("%d",atoi(b[i]));if(i!=M)printf("+");}printf("=");}19.#include<stdio.h>int main(void){int buf[100];int m,n;inti,j;buf[0]=1;buf[1]=1;scanf("%d%d",&n,&m);for(i=1;i<n;i++) { buf[i+1]=buf[i];。

算法分析与设计 第二版 英文版 (潘彦 著) 清华大学出版社 课后答案--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。

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

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

9. Shortest path counting A chess rook can move horizontally or vertically to any square in the same row or in the same column of a chessboard. Find the number of shortest paths by which a rook can move from one corner of a chessboard to the diagonally opposite corner [Gar78], p.10 (a) by a dynamic programming algorithm.
10. a. In the situation where teams A and B need i and j games, respectively, to win the series, consider the result of team A winning the game and the result of team A losing the game. b. Set up a table with five rows (0 ≤ i ≤ 4) and five columns (0 ≤ j ≤ 4) and fill it by using the recurrence derived in part (a). c. A pseudocode should be guided by the recurrence set up in part (a). The efficiency answers follow immediately from the table’s size and the time spent on computing each of its entries.

黄宇《算法设计与分析》课后习题解析(二)精选全文

黄宇《算法设计与分析》课后习题解析(二)精选全文

黄宇《算法设计与分析》课后习题解析(⼆)第2章:从算法的视⾓重新审视数学的概念2.1:(向下取整)题⽬:请计算满⾜下⾯两个条件的实数的区间解析:根据向下取整的含义,令,讨论a的取值范围即可解答:令,则可得:即:故的取值区间为:2.2: (取整函数)题⽬:证明:对于任意整数,(提⽰:将n划分为)。

解析:根据提⽰将n进⾏划分,根据取整函数的定义⽤k表⽰取整函数,即可证明;证明如下:因为对于任意整数,可划分为,则:① ;② ;综上:对于任意整数,, 得证;2.3: (斐波拉契数列)对于斐波拉契数列,请证明:1)题⽬:是偶数当且仅当n能被3整除解析:由斐波拉契数列的递归定义式,容易联想到数学归纳法;证明如下:(采⽤数学归纳法)i)当n = 1,2,3时,依次为1,1,2,符合命题;ii)假设当(k>=1)时命题均成⽴,则:① 当n = 3k+1时,是奇数,成⽴;② 当n = 3k+2时,是奇数,成⽴;③ 当 n = 3(k+1)时,是偶数,成⽴;综上:归纳可得为偶数当且仅当,得证;2)题⽬:x x =1+a (0<a <1)x =1+a (0<a <1)⌊x ⌋=1⇒⌊x ⌋=21⌊x ⌋=2⌊1+a +22a ⌋=1a +22a <1⇒0<a <−21⇒1<a +1<⇒21<x <2x (1,)2n ≥1⌈log (n +1)⌉=⌊logn ⌋+12≤k n ≤2−k +11n ≥12≤k n ≤2−k +11k +1=⌈log (2+k 1)⌉≤⌈log (n +1)⌉≤⌈log (2)⌉=k +1k +1=>⌈log (n +1)⌉=k +1k =⌊log (2)⌋≤k ⌊logn ⌋≤⌊log (2−k +11)⌋=k =>⌊logn ⌋=k n ≥1⌈log (n +1)⌉=k +1=⌊logn ⌋+1F n F n n ≤3k F =n F +n −1F =n −2F +3k F =3k −1>F 3k +1F =n F +3k +1F =3k >F 3k +2F =n F +3k +2F =3k +1>F 3k +3F n 3∣n F −n 2F F =n +1n −1(−1)n +1解析:同1)理,容易联想到数学归纳法证明如下:(采⽤数学归纳法)i)当n = 2时,, 易知成⽴;ii)假设当 n = k 时命题成⽴,① 若k = 2m, 则,当n = k+1 = 2m+1时,要证命题成⽴,即证: => ,代⼊递推式, 得:, 易知是恒等式,故命题成⽴;②当 k=2m+1时,同①理可证命题成⽴;综上:归纳可得,得证;2.4:(完美⼆叉树)给定⼀棵完美⼆叉树,记其节点数为,⾼度为,叶节点数为,内部节点数为1)题⽬:给定上述4个量中的任意⼀个,请推导出其他3个量解析:根据完美⼆叉树的结构特点易得解答:(仅以已知⾼度h推导其他三个量为例,其余同理)已知⾼度为h,可得:节点数:叶节点数:内部节点数:2)题⽬:请计算完美⼆叉树任意⼀层的节点个数:① 如果任意指定深度为的⼀层节点,请计算该层节点个数;② 如果任意指定⾼度为的⼀层节点,请计算该层节点个数;解析:根据完美⼆叉树的结构特点易得(注意节点深度和节点⾼度是互补的,相加为树⾼)解答:① ; ② ;2.5: (⼆叉树的性质)对于⼀棵⾮空的⼆叉树T,记其中叶节点的个数为,有1个⼦节点的节点个数为,有两个⼦节点的节点个数为1)题⽬:如果T是⼀棵2-tree,请证明。

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

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

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

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

step1:a=1;step2:若a*a 5. a.用欧几里德算法求gcd。

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

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欧几里德算法做了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:根据除法的定义不难证明:如果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)7.对于第一个数小于第二个数的一对数字,欧几里得算法将会如何处理?该算法在处理这种输入的过程中,上述情况最多会发生几次? Hint:对于任何形如0 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)//求方程ax^2+bx+c=0的实根的算法 //输入:实系数a,b,c//输出:实根或者无解信息 If a≠0D←b*b-4*a*c If D>0temp←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=0if 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=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. 考虑这样一个排序算法,该算法对于待排序的数组中的每一个元素,计算比它小的元素个数,然后利用这个信息,将各个元素放到有序数组的相应位置上去.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.(古老的七桥问题) 第2章习题7.对下列断言进行证明:(如果是错误的,请举例) a. 如果t(n)∈O(g(n),则g(n)∈Ω(t(n)) b.α>0时,Θ(αg(n))= Θ(g(n)) 解:a. 这个断言是正确的。

它指出如果t(n)的增长率小于或等于g(n)的增长率,那么 g(n)的增长率大于或等于t(n)的增长率t(n)≤c·g(n) for all n≥n0, where c>01 则:()t(n)?g(n) for all n≥n0cb. 这个断言是正确的。

只需证明?(?g(n))??(g(n)),?(g(n))??(?g(n))。

设f(n)∈Θ(αg(n)),则有:f(n)?c?g(n) for all n>=n0, c>0 f(n)?c1g(n) for all n>=n0, c1=cα>0即:f(n)∈Θ(g(n))又设f(n)∈Θ(g(n)),则有:f(n)?cg(n) for all n>=n0,c>0f(n)?c??g(n)?c1?g(n) for all n>=n0,c1=c/α>0 即:f(n)∈Θ(αg(n))8.证明本节定理对于下列符号也成立: a.Ω符号 b.Θ符号证明:a。

we need to proof that if t1(n)∈Ω(g1(n)) andt2(n)∈Ω(g2(n)), then t1(n)+ t2(n)∈Ω(max{g1(n),g2(n)})。

t1(n)∈Ω(g1(n)),t1(n)≥c1g1(n) for all n>=n1, where c1>0 t2(n)∈Ω(g2(n)),T2(n)≥c2g2(n) for all n>=n2, where c2>0 那么,取c>=min{c1,c2},当n>=max{n1,n2}时:t1(n)+ t2(n)≥c1g1(n)+ c2g2(n)≥c g1(n)+c g2(n)≥c[g1(n)+g2(n)] ≥cmax{ g1(n), g2(n)} 所以以命题成立。

b. t1(n)+t2(n) ∈Θ(max(g1(n),g2(n)))证明:大?的定义知,必须确定常数c1、c2和n0,使得对于所有n>=n0,有:c1max((g1(n),g2(n))?t1(n)?t2(n)?max(g1(n),g2(n)) t1(n)∈Θ(g1(n))知,存在非负整数a1,a2和n1使:a1*g1(n) t2(n)∈Θ(g2(n))知,存在非负整数b1,b2和n2使:b1*g2(n) a1*g1(n)+ b1*g2(n) C1*(g1+g2) 显然,g1(n)+g2(n) 又g2(n)>0,g1(n)+g2(n)>g1(n),即g1+g2>max(g1,g2)。

则式转换为:C1*max(g1,g2) =n0时上述不等式成立。

证毕。

习题 2.请用的非正式定义来判断下列断言是真还是假。

a. n(n + 1)/2 ∈ O(n3)b. n(n + 1)/2 ∈ O(n2)c.n(n + 1)/2 ∈Θ(n3) d. n(n + 1)/2 ∈Ω(n) 答:c假,其它真。

5.按照下列函数的增长次数对它们进行排列 (n?2)!,5lg(n+100)10, 22n, +3n3+1, ln2 n,, 3n.答:习题1. 计算下列求和表达式的值。

答:3. 考虑下面的算法。

a.该算法求的是什么? b.它的基本操作是什么?c.该基本操作执行了多少次?d.该算法的效率类型是什么?e.对该算法进行改进,或者设计一个更好的算法,然后指出它们的效率类型。

如果做不到这一点,请试着证明这是不可能做到的。

9.证明下面的公式:可以使用数学归纳法,也可以像10岁的高斯一样,用洞察力来解决该问题。

这个小学生长大以后成为有史以来最伟大的数学家之一。

数学归纳法:高斯的方法:习题1. 解下列递推关系 a.x(n)x(n1)5当n>1时 ??x(1)?0 解:b. 解:x(n)3x(n1)x(1)4当n>1时2. 对于计算n!的递归算法F(n),建立其递归调用次数的递推关系并求解。

解:3. 考虑下列递归算法,该算法用来计算前n个立方的和:S(n)=13+23+…+n3。

算法S(n)//输入:正整数n//输出:前n个立方的和 if n=1 return 1else return S(n-1)+n*n*na. 建立该算法的基本操作次数的递推关系并求解b. 如果将这个算法和直截了当的非递归算法比,你做何评价?解:7. a. 请基于公式2n=2n-1+2n-1,设计一个递归算法。

当n是任意非负整数的时候,该算法能够计算2n的值。

b. 建立该算法所做的加法运算次数的递推关系并求解c. 为该算法构造一棵递归调用树,然后计算它所做的递归调用次数。

d. 对于该问题的求解来说,这是一个好的算法吗?解:a.算法power(n) //基于公式2n=2n-1+2n-1,计算2n //输入:非负整数n //输出: 2n的值If n=0 return 1Else return power(n-1)+ power(n-1)c.C(n)??2i?2n?1?1i?0n8.考虑下面的算法算法 Min1(A[0..n-1])//输入:包含n个实数的数组A[0..n-1] If n=1 return A[0]Else temp←Min1(A[0..n-2])If temp≤A[n-1] return temp Else return A[n-1] a.该算法计算的是什么?b.建立该算法所做的基本操作次数的递推关系并求解解:a.计算的给定数组的最小值C(n1)(n)0?for all n>1n=19.考虑用于解决第8题问题的另一个算法,该算法递归地将数组分成两半.我们将它称为Min2(A[0..n-1])算法 Min(A[r..l]) If l=r return A[l] Else temp1←Min2(A[l..(l+r)/2])Temp2←Min2(A[l..(l+r)/2]+1..r)If temp1≤temp2 returntemp1 Else return temp2 a.建立该算法所做的的操作次数的递推关系并求解 b.算法Min1和Min2哪个更快?有其他更好的算法吗? 解:a. 习题的基本数据类型int和long 的最大值分别是n最小为多少的时候,第n个斐波那契数能够使下面的类型溢出。

相关文档
最新文档