算法设计与分析第二版课后习题解答
算法设计与分析-课后习题集答案
第一章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 =。
算法设计与分析第二版课后习题解答
算法设计与分析第二版课后习题解答算法设计与分析基础课后练习答案习题 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. 这个断言是正确的。
算法设计与分析第二版课后习题解答
算法设计与分析基础课后练习答案习题1.14.设计一个计算的算法,n是任意正整数。
除了赋值和比较运算,该算法只能用到基本的四则运算操作。
算法求//输入:一个正整数n2//输出:。
step1:a=1;step2:若a*a<n 转step3,否则输出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可知计算g cd(31415,14142)欧几里德算法做了11次除法。
连续整数检测算法在14142每次迭代过程中或者做了一次除法,或者两次除法,因此这个算法做除法的次数鉴于1·14142和2·14142之间,所以欧几里德算法比此算法快1·14142/11 ≈1300 与2·14142/11 ≈2600 倍之间。
6.证明等式gc 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版)-王红梅-胡明-习题答案习题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
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
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,请证明。
算法设计与分析(第2版)习题答案
习题11. 图论诞生于七桥问题。
出生于瑞士的伟大数学家欧拉(Leonhard Euler ,1707—1783)提出并解决了该问题。
七桥问题是这样描述的:一个人是否能在一次步行中穿越哥尼斯堡(现在叫加里宁格勒,在波罗的海南岸)城中全部的七座桥后回到起点,且每座桥只经过一次,图 1.7是这条河以及河上的两个岛和七座桥的草图。
请将该问题的数据模型抽象出来,并判断此问题是否有解。
七桥问题属于一笔画问题。
输入:一个起点输出:相同的点1, 一次步行2, 经过七座桥,且每次只经历过一次3, 回到起点该问题无解:能一笔画的图形只有两类:一类是所有的点都是偶点。
另一类是只有二个奇点的图形。
2.在欧几里德提出的欧几里德算法中(即最初的欧几里德算法)用的不是除法而是减法。
请用伪代码描述这个版本的欧几里德算法1.r=m-n2.循环直到r=02.1 m=n2.2 n=r2.3 r=m-n3 输出m3.设计算法求数组中相差最小的两个元素(称为最接近数)的差。
要求分别给出伪代码和C ++描述。
//采用分治法//对数组先进行快速排序//在依次比较相邻的差#include <iostream>using namespace std;int partions(int b[],int low,int high) {图1.7 七桥问题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]中一个既不是最大也不是最小的元素,并说明最坏情况下的比较次数。
算法设计与分析 第2版 吕国英 第三章课后习题答案
3.1//计算2+22+222+...+222 (2)void main(){int i,n,sum=0;print("请输入最后一个因子的位数\n");scanf("%d",&n);for(i=1;i<=n;i++)sum=sum+((int)pow(10,i)-1)/9*2;print("2+22+222+...+222……2=%d\n",sum); }3.2显示{5,7,4,8,9,1}的方阵方式main(){int i,j,t,ori[6]={5,7,4,8,9,1};for(i=0;i<6;i++){for(j=0;j<6;j++){t=(j-i)<0?j-i+6:j-i;printf("%d ",ori[t]);}printf("\n");}}3.3main(){int n;int **up(int **array);scanf("%d",&n);int arr[1][1]={{n*n}};for(j=1;j<n;j++)arr=up(**arr,j);}int **up(int **array,n){int upN=n+1;int[upN][upN] tem;tem[1][1]=array[1][1]-pow(n+1,2);for(i=1;i<=n;i++)tem[1][i]=tem[1][i-1]+1;for(i=1;i<=n;i++)tem[n][i]=tem[n][i-1]+1;for(i=1;i<=n;i++)tem[n][n-i]=tem[n][n+1-i]+1;for(i=1;i<n;i++)tem[1][n-i]=tem[1][n-i+1]+1return **tem;}3.4main(){int i,j,t=0,next=1,n;printf("请输入n\n");scanf("%d",&n);printf("显示效果如下\n");for(i=1;i<=n;i++){for(j=1;j<=n-i+1;j++){if(j==1)t=next;elset=t+i+j-1;if(j==2)next=t-1;printf("%d ",t);}printf("\n");}}//思想:每一行的第二个数为next,下一行的第一个数为next-13.5main(){int n,i,j,k;int arr[100][100]={{0}};//动态定义数组太难,所以在系统直接定义一个100*100的方阵,可以处理部分小问题for(i=0;i<100;i++)for(j=0;j<100;j++)arr[i][j]=0;printf("请输入n\n");scanf("%d",&n);/*if(n%2==0){for(k=0;k<n/2;k++)for(i=k;i<n-k;i++)for(j=k;j<n-k;j++)arr[i][j]=k+1;}else{for(k=0;k<(n+1)/2;k++)for(i=k;i<n-k;i++)for(j=k;j<n-k;j++)arr[i][j]=k+1;}*///可将第一个for循环中的判断条件统一改为k<(n+1)/2 for(k=0;k<(n+1)/2;k++)for(i=k;i<n-k;i++)for(j=k;j<n-k;j++)arr[i][j]=k+1;printf("显示效果如下:\n")for(i=0;i<n;i++){for(j=0;j<n;j++)printf("%2d",arr[i][j]);printf("\n");}}3.7main(){int ack(int m,int n);int m,n,score;printf("请输入ackermann函数的m,n:\n");printf("m:");scanf("%d",&m);printf("n:");scanf("%d",&n);score=ack(m,n);printf("ack(%d,%d)=%d\n",m,n,score);}int ack(int m,int n){if(m==0)return n+1;elseif(n==0)return ack(m-1,1);elsereturn ack(m-1,ack(m,n-1));}3.8main(){char str[40];int i,l,t=1;printf("Please input a string!\n");scanf("%s",str);l=strlen(str);for(i=0;i<l/2;i++)if(str[i]!=str[l-i-1])t=0;if(t)printf("The string is Huiwen!\n");elseprintf("The string is not Huiwen!\n");}3.11main(){int i,n,sum=0;//sum为零的个数int zero(int pro);printf("此程序用于计算1*2*3*…*n所得的数末尾有多少个零。
算法分析与设计第二版习题答案-第三章到第五章
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();
算法设计与分析(第二版)习题答案 主编:吕国英
算法设计与分析(第二版)习题答案(第三章)
第三章:
1.#include<stdlib.h>#include<stdio.h>int main(int argc,char **argv){int n;int i,j,k;int *buf;printf("请输入n的数值:");
;}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-
算法设计与分析(第2版) 王红梅 胡明 习题参考答案
usingnamespacestd;
intmain()
{
longdoubleresult=1;
doublej=1;
for(inti=1;i<=64;++i)
{
j=j*2;
result+=j;
j++;
}
cout<<result<<endl;
return0;
}
习题3
1.假设在文本"ababcabccabccacbab"中查找模式"abccac",写出分别采用BF算法和KMP算法的串匹配过
else
value=a[i+2]-a[i+1];
}
cout<<value<<endl;
return0;
}
4.设数组a[n]中的元素均不相等,设计算法找出a[n]中一个既不是最大也不是最小的元素,并说明最坏情况下的比较次数。要求分别给出伪代码和C++描述。
#include<iostream>
usingnamespacestd;
{
if(n==1)
return4;
elseif(n>1)
return3*T(n-1);
}
(2)
intT(intn)
{
if(n==1)
return1;
elseif(n>1)
return2*T(n/3)+n;
}
5.求下列问题的平凡下界,并指出其下界是否紧密。
(1)求数组中的最大元素;
(2)判断邻接矩阵表示的无向图是不是完全图;
算法设计与分析书后参考答案
参考答案第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)由于顶层设计和底层实现局部化,在设计中出现的差错也是局部的,因而容易查找也容易纠正,在设计中常常要做的增、删、改也都是局部的,因而也都容易进行。
算法设计与分析(第二版) 第8章
大规模b,表示其中任一对象所用的最大位数为cN+b,而 cN+b≤(c+1)n。因此,完成A中的每一步至多需要O(n2)位。 证毕。
5. 另一种NP定义 实际上,存在另一种更直观的复杂类NP的定义。这种 NP类的定义是基于确定性的验证,而不是非确定性的接受。 我们说语言L可被一个算法A验证(verified),如果对于输入串 x∈L,存在另一个串y,满足对于输入z=x+y,算法A输出 “yes”,其中符号“+”表示连接。由于串y可帮助我们证明x 的确在L中,因此称串y为L中成员的证书(certificate)。当一 个串不在L中时,我们不做验证的声明。
由此可得,如果一个合理算法的运行时间是输入项数N 的多项式时间,那么它也是输入位数n的多项式时间。因此, 本章其余部分中,我们用n作为问题的输入规模,将多项式 算法的运行时间理解为输入位数的多项式函数。
8.1.1 复杂类P和复杂类NP 1. 判定问题(decision problem) 为了简化讨论,暂时只讨论判定问题,即输出为“yes”
尤其是给定了输入x后,可以构造用 p(n)步运行算法A的补算 法B,其中n是x的规模,并且如果算法B试图运行多于p(n)步, 就会终止算法A。如果算法A输出“yes”,那么算法B输出 “no”;同样,如果算法A输出“no”,或者算法A至少运行 p(n)步而没有产生任何输出,那么算法B输出“yes”。无论 哪一种情况,补算法B的运行时间均为多项式时间。因此, 如果表示某个判定问题的语言L在P中,那么L的补也在P中。
算法设计与分析(第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]中一个既不是最大也不是最小的元素,并说明最坏情况下的比较次数。
算法设计与分析习题解答(第2版)
第1章算法引论11.1 算法与程序11.2 表达算法的抽象机制11.3 描述算法31.4 算法复杂性分析13小结16习题17第2章递归与分治策略192.1 递归的概念192.2 分治法的基本思想262.3 二分搜索技术272.4 大整数的乘法282.5 Strassen矩阵乘法302.6 棋盘覆盖322.7 合并排序342.8 快速排序372.9 线性时间选择392.10 最接近点对问题432.11 循环赛日程表53小结54习题54第3章动态规划613.1 矩阵连乘问题62目录算法设计与分析(第2版)3.2 动态规划算法的基本要素67 3.3 最长公共子序列713.4 凸多边形最优三角剖分753.5 多边形游戏793.6 图像压缩823.7 电路布线853.8 流水作业调度883.9 0-1背包问题923.10 最优二叉搜索树98小结101习题102第4章贪心算法1074.1 活动安排问题1074.2 贪心算法的基本要素1104.2.1 贪心选择性质1114.2.2 最优子结构性质1114.2.3 贪心算法与动态规划算法的差异1114.3 最优装载1144.4 哈夫曼编码1164.4.1 前缀码1174.4.2 构造哈夫曼编码1174.4.3 哈夫曼算法的正确性1194.5 单源最短路径1214.5.1 算法基本思想1214.5.2 算法的正确性和计算复杂性123 4.6 最小生成树1254.6.1 最小生成树性质1254.6.2 Prim算法1264.6.3 Kruskal算法1284.7 多机调度问题1304.8 贪心算法的理论基础1334.8.1 拟阵1334.8.2 带权拟阵的贪心算法1344.8.3 任务时间表问题137小结141习题141第5章回溯法1465.1 回溯法的算法框架1465.1.1 问题的解空间1465.1.2 回溯法的基本思想1475.1.3 递归回溯1495.1.4 迭代回溯1505.1.5 子集树与排列树1515.2 装载问题1525.3 批处理作业调度1605.4 符号三角形问题1625.5 n后问题1655.6 0\|1背包问题1685.7 最大团问题1715.8 图的m着色问题1745.9 旅行售货员问题1775.10 圆排列问题1795.11 电路板排列问题1815.12 连续邮资问题1855.13 回溯法的效率分析187小结190习题191第6章分支限界法1956.1 分支限界法的基本思想1956.2 单源最短路径问题1986.3 装载问题2026.4 布线问题2116.5 0\|1背包问题2166.6 最大团问题2226.7 旅行售货员问题2256.8 电路板排列问题2296.9 批处理作业调度232小结237习题238第7章概率算法2407.1 随机数2417.2 数值概率算法2447.2.1 用随机投点法计算π值2447.2.2 计算定积分2457.2.3 解非线性方程组2477.3 舍伍德算法2507.3.1 线性时间选择算法2507.3.2 跳跃表2527.4 拉斯维加斯算法2597.4.1 n 后问题2607.4.2 整数因子分解2647.5 蒙特卡罗算法2667.5.1 蒙特卡罗算法的基本思想2667.5.2 主元素问题2687.5.3 素数测试270小结273习题273第8章 NP完全性理论2788.1 计算模型2798.1.1 随机存取机RAM2798.1.2 随机存取存储程序机RASP2878.1.3 RAM模型的变形与简化2918.1.4 图灵机2958.1.5 图灵机模型与RAM模型的关系297 8.1.6 问题变换与计算复杂性归约299 8.2 P类与NP类问题3018.2.1 非确定性图灵机3018.2.2 P类与NP类语言3028.2.3 多项式时间验证3048.3 NP完全问题3058.3.1 多项式时间变换3058.3.2 Cook定理3078.4 一些典型的NP完全问题3108.4.1 合取范式的可满足性问题3118.4.2 3元合取范式的可满足性问题312 8.4.3 团问题3138.4.4 顶点覆盖问题3148.4.5 子集和问题3158.4.6 哈密顿回路问题3178.4.7 旅行售货员问题322小结323习题323第9章近似算法3269.1 近似算法的性能3279.2 顶点覆盖问题的近似算法3289.3 旅行售货员问题近似算法3299.3.1 具有三角不等式性质的旅行售货员问题330 9.3.2 一般的旅行售货员问题3319.4 集合覆盖问题的近似算法3339.5 子集和问题的近似算法3369.5.1 子集和问题的指数时间算法3369.5.2 子集和问题的完全多项式时间近似格式337 小结340习题340第10章算法优化策略34510.1 算法设计策略的比较与选择34510.1.1 最大子段和问题的简单算法34510.1.2 最大子段和问题的分治算法34610.1.3 最大子段和问题的动态规划算法34810.1.4 最大子段和问题与动态规划算法的推广349 10.2 动态规划加速原理35210.2.1 货物储运问题35210.2.2 算法及其优化35310.3 问题的算法特征35710.3.1 贪心策略35710.3.2 对贪心策略的改进35710.3.3 算法三部曲35910.3.4 算法实现36010.3.5 算法复杂性36610.4 优化数据结构36610.4.1 带权区间最短路问题36610.4.2 算法设计思想36710.4.3 算法实现方案36910.4.4 并查集37310.4.5 可并优先队列37610.5 优化搜索策略380小结388习题388第11章在线算法设计39111.1 在线算法设计的基本概念39111.2 页调度问题39311.3 势函数分析39511.4 k 服务问题39711.4.1 竞争比的下界39711.4.2 平衡算法39911.4.3 对称移动算法39911.5 Steiner树问题40311.6 在线任务调度40511.7 负载平衡406小结407习题407词汇索引409参考文献415习题1-1 实参交换1习题1-2 方法头签名1习题1-3 数组排序判定1习题1-4 函数的渐近表达式2习题1-5 O(1) 和 O(2) 的区别2习题1-7 按渐近阶排列表达式2习题1-8 算法效率2习题1-9 硬件效率3习题1-10 函数渐近阶3习题1-11 n !的阶4习题1-12 平均情况下的计算时间复杂性4算法实现题1-1 统计数字问题4算法实现题1-2 字典序问题5算法实现题1-3 最多约数问题6算法实现题1-4 金币阵列问题8算法实现题1-5 最大间隙问题11第2章递归与分治策略14 习题2-1 Hanoi 塔问题的非递归算法14习题2-2 7个二分搜索算法15习题2-3 改写二分搜索算法18习题2-4 大整数乘法的 O(nm log(3/2))算法19习题2-5 5次 n /3位整数的乘法19习题2-6 矩阵乘法21习题2-7 多项式乘积21习题2-8 不动点问题的 O( log n) 时间算法22习题2-9 主元素问题的线性时间算法22习题2-10 无序集主元素问题的线性时间算法22习题2-11 O (1)空间子数组换位算法23习题2-12 O (1)空间合并算法25习题2-13 n 段合并排序算法32习题2-14 自然合并排序算法32习题2-15 最大值和最小值问题的最优算法35习题2-16 最大值和次大值问题的最优算法35习题2-17 整数集合排序35习题2-18 第 k 小元素问题的计算时间下界36习题2-19 非增序快速排序算法37习题2-20 随机化算法37习题2-21 随机化快速排序算法38习题2-22 随机排列算法38习题2-23 算法qSort中的尾递归38习题2-24 用栈模拟递归38习题2-25 算法select中的元素划分39习题2-26 O(n log n) 时间快速排序算法40习题2-27 最接近中位数的 k 个数40习题2-28 X和Y 的中位数40习题2-29 网络开关设计41习题2-32 带权中位数问题42习题2-34 构造Gray码的分治算法43习题2-35 网球循环赛日程表44目录算法设计与分析习题解答(第2版)算法实现题2-1 输油管道问题(习题2-30) 49算法实现题2-2 众数问题(习题2-31) 50算法实现题2-3 邮局选址问题(习题2-32) 51算法实现题2-4 马的Hamilton周游路线问题(习题2-33) 51算法实现题2-5 半数集问题60算法实现题2-6 半数单集问题62算法实现题2-7 士兵站队问题63算法实现题2-8 有重复元素的排列问题63算法实现题2-9 排列的字典序问题65算法实现题2-10 集合划分问题(一)67算法实现题2-11 集合划分问题(二)68算法实现题2-12 双色Hanoi塔问题69算法实现题2-13 标准二维表问题71算法实现题2-14 整数因子分解问题72算法实现题2-15 有向直线2中值问题72第3章动态规划76习题3-1 最长单调递增子序列76习题3-2 最长单调递增子序列的 O(n log n) 算法77习题3-7 漂亮打印78习题3-11 整数线性规划问题79习题3-12 二维背包问题80习题3-14 Ackermann函数81习题3-17 最短行驶路线83习题3-19 最优旅行路线83算法实现题3-1 独立任务最优调度问题(习题3-3) 83算法实现题3-2 最少硬币问题(习题3-4) 85算法实现题3-3 序关系计数问题(习题3-5) 86算法实现题3-4 多重幂计数问题(习题3-6) 87算法实现题3-5 编辑距离问题(习题3-8) 87算法实现题3-6 石子合并问题(习题3-9) 89算法实现题3-7 数字三角形问题(习题3-10) 91算法实现题3-8 乘法表问题(习题3-13) 92算法实现题3-9 租用游艇问题(习题3-15) 93算法实现题3-10 汽车加油行驶问题(习题3-16) 95算法实现题3-11 圈乘运算问题(习题3-18) 96算法实现题3-12 最少费用购物(习题3-20) 102算法实现题3-13 最大长方体问题(习题3-21) 104算法实现题3-14 正则表达式匹配问题(习题3-22) 105算法实现题3-15 双调旅行售货员问题(习题3-23) 110算法实现题3-16 最大 k 乘积问题(习题5-24) 111算法实现题3-17 最小 m 段和问题113算法实现题3-18 红黑树的红色内结点问题115第4章贪心算法123 习题4-2 活动安排问题的贪心选择123习题4-3 背包问题的贪心选择性质123习题4-4 特殊的0-1背包问题124习题4-10 程序最优存储问题124习题4-13 最优装载问题的贪心算法125习题4-18 Fibonacci序列的Huffman编码125习题4-19 最优前缀码的编码序列125习题4-21 任务集独立性问题126习题4-22 矩阵拟阵126习题4-23 最小权最大独立子集拟阵126习题4-27 整数边权Prim算法126习题4-28 最大权最小生成树127习题4-29 最短路径的负边权127习题4-30 整数边权Dijkstra算法127算法实现题4-1 会场安排问题(习题4-1) 128算法实现题4-2 最优合并问题(习题4-5) 129算法实现题4-3 磁带最优存储问题(习题4-6) 130算法实现题4-4 磁盘文件最优存储问题(习题4-7) 131算法实现题4-5 程序存储问题(习题4-8) 132算法实现题4-6 最优服务次序问题(习题4-11) 133算法实现题4-7 多处最优服务次序问题(习题4-12) 134算法实现题4-8 d 森林问题(习题4-14) 135算法实现题4-9 汽车加油问题(习题4-16) 137算法实现题4-10 区间覆盖问题(习题4-17) 138算法实现题4-11 硬币找钱问题(习题4-24) 138算法实现题4-12 删数问题(习题4-25) 139算法实现题4-13 数列极差问题(习题4-26) 140算法实现题4-14 嵌套箱问题(习题4-31) 140算法实现题4-15 套汇问题(习题4-32) 142算法实现题4-16 信号增强装置问题(习题5-17) 143算法实现题4-17 磁带最大利用率问题(习题4-9) 144算法实现题4-18 非单位时间任务安排问题(习题4-15) 145算法实现题4-19 多元Huffman编码问题(习题4-20) 147算法实现题4-20 多元Huffman编码变形149算法实现题4-21 区间相交问题151算法实现题4-22 任务时间表问题151第5章回溯法153习题5\|1 装载问题改进回溯法(一)153习题5\|2 装载问题改进回溯法(二)154习题5\|4 0-1背包问题的最优解155习题5\|5 最大团问题的迭代回溯法156习题5\|7 旅行售货员问题的费用上界157习题5\|8 旅行售货员问题的上界函数158算法实现题5-1 子集和问题(习题5-3) 159算法实现题5-2 最小长度电路板排列问题(习题5-9) 160算法实现题5-3 最小重量机器设计问题(习题5-10) 163算法实现题5-4 运动员最佳匹配问题(习题5-11) 164算法实现题5-5 无分隔符字典问题(习题5-12) 165算法实现题5-6 无和集问题(习题5-13) 167算法实现题5-7 n 色方柱问题(习题5-14) 168算法实现题5-8 整数变换问题(习题5-15) 173算法实现题5-9 拉丁矩阵问题(习题5-16) 175算法实现题5-10 排列宝石问题(习题5-16) 176算法实现题5-11 重复拉丁矩阵问题(习题5-16) 179算法实现题5-12 罗密欧与朱丽叶的迷宫问题181算法实现题5-13 工作分配问题(习题5-18) 183算法实现题5-14 独立钻石跳棋问题(习题5-19) 184算法实现题5-15 智力拼图问题(习题5-20) 191算法实现题5-16 布线问题(习题5-21) 198算法实现题5-17 最佳调度问题(习题5-22) 200算法实现题5-18 无优先级运算问题(习题5-23) 201算法实现题5-19 世界名画陈列馆问题(习题5-25) 203算法实现题5-20 世界名画陈列馆问题(不重复监视)(习题5-26) 207 算法实现题5-21 部落卫队问题(习题5-6) 209算法实现题5-22 虫蚀算式问题211算法实现题5-23 完备环序列问题214算法实现题5-24 离散01串问题217算法实现题5-25 喷漆机器人问题218算法实现题5-26 n 2-1谜问题221第6章分支限界法229习题6-1 0-1背包问题的栈式分支限界法229习题6-2 用最大堆存储活结点的优先队列式分支限界法231习题6-3 团顶点数的上界234习题6-4 团顶点数改进的上界235习题6-5 修改解旅行售货员问题的分支限界法235习题6-6 解旅行售货员问题的分支限界法中保存已产生的排列树237 习题6-7 电路板排列问题的队列式分支限界法239算法实现题6-1 最小长度电路板排列问题一(习题6-8) 241算法实现题6-2 最小长度电路板排列问题二(习题6-9) 244算法实现题6-3 最小权顶点覆盖问题(习题6-10) 247算法实现题6-4 无向图的最大割问题(习题6-11) 250算法实现题6-5 最小重量机器设计问题(习题6-12) 253算法实现题6-6 运动员最佳匹配问题(习题6-13) 256算法实现题6-7 n 后问题(习题6-15) 259算法实现题6-8 圆排列问题(习题6-16) 260算法实现题6-9 布线问题(习题6-17) 263算法实现题6-10 最佳调度问题(习题6-18) 265算法实现题6-11 无优先级运算问题(习题6-19) 268算法实现题6-12 世界名画陈列馆问题(习题6-21) 271算法实现题6-13 骑士征途问题274算法实现题6-14 推箱子问题275算法实现题6-15 图形变换问题281算法实现题6-16 行列变换问题284算法实现题6-17 重排 n 2宫问题285算法实现题6-18 最长距离问题290第7章概率算法296习题7-1 模拟正态分布随机变量296习题7-2 随机抽样算法297习题7-3 随机产生 m 个整数297习题7-4 集合大小的概率算法298习题7-5 生日问题299习题7-6 易验证问题的拉斯维加斯算法300习题7-7 用数组模拟有序链表300习题7-8 O(n 3/2)舍伍德型排序算法300习题7-9 n 后问题解的存在性301习题7-11 整数因子分解算法302习题7-12 非蒙特卡罗算法的例子302习题7-13 重复3次的蒙特卡罗算法303习题7-14 集合随机元素算法304习题7-15 由蒙特卡罗算法构造拉斯维加斯算法305习题7-16 产生素数算法306习题7-18 矩阵方程问题306算法实现题7-1 模平方根问题(习题7-10) 307算法实现题7-2 集合相等问题(习题7-17) 309算法实现题7-3 逆矩阵问题(习题7-19) 309算法实现题7-4 多项式乘积问题(习题7-20) 310算法实现题7-5 皇后控制问题311算法实现题7-6 3-SAT问题314算法实现题7-7 战车问题315算法实现题7-8 圆排列问题317算法实现题7-9 骑士控制问题319算法实现题7-10 骑士对攻问题320第8章NP完全性理论322 习题8-1 RAM和RASP程序322习题8-2 RAM和RASP程序的复杂性322习题8-3 计算 n n 的RAM程序322习题8-4 没有MULT和DIV指令的RAM程序324习题8-5 MULT和DIV指令的计算能力324习题8-6 RAM和RASP的空间复杂性325习题8-7 行列式的直线式程序325习题8-8 求和的3带图灵机325习题8-9 模拟RAM指令325习题8-10 计算2 2 n 的RAM程序325习题8-11 计算 g(m,n)的程序 326习题8-12 图灵机模拟RAM的时间上界326习题8-13 图的同构问题326习题8-14 哈密顿回路327习题8-15 P类语言的封闭性327习题8-16 NP类语言的封闭性328习题8-17 语言的2 O (n k) 时间判定算法328习题8-18 P CO -NP329习题8-19 NP≠CO -NP329习题8-20 重言布尔表达式329习题8-21 关系∝ p的传递性329习题8-22 L ∝ p 330习题8-23 语言的完全性330习题8-24 的CO-NP完全性330习题8-25 判定重言式的CO-NP完全性331习题8-26 析取范式的可满足性331习题8-27 2-SAT问题的线性时间算法331习题8-28 整数规划问题332习题8-29 划分问题333习题8-30 最长简单回路问题334第9章近似算法336习题9-1 平面图着色问题的绝对近似算法336习题9-2 最优程序存储问题336习题9-4 树的最优顶点覆盖337习题9-5 顶点覆盖算法的性能比339习题9-6 团的常数性能比近似算法339习题9-9 售货员问题的常数性能比近似算法340习题9-10 瓶颈旅行售货员问题340习题9-11 最优旅行售货员回路不自相交342习题9-14 集合覆盖问题的实例342习题9-16 多机调度问题的近似算法343习题9-17 LPT算法的最坏情况实例345习题9-18 多机调度问题的多项式时间近似算法345算法实现题9-1 旅行售货员问题的近似算法(习题9-9) 346 算法实现题9-2 可满足问题的近似算法(习题9-20) 348算法实现题9-3 最大可满足问题的近似算法(习题9-21) 349 算法实现题9-4 子集和问题的近似算法(习题9-15) 351算法实现题9-5 子集和问题的完全多项式时间近似算法352算法实现题9-6 实现算法greedySetCover(习题9-13) 352算法实现题9-7 装箱问题的近似算法First Fit(习题9-19) 356算法实现题9-8 装箱问题的近似算法Best Fit(习题9-19) 358算法实现题9-9 装箱问题的近似算法First Fit Decreasing(习题9-19) 360算法实现题9-10 装箱问题的近似算法Best Fit Decreasing(习题9-19) 361算法实现题9-11 装箱问题的近似算法Next Fit361第10章算法优化策略365 习题10-1 算法obst的正确性365习题10-2 矩阵连乘问题的 O(n 2) 时间算法365习题10-6 货物储运问题的费用371习题10-7 Garsia算法371算法实现题10-1 货物储运问题(习题10-3) 374算法实现题10-2 石子合并问题(习题10-4) 374算法实现题10-3 最大运输费用货物储运问题(习题10-5) 375算法实现题10-4 五边形问题377算法实现题10-5 区间图最短路问题(习题10-8) 381算法实现题10-6 圆弧区间最短路问题(习题10-9) 381算法实现题10-7 双机调度问题(习题10-10) 382算法实现题10-8 离线最小值问题(习题10-11) 390算法实现题10-9 最近公共祖先问题(习题10-12) 393算法实现题10-10 达尔文芯片问题395算法实现题10-11 多柱Hanoi塔问题397算法实现题10-12 线性时间Huffman算法400算法实现题10-13 单机调度问题402算法实现题10-14 最大费用单机调度问题405算法实现题10-15 飞机加油问题408第11章在线算法设计410习题11-1 在线算法LFU的竞争性410习题11-4 多读写头磁盘问题的在线算法410习题11-6 带权页调度问题410算法实现题11-1 最优页调度问题(习题11-2) 411算法实现题11-2 在线LRU页调度(习题11-3) 414算法实现题11-3 k 服务问题(习题11-5) 416参考文献422。
算法分析与设计 第二版 英文版 (潘彦 著) 清华大学出版社 课后答案--solu7
1
8. a. Write a program for multiplying two sparse matrices, a p-by-q matrix A and a q-by-r matrix B.
b. Write a program for multiplying two sparse polynomials p(x) and q(x) of degrees m and n, respectively.
tree’s vertices in constant time.
7. The following technique, known as virtual initialization, provides a
网 time-efficient way to initialize just some elements of a given array A[0..n −Fra 网 案 答 后 课2
Hints to Exercises 7.1
1. Yes, it is possible. How? 2. Check the algorithm’s pseudocode to see what it does upon encountering
算法分析与设计 第二版 英文版 (潘彦 著) 清华大学出版社 课后答案--solu5
Exercises 5.1
1. Ferrying soldiers A detachment of n soldiers must cross a wide and deep river with no bridge in sight. They notice two 12-year-old boys playing in a rowboat by the shore. The boat is so tiny, however, that it can only hold two boys or one soldier. How can the soldiers get across the river and leave the boys in joint possession of the boat? How many times need the boat pass from shore to shore?
w.
co
n2 . 4
m
Hints to Exercises 5.1
1. Solve the problem for n = 1. 2. You may consider pouring soda from a filled glass into an empty glass as one move. 3. Use the fact that all the subsets of an n-element set S = {a1 , ..., an } can be divided into two groups: those that contain an and those that do not.
课
后
b. Recall that, generally speaking, sorting algorithms that can exchange elements far apart are not stable.
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
算法设计与分析基础课后练习答案习题1.14.设计一个计算的算法,n是任意正整数。
除了赋值和比较运算,该算法只能用到基本的四则运算操作。
算法求//输入:一个正整数n 2//输出:。
tep1:a=1;step2:若a*a<n 转step 3,否则输出a;step3:a=a+1转step 2;5. a.用欧几里德算法求gcd(31415,14142)。
. 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..有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:根据除法的定义不难证明:●如果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<=m<n的一对数字,Euclid算法在第一次叠代时交换m和n, 即gcd(m,n)=gcd(n,m)并且这种交换处理只发生一次.8.a.对于所有1≤m,n≤10的输入, Euclid算法最少要做几次除法?(1次)b. 对于所有1≤m,n≤10的输入, Euclid算法最多要做几次除法?(5次)gcd(5,8)习题1.21.(农夫过河)P—农夫W—狼G—山羊C—白菜2.(过桥问题)1,2,5,10---分别代表4个人, f—手电筒4. 对于任意实系数a,b,c, 某个算法能求方程ax^2+bx+c=0的实根,写出上述算法的伪代码(可以假设sqrt(x)是求平方根的函数)算法Quadratic(a,b,c)//求方程ax^2+bx+c=0的实根的算法//输入:实系数a,b,c//输出:实根或者无解信息f a≠0D←b*b-4*a*cIf D>0temp←2*ax1←(-b+sqrt(D))/tempx2←(-b-sqrt(D))/tempreturn x1,x2else if D=0 return –b/(2*a)else return “no real roots”lse //a=0if b≠0 return –c/belse //a=b=0if c=0 return “no real numbers”else return “no real roots”5.描述将十进制整数表达为二进制整数的标准算法a.用文字描述b.用伪代码描述解答:a.将十进制整数转换为二进制整数的算法输入:一个正整数n输出:正整数n相应的二进制数第一步:用n除以2,余数赋给Ki(i=0,1,2...),商赋给n第二步:如果n=0,则到第三步,否则重复第一步第三步:将Ki按照i从高到低的顺序输出b.伪代码算法DectoBin(n)//将十进制整数n转换为二进制整数的算法//输入:正整数n//输出:该正整数相应的二进制数,该数存放于数组Bin[1...n]中i=1while n!=0 do {in[i]=n%2;=(int)n/2;++;}while i!=0 do{rint Bin[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.(古老的七桥问题)第2章 习题2.17.对下列断言进行证明:(如果是错误的,请举例) 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>0则:)()()1(n g n t c≤ for all n ≥n0b. 这个断言是正确的。
只需证明))(())(()),(())((n g n g n g n g ααΘ⊆ΘΘ⊆Θ。
设f(n)∈Θ(αg(n)),则有:)()(n g c n f α≤ for all n>=n0, c>0 )()(1n g c n f ≤ for all n>=n0, c1=c α>0即:f(n)∈Θ(g(n))又设f(n)∈Θ(g(n)),则有:)()(n cg n f ≤ for all n>=n0,c>0)()()(1n g c n g cn f ααα=≤for all n>=n0,c1=c/α>0即:f(n)∈Θ(αg(n))8.证明本节定理对于下列符号也成立: a.Ω符号 b.Θ符号 证明:a 。
we need to proof that if t 1(n)∈Ω(g 1(n)) and t 2(n)∈Ω(g 2(n)), then t 1(n)+ t 2(n)∈Ω(max{g 1(n), g 2(n)})。
由 t 1(n)∈Ω(g 1(n)),t 1(n)≥c 1g 1(n) for all n>=n1, where c1>0 由 t 2(n)∈Ω(g 2(n)),T 2(n)≥c 2g 2(n) for all n>=n2, where c2>0 那么,取c>=min{c1,c2},当n>=max{n1,n2}时: t 1(n)+ t 2(n)≥c 1g 1(n)+ c 2g 2(n) ≥c g 1(n)+c g 2(n)≥c[g 1(n)+ g 2(n)] ≥cmax{ g 1(n), g 2(n)} 所以以命题成立。
b. t 1(n)+t 2(n) ∈Θ()))(2),(1max(n g n g证明:由大Ⓗ的定义知,必须确定常数c1、c2和n0,使得对于所有n>=n0,有:))(2),(1max()(2)(1))(2),(1max((1n g n g n t n t n g n g c ≤+≤由t 1(n)∈Θ(g1(n))知,存在非负整数a1,a2和n1使: a1*g1(n)<=t 1(n)<=a2*g1(n)-----(1)由t 2(n)∈Θ(g2(n))知,存在非负整数b1,b2和n2使: b1*g2(n)<=t 2(n)<=b2*g2(n)-----(2) (1)+(2):a1*g1(n)+ b1*g2(n)<=t1(n)+t2(n) <= a2*g1(n)+ b2*g2(n) 令c1=min(a1,b1),c2=max(a2,b2),则C1*(g1+g2)<= t 1(n)+t 2(n) <=c2(g1+g2)-----(3) 不失一般性假设max(g1(n),g2(n))=g1(n).显然,g1(n)+g2(n)<2g1(n),即g1+g2<2max(g1,g2)又g2(n)>0,g1(n)+g2(n)>g1(n),即g1+g2>max(g1,g2)。
则(3)式转换为:C1*max(g1,g2) <= t1(n)+t2(n) <=c2*2max(g1,g2)所以当c1=min(a1,b1),c2=2c2=2max(c1,c2),n0=max(n1,n2)时,当n>=n0时上述不等式成立。
证毕。
习题2.22.请用的非正式定义来判断下列断言是真还是假。
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, 0.001n4+3n3+1, ln2 n,,3n.答:习题2.31.计算下列求和表达式的值。
答:3.考虑下面的算法。
a.该算法求的是什么?b.它的基本操作是什么?c.该基本操作执行了多少次?d.该算法的效率类型是什么?e.对该算法进行改进,或者设计一个更好的算法,然后指出它们的效率类型。
如果做不到这一点,请试着证明这是不可能做到的。
9.证明下面的公式:可以使用数学归纳法,也可以像10岁的高斯一样,用洞察力来解决该问题。
这个小学生长大以后成为有史以来最伟大的数学家之一。
数学归纳法:高斯的方法:习题2.41.解下列递推关系(做a,b)a.:. :⎩⎨⎧=+-=)1(5)1()(xnxnx⎩⎨⎧=-=4)1()1(3)(xnxnx当n>1时当n>1时2.对于计算n!的递归算法F(n),建立其递归调用次数的递推关系并求解。
解:3.考虑下列递归算法,该算法用来计算前n个立方的和:S(n)=13+23+…+n3。