算法导论第二章第一节答案

合集下载

高中数学第二章算法初步1算法的基本思想课时作业含解析北师大版必

高中数学第二章算法初步1算法的基本思想课时作业含解析北师大版必

学习资料第二章算法初步1算法的基本思想[课时作业][A组基础巩固]1.能设计算法求解下列各式中S的值的是()①S=错误!+错误!+错误!+…+错误!;②S=错误!+错误!+错误!+…+错误!+…;③S=错误!+错误!+错误!+…+错误!(n为确定的正整数).A.①②B.①③C.②③D.①②③解析:因为算法的步骤是有限的,所以②不能设计算法求解,易知①③能设计算法求解.答案:B2.关于一元二次方程x2-5x+6=0的求根问题,下列说法正确的是()A.只能设计一种算法B.可以设计两种算法C.不能设计算法D.不能根据解题过程设计算法答案:B3.对于一般的二元一次方程组错误!在写解此方程组的算法时,需要注意的是()A.a1≠0 B.a2≠0C.a1b2-a2b1≠0 D.a1b1-a2b2≠0答案:C4.下面给出的是一个已打乱的“找出a,b,c,d四个数中最大值”的算法:①max=a,②输出max,③如果max<d,则max=d,④如果b〉max,则max=b,⑤输入a,b,c,d四个数,⑥如果c>max,则max=c。

正确的步骤序号为()A.⑤①④⑥③②B.⑤②④③⑥①C.⑤⑥③④①②D.⑤①④⑥②③答案:A5.已知直角三角形的两条直角边长分别为a,b.写出求斜边长c的算法如下:第一步,输入两直角边长a,b的值.第二步,计算c=错误!的值.第三步,________________.将算法补充完整,横线处应填____________________.答案:输出斜边长c的值6.已知一个学生的语文成绩为89,数学成绩为96,外语成绩为99,求他的总分和平均成绩的一个算法为:第一步,取A=89,B=96,C=99;第二步,_______________________________________________________;第三步,________________________________________________________;第四步,输出计算的结果.解析:应先计算总分D=A+B+C,然后再计算平均成绩E=错误!.答案:计算总分D=A+B+C计算平均成绩E=错误!7.求1×3×5×7×9×11的值的一个算法如下,请将其补充完整.1.求1×3得结果;2.将第1步所得结果3乘5,得到结果15.3.________________.4.再将第3步所得结果105乘9,得945.5.再将第4步所得结果945乘11,得到10 395,即为最后结果.解析:由于第2步是计算3×5,故第3步应是计算第3次乘法15×7。

算法导论第三版第二章第一节习题答案

算法导论第三版第二章第一节习题答案

算法导论第三版第⼆章第⼀节习题答案2.1-1:以图2-2为模型,说明INSERTION-SORT在数组A=<31,41,59,26,41,58>上的执⾏过程。

NewImage2.1-2:重写过程INSERTION-SORT,使之按⾮升序(⽽不是按⾮降序)排序。

注意,跟之前升序的写法只有⼀个地⽅不⼀样:NewImage2.1-3:考虑下⾯的查找问题:输⼊:⼀列数A=<a1,a2,…,an >和⼀个值v输出:下标i,使得v=A[i],或者当v不在A中出现时为NIL。

写出针对这个问题的现⾏查找的伪代码,它顺序地扫描整个序列以查找v。

利⽤循环不变式证明算法的正确性。

确保所给出的循环不变式满⾜三个必要的性质。

(2.1-3 Consider the searching problem:Input: A sequence of n numbers A D ha1; a2; : : : ;ani and a value _.Output: An index i such that _ D AOEi_ or the special value NIL if _ does not appear in A.Write pseudocode for linear search, which scans through the sequence, looking for _. Using a loop invariant, prove that your algorithm is correct. Make sure that your loop invariant fulfills the three necessary properties.)LINEAR-SEARCH(A,v)1 for i=1 to A.length2 if v = A[i]3 return i4 return NIL现⾏查找算法正确性的证明。

算法导论课程作业答案

算法导论课程作业答案

算法导论课程作业答案Introduction to AlgorithmsMassachusetts Institute of Technology 6.046J/18.410J Singapore-MIT Alliance SMA5503 Professors Erik Demaine,Lee Wee Sun,and Charles E.Leiserson Handout10Diagnostic Test SolutionsProblem1Consider the following pseudocode:R OUTINE(n)1if n=12then return13else return n+R OUTINE(n?1)(a)Give a one-sentence description of what R OUTINE(n)does.(Remember,don’t guess.) Solution:The routine gives the sum from1to n.(b)Give a precondition for the routine to work correctly.Solution:The value n must be greater than0;otherwise,the routine loops forever.(c)Give a one-sentence description of a faster implementation of the same routine. Solution:Return the value n(n+1)/2.Problem2Give a short(1–2-sentence)description of each of the following data structures:(a)FIFO queueSolution:A dynamic set where the element removed is always the one that has been in the set for the longest time.(b)Priority queueSolution:A dynamic set where each element has anassociated priority value.The element removed is the element with the highest(or lowest)priority.(c)Hash tableSolution:A dynamic set where the location of an element is computed using a function of the ele ment’s key.Problem3UsingΘ-notation,describe the worst-case running time of the best algorithm that you know for each of the following:(a)Finding an element in a sorted array.Solution:Θ(log n)(b)Finding an element in a sorted linked-list.Solution:Θ(n)(c)Inserting an element in a sorted array,once the position is found.Solution:Θ(n)(d)Inserting an element in a sorted linked-list,once the position is found.Solution:Θ(1)Problem4Describe an algorithm that locates the?rst occurrence of the largest element in a?nite list of integers,where the integers are not necessarily distinct.What is the worst-case running time of your algorithm?Solution:Idea is as follows:go through list,keeping track of the largest element found so far and its index.Update whenever necessary.Running time isΘ(n).Problem5How does the height h of a balanced binary search tree relate to the number of nodes n in the tree? Solution:h=O(lg n) Problem 6Does an undirected graph with 5vertices,each of degree 3,exist?If so,draw such a graph.If not,explain why no such graph exists.Solution:No such graph exists by the Handshaking Lemma.Every edge adds 2to the sum of the degrees.Consequently,the sum of the degrees must be even.Problem 7It is known that if a solution to Problem A exists,then a solution to Problem B exists also.(a)Professor Goldbach has just produced a 1,000-page proof that Problem A is unsolvable.If his proof turns out to be valid,can we conclude that Problem B is also unsolvable?Answer yes or no (or don’t know).Solution:No(b)Professor Wiles has just produced a 10,000-page proof that Problem B is unsolvable.If the proof turns out to be valid,can we conclude that problem A is unsolvable as well?Answer yes or no (or don’t know).Solution:YesProblem 8Consider the following statement:If 5points are placed anywhere on or inside a unit square,then there must exist two that are no more than √2/2units apart.Here are two attempts to prove this statement.Proof (a):Place 4of the points on the vertices of the square;that way they are maximally sepa-rated from one another.The 5th point must then lie within √2/2units of one of the other points,since the furthest from the corners it can be is the center,which is exactly √2/2units fromeach of the four corners.Proof (b):Partition the square into 4squares,each with a side of 1/2unit.If any two points areon or inside one of these smaller squares,the distance between these two points will be at most √2/2units.Since there are 5points and only 4squares,at least two points must fall on or inside one of the smaller squares,giving a set of points that are no more than √2/2apart.Which of the proofs are correct:(a),(b),both,or neither (or don’t know)?Solution:(b)onlyProblem9Give an inductive proof of the following statement:For every natural number n>3,we have n!>2n.Solution:Base case:True for n=4.Inductive step:Assume n!>2n.Then,multiplying both sides by(n+1),we get(n+1)n!> (n+1)2n>2?2n=2n+1.Problem10We want to line up6out of10children.Which of the following expresses the number of possible line-ups?(Circle the right answer.)(a)10!/6!(b)10!/4!(c) 106(d) 104 ·6!(e)None of the above(f)Don’t knowSolution:(b),(d)are both correctProblem11A deck of52cards is shuf?ed thoroughly.What is the probability that the4aces are all next to each other?(Circle theright answer.)(a)4!49!/52!(b)1/52!(c)4!/52!(d)4!48!/52!(e)None of the above(f)Don’t knowSolution:(a)Problem12The weather forecaster says that the probability of rain on Saturday is25%and that the probability of rain on Sunday is25%.Consider the following statement:The probability of rain during the weekend is50%.Which of the following best describes the validity of this statement?(a)If the two events(rain on Sat/rain on Sun)are independent,then we can add up the twoprobabilities,and the statement is true.Without independence,we can’t tell.(b)True,whether the two events are independent or not.(c)If the events are independent,the statement is false,because the the probability of no rainduring the weekend is9/16.If they are not independent,we can’t tell.(d)False,no matter what.(e)None of the above.(f)Don’t know.Solution:(c)Problem13A player throws darts at a target.On each trial,independentlyof the other trials,he hits the bull’s-eye with probability1/4.How many times should he throw so that his probability is75%of hitting the bull’s-eye at least once?(a)3(b)4(c)5(d)75%can’t be achieved.(e)Don’t know.Solution:(c),assuming that we want the probability to be≥0.75,not necessarily exactly0.75.Problem14Let X be an indicator random variable.Which of the following statements are true?(Circle all that apply.)(a)Pr{X=0}=Pr{X=1}=1/2(b)Pr{X=1}=E[X](c)E[X]=E[X2](d)E[X]=(E[X])2Solution:(b)and(c)only。

《算法导论(第二版)》(中文版)课后答案

《算法导论(第二版)》(中文版)课后答案

5
《算法导论(第二版) 》参考答案 do z←y 调用之前保存结果 y←INTERVAL-SEARCH-SUBTREE(y, i) 如果循环是由于y没有左子树,那我们返回y 否则我们返回z,这时意味着没有在z的左子树找到重叠区间 7 if y≠ nil[T] and i overlap int[y] 8 then return y 9 else return z 5 6 15.1-5 由 FASTEST-WAY 算法知:
15
lg n
2 lg n1 1 2cn 2 cn (n 2 ) 2 1
4.3-1 a) n2 b) n2lgn c) n3 4.3-4
2
《算法导论(第二版) 》参考答案 n2lg2n 7.1-2 (1)使用 P146 的 PARTION 函数可以得到 q=r 注意每循环一次 i 加 1,i 的初始值为 p 1 ,循环总共运行 (r 1) p 1次,最 终返回的 i 1 p 1 (r 1) p 1 1 r (2)由题目要求 q=(p+r)/2 可知,PARTITION 函数中的 i,j 变量应该在循环中同 时变化。 Partition(A, p, r) x = A[p]; i = p - 1; j = r + 1; while (TRUE) repeat j--; until A[j] <= x; repeat i++; until A[i] >= x; if (i < j) Swap(A, i, j); else return j; 7.3-2 (1)由 QuickSort 算法最坏情况分析得知:n 个元素每次都划 n-1 和 1 个,因 为是 p<r 的时候才调用,所以为Θ (n) (2)最好情况是每次都在最中间的位置分,所以递推式是: N(n)= 1+ 2*N(n/2) 不难得到:N(n) =Θ (n) 7.4-2 T(n)=2*T(n/2)+ Θ (n) 可以得到 T(n) =Θ (n lgn) 由 P46 Theorem3.1 可得:Ω (n lgn)

中科大算法导论第一,二次和第四次作业答案

中科大算法导论第一,二次和第四次作业答案
第一次作业
2.2-3 再次考虑线性查找问题 (见练习2.1-3)。在平均情况 下,需要检查输入序列中的多 少个元素?假定待查找的元素 是数组中任何一个元素的可能 性是相等的。在最坏情况下有 怎样呢?用Θ形式表示的话,线 性查找的平均情况和最坏情况 运行时间怎样?对你的答案加 以说明。 • 线性查找问题 • 输入:一列数A=<a1,a2,…,an>和一 个值v。 • 输出:下标i,使得v=A[i],或者当 v不在A中出现时为NIL。 • 平均情况下需要查找 (1+2+…+n)/n=(n+1)/2 • 最坏情况下即最后一个元素为待 查找元素,需要查找n个。 • 故平均情况和最坏情况的运行时 间都为Θ(n)。
• 2.3-2改写MERGE过程,使之不使 用哨兵元素,而是在一旦数组L或R 中的所有元素都被复制回数组A后, 就立即停止,再将另一个数组中 余下的元素复制回数组A中。 • MERGE(A,p,q,r) 1. n1←q-p+1 2. n2 ←r-q 3. create arrays L[1..n1] and R[1..n2] 4. for i ←1 to n1 5. do L*i+ ←A*p+i-1] 6. for j ←1 to n2 7. do R*j+ ←A*q+j+ 8. i ←1 9. j ←1
10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21.
k ←p while((i<=n1) and (j<=n2)) do if L[i]<=R[j] do A[k]=L[i] i++ else do A[k]=R[j] j++ k++ while(i<=n1) do A[k++]=L[i++] while(j<=n2) do A[k++]=R[j++]

《算法导论》习题答案

《算法导论》习题答案
i 1
n/2
n! nn , n! o(nn )
3.2.4 是否多项式有界 lg n !与 lg lg n !
设lgn=m,则 m! 2 m ( )m e2m ( )m em(ln m1) mln m1 nln ln n
∴lgn!不是多项式有界的。
T (n) O(lg n)
4.1.2 证明 T (n) 2T (n) n 的解为 O(n lg n)
设 T (n) c n lg n
T (n) 2c n lg n n c lg n n n c(n 1) lg(n / 2) n cn lg n c lg n cn n cn(lg n 1) n c(lg n 2n)
虽然用二分查找法可以将查找正确位置的时间复杂度降下来,但 是移位操作的复杂度并没有减少, 所以最坏情况下该算法的时间复杂 度依然是 (n2 )
2.3-7 给出一个算法, 使得其能在 (n lg n) 的时间内找出在一个 n 元
素的整数数组内,是否存在两个元素之和为 x
首先利用快速排序将数组排序,时间 (n lg n) ,然后再进行查找:
sin(n / 2) 2 1,所以 af (n / b) cf (n) 不满足。 2(sin n 2)
4.1.6 计算 T (n) 2T (
令 m lg n, T (2 ) 2T (2
m m/ 2
n ) 1 的解
) 1
令 T(n)=S(m),则 S (m) 2S (m / 2) 1 其解为 S (m) (m),T (n) S (m) (lg n)
4.2 The recursion-tree method 4.2.1 4.2.2 4.2.3 4.2.5 略

【第二章】算法竞赛入门经典(第二版)-课后习题答案

【第二章】算法竞赛入门经典(第二版)-课后习题答案

2-1 Daffodil2017年10月1日12:561 #include<stdio.h>2 int main(void)3 {4 int shui,xian,hua;5 int n =100;6 int g,s,b;7 int sum =0;8 while(n <1000)9 {10 g =n%10;11 s =n/10%10;12 b =n/100;13 shui =g*g*g;14 xian =s*s*s;15 hua =b*b*b;16 sum =shui +xian +hua;17 if(sum ==n)printf("%d\n",n);18 n++;19 }20 return0;21 }2-2 Hanxin2017年10月1日12:591 #include<stdio.h>2 int main(void)3 {4 int s,w,q;5 int kase =0;6 while(scanf("%d%d%d", &s, &w, &q) !=EOF)7 {8 int i =0;9 int n =10;10 while(n <=101)11 {12 if(n%3==s &&n%5==w &&n%7==q &&n <=100)13 {14 printf("Case %d: %d\n", ++kase,n);15 i =1;16 }17 else if(n >100&&i ==0)printf("Case %d: No answer\n", ++kase);18 n++;19 }20 }21 return0;22 }2-3 Triangle2017年10月1日12:591 #include <stdio.h>2 int main()3 {4 int i, j, n;5 scanf("%d", &n);6 for(i = 0; i < n; i++)7 {8 for(j= 0; j< I; j++)9 printf(" ");10 for(j= 0; j< 2*(n-i)-1; j++)11 printf("#\n");12 }13return0;14}2-4 Subsequence2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 long long n,m;5 int kase =0;6 for( ; ; )7 {8 scanf("%lld%lld", &n, &m);9 if(n ==0&&m ==0)break;10 double sum =0.0;11 while(n <=m)12 {13 long long a =n*n;14 double b = (double)1.0/a;15 sum +=b;16 n++;17 }18 printf("Case %d: %.5lf\n", ++kase,sum);19 }20 return0;21 }22 /*23 将所有int改为long long方才解决问题,为什么?24 long long n, m; 为什么不能为int n, m; ?25 */2-5 Decimal2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 int a,b,c;5 int kase =0;6 int i;7 for(;;)8 {9 scanf("%d%d%d", &a, &b, &c);10 if(a ==0&&b ==0&&c ==0)break;11 a %=b;12 printf("Case %d: %d.", ++kase,a/b);13 for(i =1;i <c;i++)14 {15 printf("%d",a*10/b);16 a =a*10%b;17 }18 if(a%b*10*10/b >=5)19 printf("%d\n",a%b*10/b+1);20 else21 printf("%d\n",a%b*10/b);22 }23 return0;24 }25 /*26 循环+判断 可以避开数组...27 求余的式子很巧妙...28 */2-6 Permutation2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 int a,b,c,d,e,f,g,h,i;5 int n =100;6 while(n <=333)7 {8 a =n/100;9 b =n/10%10;10 c =n%10;11 if(a ==b ||a ==c ||b ==c )12 n++;13 else if(b ==0||c ==0)14 n++;15 else16 {17 int n2 =n*2;18 d =n2/100;19 e =n2/10%10;20 f =n2%10;21 if(e ==0||f ==0)22 n++;23 else if(d ==e ||d ==f ||e ==f)24 n++;25 else if(d ==b ||d ==c)// d == a省略,百位不会相等26 n++;27 else if(e ==a ||e ==b ||e ==c)28 n++;29 else if(f ==a ||f ==b ||f ==c)30 n++;31 else32 {33 int n3 =n*3;34 g =n3/100;35 h =n3/10%10;36 i =n3%10;37 if(h ==0||i ==0)38 n++;39 else if(g ==h ||g ==i ||h ==i)40 n++;41 else if(g ==b ||g ==c ||g ==e ||g ==f)42 n++;43 else if(h ==a ||h ==b ||h ==c ||h ==d ||h ==e ||h ==f)43 else if(h ==a ||h ==b ||h ==c ||h ==d ||h ==e ||h ==f)44 n++;45 else if(i ==a ||i ==b ||i ==c ||i ==d ||i ==e ||i ==f)46 n++;47 else48 {49 printf("%d %d %d\n",n,n2,n3);50 n++;51 }52 }53 }54 }55 return0;56 }Chapter 2 Q&A2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 int n,i;5 scanf("%d", &n);6 for(i =1;i <=n;i++)7 printf("%d\n",i);89 /*10 for(i = 1; i <= n; i++)11 printf("%d\n", 2*i); //任务一1213 for(i = 2; i <= 2*n; i+=2) //任务二14 printf("%d\n", i);15 */1617 return0;18 }1 #include<stdio.h>2 int main(void)3 {4 double i;5 for(i =0;i !=10;i +=0.1)6 printf("%.1f\n",i);7 return0;8 }。

算法导论答案 (4)

算法导论答案 (4)

算法导论答案第一章:算法概述啊算法的定义算法是一系列解决问题的明确指令。

它是一个有穷步骤集,其中每个步骤或操作由确定性和可行性特征。

算法是通过将预期的输入转换为输出来解决问题的工具。

第二章:插入排序插入排序的思想插入排序是一种简单直观的排序算法,其基本思想是将待排序的序列分为已排序和未排序两部分,每次从未排序的部分中取出一个元素,并将其插入到已排序部分的正确位置,直到所有元素都被排序。

插入排序的算法实现以下是插入排序的伪代码:INSERTION-SORT(A)for j = 2 to A.lengthkey = A[j]// Insert A[j] into the sorted sequence A[1.. j-1].i = j - 1while i > 0 and A[i] > keyA[i + 1] = A[i]i = i - 1A[i + 1] = key插入排序的时间复杂度插入排序的时间复杂度为O(n^2),其中n是排序的元素个数。

虽然插入排序的最坏情况下的复杂度很高,但是对于小规模的数据集,插入排序是一种较快的排序算法。

第三章:分治策略分治策略的基本思想分治策略是一种解决问题的思想,它将问题的规模不断缩小,直到问题足够小而可以直接解决。

然后将子问题的解合并起来,得到原问题的解。

分治策略的应用实例一种经典的应用分治策略的算法是归并排序。

归并排序将待排序的序列划分为两个子序列,分别排序后再将两个有序子序列合并为一个有序序列。

以下是归并排序的伪代码:MERGE-SORT(A, p, r)if p < rq = floor((p + r) / 2)MERGE-SORT(A, p, q)MERGE-SORT(A, q + 1, r)MERGE(A, p, q, r)MERGE(A, p, q, r)n1 = q - p + 1n2 = r - qlet L[1..n1+1] and R[1..n2+1] be new arraysfor i = 1 to n1L[i] = A[p + i - 1]for j = 1 to n2R[j] = A[q + j]L[n1 + 1] = infinityR[n2 + 1] = infinityi = 1j = 1for k = p to rif L[i] <= R[j]A[k] = L[i]i = i + 1elseA[k] = R[j]j = j + 1分治策略的时间复杂度归并排序的时间复杂度为O(nlogn),其中n是待排序序列的长度。

算法导论第三版_习题_第二章_C语言实现

算法导论第三版_习题_第二章_C语言实现

目录第二章 (2)练习题 (2)2.1-1 (2)2.1-2 (2)2.1-3 (2)2.1-4 (3)2.2-1 (3)2.2-2 (3)2.2-3 (4)2.2-4 (4)2.3-1 (4)2.3-2 (4)2.3-3 (4)2.3-4 (5)2.3-5 (5)2.3-6 (6)*2.3-7 (6)思考题 (6)2-1 ( (6)第二章练习题2.1-1以图2-2为模型,说明INSERTION-SORT在数组A=(31,41,59,26, 41,58〉上的执行过程。

略2.1-2重写过程INSERTION-SORT,使之按非升序(而不是非降序)排序。

//2.1-2.c 插入排序-非升序void InsertionSortNI(int ar[],int n){int i,j,key;for(j=1;j<n;j++){key = ar[j];i = j-1;while(i>=0&& ar[i]<key){ar[i+1]= ar[i];i=i-1;}ar[i+1]= key;}}2.1-3思考下面的查找问题:输入:有n个元素的序列A= (a1,a2,…,an)和一个值v。

输出:下标i(当v=A[i]), 或者特殊值NIL(当v不在A中出现时)。

写出线性查找的伪代码,它扫描整个序列来查找v。

使用一个循环不变式来证明你的算法是正确的。

确保你的循环不变式满足三条必要的性质。

代码://2.1-3.c 线性查找int serchv(int A[],int n,int v){int i;for(i=0;i<n;i++){if(A[i]==v)return i;}return 'NULL';}证明:循环不变式:在每一次for循环开始时,子数组A[0, ..., i-1]中的元素都不等于v;初始化:在第一次迭代之前,i=0,子数组是空数组,易知循环不定式是成立的;保持:在每次循环内部,将A[i] 与v比较,若符合,则返回正确结果i;在每次循环结束时,得知子数组A[0, ..., i-2]不含有v,循环不定式维持成立;递增i,使循环遍历数组中的元素,直到找到v或到达数组尽头;终止:终止条件为1. i>=n 或者2. A[i]==v。

算法导论习题答案 (1)

算法导论习题答案 (1)

Introduction to Algorithms September 24, 2004Massachusetts Institute of Technology 6.046J/18.410J Professors Piotr Indyk and Charles E. Leiserson Handout 7Problem Set 1 SolutionsExercise 1-1. Do Exercise 2.3-7 on page 37 in CLRS.Solution:The following algorithm solves the problem:1.Sort the elements in S using mergesort.2.Remove the last element from S. Let y be the value of the removed element.3.If S is nonempty, look for z=x−y in S using binary search.4.If S contains such an element z, then STOP, since we have found y and z such that x=y+z.Otherwise, repeat Step 2.5.If S is empty, then no two elements in S sum to x.Notice that when we consider an element y i of S during i th iteration, we don’t need to look at the elements that have already been considered in previous iterations. Suppose there exists y j∗S, such that x=y i+y j. If j<i, i.e. if y j has been reached prior to y i, then we would have found y i when we were searching for x−y j during j th iteration and the algorithm would have terminated then.Step 1 takes �(n lg n)time. Step 2 takes O(1)time. Step 3 requires at most lg n time. Steps 2–4 are repeated at most n times. Thus, the total running time of this algorithm is �(n lg n). We can do a more precise analysis if we notice that Step 3 actually requires �(lg(n−i))time at i th iteration.However, if we evaluate �n−1lg(n−i), we get lg(n−1)!, which is �(n lg n). So the total runningi=1time is still �(n lg n).Exercise 1-2. Do Exercise 3.1-3 on page 50 in CLRS.Exercise 1-3. Do Exercise 3.2-6 on page 57 in CLRS.Exercise 1-4. Do Problem 3-2 on page 58 of CLRS.Problem 1-1. Properties of Asymptotic NotationProve or disprove each of the following properties related to asymptotic notation. In each of the following assume that f, g, and h are asymptotically nonnegative functions.� (a) f (n ) = O (g (n )) and g (n ) = O (f (n )) implies that f (n ) = �(g (n )).Solution:This Statement is True.Since f (n ) = O (g (n )), then there exists an n 0 and a c such that for all n √ n 0, f (n ) ←Similarly, since g (n )= O (f (n )), there exists an n � 0 and a c such that for allcg (n ). �f (n ). Therefore, for all n √ max(n 0,n Hence, f (n ) = �(g (n )).�()g n ,0← �),0c 1 � g (n ) ← f (n ) ← cg (n ).n √ n c � 0 (b) f (n ) + g (n ) = �(max(f (n ),g (n ))).Solution:This Statement is True.For all n √ 1, f (n ) ← max(f (n ),g (n )) and g (n ) ← max(f (n ),g (n )). Therefore:f (n ) +g (n ) ← max(f (n ),g (n )) + max(f (n ),g (n )) ← 2 max(f (n ),g (n ))and so f (n ) + g (n )= O (max(f (n ),g (n ))). Additionally, for each n , either f (n ) √max(f (n ),g (n )) or else g (n ) √ max(f (n ),g (n )). Therefore, for all n √ 1, f (n ) + g (n ) √ max(f (n ),g (n )) and so f (n ) + g (n ) = �(max(f (n ),g (n ))). Thus, f (n ) + g (n ) = �(max(f (n ),g (n ))).(c) Transitivity: f (n ) = O (g (n )) and g (n ) = O (h (n )) implies that f (n ) = O (h (n )).Solution:This Statement is True.Since f (n )= O (g (n )), then there exists an n 0 and a c such that for all n √ n 0, �)f ()n ,0← �()g n ,0← f (n ) ← cg (n ). Similarly, since g (n ) = O (h (n )), there exists an n �h (n ). Therefore, for all n √ max(n 0,n and a c � such thatfor all n √ n Hence, f (n ) = O (h (n )).cc�h (n ).c (d) f (n ) = O (g (n )) implies that h (f (n )) = O (h (g (n )).Solution:This Statement is False.We disprove this statement by giving a counter-example. Let f (n ) = n and g (n ) = 3n and h (n )=2n . Then h (f (n )) = 2n and h (g (n )) = 8n . Since 2n is not O (8n ), this choice of f , g and h is a counter-example which disproves the theorem.(e) f(n)+o(f(n))=�(f(n)).Solution:This Statement is True.Let h(n)=o(f(n)). We prove that f(n)+o(f(n))=�(f(n)). Since for all n√1, f(n)+h(n)√f(n), then f(n)+h(n)=�(f(n)).Since h(n)=o(f(n)), then there exists an n0such that for all n>n0, h(n)←f(n).Therefore, for all n>n0, f(n)+h(n)←2f(n)and so f(n)+h(n)=O(f(n)).Thus, f(n)+h(n)=�(f(n)).(f) f(n)=o(g(n))and g(n)=o(f(n))implies f(n)=�(g(n)).Solution:This Statement is False.We disprove this statement by giving a counter-example. Consider f(n)=1+cos(�≈n)and g(n)=1−cos(�≈n).For all even values of n, f(n)=2and g(n)=0, and there does not exist a c1for which f(n)←c1g(n). Thus, f(n)is not o(g(n)), because if there does not exist a c1 for which f(n)←c1g(n), then it cannot be the case that for any c1>0and sufficiently large n, f(n)<c1g(n).For all odd values of n, f(n)=0and g(n)=2, and there does not exist a c for which g(n)←cf(n). By the above reasoning, it follows that g(n)is not o(f(n)). Also, there cannot exist c2>0for which c2g(n)←f(n), because we could set c=1/c2if sucha c2existed.We have shown that there do not exist constants c1>0and c2>0such that c2g(n)←f(n)←c1g(n). Thus, f(n)is not �(g(n)).Problem 1-2. Computing Fibonacci NumbersThe Fibonacci numbers are defined on page 56 of CLRS asF0=0,F1=1,F n=F n−1+F n−2for n√2.In Exercise 1-3, of this problem set, you showed that the n th Fibonacci number isF n=�n−� n,�5where �is the golden ratio and �is its conjugate.A fellow 6.046 student comes to you with the following simple recursive algorithm for computing the n th Fibonacci number.F IB(n)1 if n=02 then return 03 elseif n=14 then return 15 return F IB(n−1)+F IB(n−2)This algorithm is correct, since it directly implements the definition of the Fibonacci numbers. Let’s analyze its running time. Let T(n)be the worst-case running time of F IB(n).1(a) Give a recurrence for T(n), and use the substitution method to show that T(n)=O(F n).Solution: The recurrence is: T(n)=T(n−1)+T(n−2)+1.We use the substitution method, inducting on n. Our Induction Hypothesis is: T(n)←cF n−b.To prove the inductive step:T(n)←cF n−1+cF n−2−b−b+1← cF n−2b+1Therefore, T(n)←cF n−b+1provided that b√1. We choose b=2and c=10.∗{For the base case consider n0,1}and note the running time is no more than10−2=8.(b) Similarly, show that T(n)=�(F n), and hence, that T(n)=�(F n).Solution: Again the recurrence is: T(n)=T(n−1)+T(n−2)+1.We use the substitution method, inducting on n. Our Induction Hypothesis is: T(n)√F n.To prove the inductive step:T(n)√F n−1+F n−2+1√F n+1Therefore, T(n)←F n. For the base case consider n∗{0,1}and note the runningtime is no less than 1.1In this problem, please assume that all operations take unit time. In reality, the time it takes to add two num­bers depends on the number of bits in the numbers being added (more precisely, on the number of memory words). However, for the purpose of this problem, the approximation of unit time addition will suffice.Professor Grigori Potemkin has recently published an improved algorithm for computing the n th Fibonacci number which uses a cleverly constructed loop to get rid of one of the recursive calls. Professor Potemkin has staked his reputation on this new algorithm, and his tenure committee has asked you to review his algorithm.F IB�(n)1 if n=02 then return 03 elseif n=14 then return 15 6 7 8 sum �1for k�1to n−2do sum �sum +F IB�(k) return sumSince it is not at all clear that this algorithm actually computes the n th Fibonacci number, let’s prove that the algorithm is correct. We’ll prove this by induction over n, using a loop invariant in the inductive step of the proof.(c) State the induction hypothesis and the base case of your correctness proof.Solution: To prove the algorithm is correct, we are inducting on n. Our inductionhypothesis is that for all n<m, Fib�(n)returns F n, the n th Fibonacci number.Our base case is m=2. We observe that the first four lines of Potemkin guaranteethat Fib�(n)returns the correct value when n<2.(d) State a loop invariant for the loop in lines 6-7. Prove, using induction over k, that your“invariant” is indeed invariant.Solution: Our loop invariant is that after the k=i iteration of the loop,sum=F i+2.We prove this induction using induction over k. We assume that after the k=(i−1)iteration of the loop, sum=F i+1. Our base case is i=1. We observe that after thefirst pass through the loop, sum=2which is the 3rd Fibonacci number.To complete the induction step we observe that if sum=F i+1after the k=(i−1)andif the call to F ib�(i)on Line 7 correctly returns F i(by the induction hypothesis of ourcorrectness proof in the previous part of the problem) then after the k=i iteration ofthe loop sum=F i+2. This follows immediately form the fact that F i+F i+1=F i+2.(e) Use your loop invariant to complete the inductive step of your correctness proof.Solution: To complete the inductive step of our correctness proof, we must show thatif F ib�(n)returns F n for all n<m then F ib�(m)returns m. From the previous partwe know that if F ib�(n)returns F n for all n<m, then at the end of the k=i iterationof the loop sum=F i+2. We can thus conclude that after the k=m−2iteration ofthe loop, sum=F m which completes our correctness proof.(f) What is the asymptotic running time, T�(n), of F IB�(n)? Would you recommendtenure for Professor Potemkin?Solution: We will argue that T�(n)=�(F n)and thus that Potemkin’s algorithm,F ib�does not improve upon the assymptotic performance of the simple recurrsivealgorithm, F ib. Therefore we would not recommend tenure for Professor Potemkin.One way to see that T�(n)=�(F n)is to observe that the only constant in the programis the 1 (in lines 5 and 4). That is, in order for the program to return F n lines 5 and 4must be executed a total of F n times.Another way to see that T�(n)=�(F n)is to use the substitution method with thehypothesis T�(n)√F n and the recurrence T�(n)=cn+�n−2T�(k).k=1Problem 1-3. Polynomial multiplicationOne can represent a polynomial, in a symbolic variable x, with degree-bound n as an array P[0..n] of coefficients. Consider two linear polynomials, A(x)=a1x+a0and B(x)=b1x+b0, where a1, a0, b1, and b0are numerical coefficients, which can be represented by the arrays [a0,a1]and [b0,b1], respectively. We can multiply A and B using the four coefficient multiplicationsm1=a1·b1,m2=a1·b0,m3=a0·b1,m4=a0·b0,as well as one numerical addition, to form the polynomialC(x)=m1x2+(m2+m3)x+m4,which can be represented by the array[c0,c1,c2]=[m4,m3+m2,m1].(a) Give a divide-and-conquer algorithm for multiplying two polynomials of degree-bound n,represented as coefficient arrays, based on this formula.Solution:We can use this idea to recursively multiply polynomials of degree n−1, where n isa power of 2, as follows:Let p(x)and q(x)be polynomials of degree n−1, and divide each into the upper n/2 and lower n/2terms:p(x)=a(x)x n/2+b(x),q(x)=c(x)x n/2+d(x),where a(x), b(x), c(x), and d(x)are polynomials of degree n/2−1. The polynomial product is thenp(x)q(x)=(a(x)x n/2+b(x))(c(x)x n/2+d(x))=a(x)c(x)x n+(a(x)d(x)+b(x)c(x))x n/2+b(x)d(x).The four polynomial products a(x)c(x), a(x)d(x), b(x)c(x), and b(x)d(x)are com­puted recursively.(b) Give and solve a recurrence for the worst-case running time of your algorithm.Solution:Since we can perform the dividing and combining of polynomials in time �(n), re­cursive polynomial multiplication gives us a running time ofT(n)=4T(n/2)+�(n)=�(n2).(c) Show how to multiply two linear polynomials A(x)=a1x+a0and B(x)=b1x+b0using only three coefficient multiplications.Solution:We can use the following 3 multiplications:m1=(a+b)(c+d)=ac+ad+bc+bd,m2=ac,m3=bd,so the polynomial product is(ax+b)(cx+d)=m2x2+(m1−m2−m3)x+m3.� (d) Give a divide-and-conquer algorithm for multiplying two polynomials of degree-bound nbased on your formula from part (c).Solution:The algorithm is the same as in part (a), except for the fact that we need only compute three products of polynomials of degree n/2 to get the polynomial product.(e) Give and solve a recurrence for the worst-case running time of your algorithm.Solution:Similar to part (b):T (n )=3T (n/2) + �(n )lg 3)= �(n �(n 1.585)Alternative solution Instead of breaking a polynomial p (x ) into two smaller poly­nomials a (x ) and b (x ) such that p (x )= a (x ) + x n/2b (x ), as we did above, we could do the following:Collect all the even powers of p (x ) and substitute y = x 2 to create the polynomial a (y ). Then collect all the odd powers of p (x ), factor out x and substitute y = x 2 to create the second polynomial b (y ). Then we can see thatp (x ) = a (y ) + x b (y )· Both a (y ) and b (y ) are polynomials of (roughly) half the original size and degree, and we can proceed with our multiplications in a way analogous to what was done above.Notice that, at each level k , we need to compute y k = y 2 (where y 0 = x ), whichk −1 takes time �(1) per level and does not affect the asymptotic running time.。

算法分析教材习题答案(第2章)

算法分析教材习题答案(第2章)

第2章算法分析题2-2分析与解答:算法BinarySearch1与教材中的算法BinarySearch 相比,数组段左右游标left 和right 的调整不正确,导致陷入死循环。

算法BinarySearch2与教材中的算法BinarySearch 相比,数组段左右游标left 和right 的调整不正确,导致x=a[n-1]时返回错误。

算法BinarySearch3与正确算法BinarySearch5相比,数组段左右游标left 和right 的调整不正确,导致x=a[n-1]时返回错误。

算法BinarySearch4与正确算法BinarySearch5相比,数组段左右游标left 和right 的调整不正确,导致陷入死循环。

算法BinarySearch5正确,且当数组中有重复元素时,返回满足条件的最右元素。

算法BinarySearch6与正确算法BinarySearch5相比,数组段左右游标left 和right 的调整不正确,导致x=a[n-1]时返回错误。

算法BinarySearch7与正确算法BinarySearch5相比,数组段左右游标left 和right 的调整不正确,导致x=a[0]时陷入死循环。

算法分析题2-5分析与解答:这个问题有更一般的解。

将两个 n 位大整数u 和v 都分割为n/m 位的m 段,可以用2m-1次n/m 位整数的乘法求得uv 的值。

事实上,设x=2n/m ,可以将u 和v 及其乘积w=vu 表示为:U=u 0+u 1x+…+u m-1x m-1,v=v o +v 1x+…+v m-1x m-1W=uv=w 0+w 1x+w 2x 2+...+w 2m-2x 2m-2将u,v 和w 都看作关于变量x 的多项式,并取2m-1个不同的数x1,x2,…x2m-1,代入多项式,可得:U(x i )=u 0+u 1x+…+u m-1x m-1,V(xi)=v o +v 1x+…+v m-1x m-1W(x i )=u(x i )v(x i )= w 0+w 1x+w 2x 2+...+w 2m-2x 2m-2用矩阵形式表示为:w(x 1) 1 x 1 x 12 … x 12m-2 w 0w(x 2) = 1 x 2 x 22 … x 22m-2 w 1. .. . .... .W(x 2m-1) 1 x 2m-1 x 2m-12 ... x 2m-12m-2 w 2m-2设 B= =B -1其中,W(x i )=u(x i )v(x i )是两个n/m 位数的乘法去处,共有2m-1个乘法,其他均为加减法或数乘运算。

算法导论第三版答案

算法导论第三版答案
Solution to Exercise 2.3-5
Procedure BINARY-SEARCH takes a sorted array A, a value , and a range Œlow : : high of the array, in which we search for the value . The procedure compares to the array entry at the midpoint of the range and decides to eliminate half the range from further consideration. We give both iterative and recursive versions, each of which returns either an index i such that AŒi D , or NIL if no utions for Chapter 2: Getting Started
AŒlow : : high contains the value . The initial call to either version should have the parameters A; ; 1; n.
Selected Solutions for Chapter 2: Getting Started
2-3
d. We follow the hint and modify merge sort to count the number of inversions in ‚.n lg n/ time.
To start, let us define a merge-inversion as a situation within the execution of merge sort in which the MERGE procedure, after copying AŒp : : q to L and AŒq C 1 : : r to R, has values x in L and y in R such that x > y. Consider an inversion .i; j /, and let x D AŒi and y D AŒj , so that i < j and x > y. We claim that if we were to run merge sort, there would be exactly one mergeinversion involving x and y. To see why, observe that the only way in which array elements change their positions is within the MERGE procedure. Moreover, since MERGE keeps elements within L in the same relative order to each other, and correspondingly for R, the only way in which two elements can change their ordering relative to each other is for the greater one to appear in L and the lesser one to appear in R. Thus, there is at least one merge-inversion involving x and y. To see that there is exactly one such merge-inversion, observe that after any call of MERGE that involves both x and y, they are in the same sorted subarray and will therefore both appear in L or both appear in R in any given call thereafter. Thus, we have proven the claim.

算法导论(第二版)课后习题解答

算法导论(第二版)课后习题解答
n
Θ
i=1
i
= Θ(n2 )
This holds for both the best- and worst-case running time. 2.2 − 3 Given that each element is equally likely to be the one searched for and the element searched for is present in the array, a linear search will on the average have to search through half the elements. This is because half the time the wanted element will be in the first half and half the time it will be in the second half. Both the worst-case and average-case of L INEAR -S EARCH is Θ(n). 3
Solutions for Introduction to algorithms second edition
Philip Bille
The author of this document takes absolutely no responsibility for the contents. This is merely a vague suggestion to a solution to some of the exercises posed in the book Introduction to algorithms by Cormen, Leiserson and Rivest. It is very likely that there are many errors and that the solutions are wrong. If you have found an error, have a better solution or wish to contribute in some constructive way please send a message to beetle@it.dk. It is important that you try hard to solve the exercises on your own. Use this document only as a last resort or to check if your instructor got it all wrong. Please note that the document is under construction and is updated only sporadically. Have fun with your algorithms. Best regards, Philip Bille

算法导论中文版答案

算法导论中文版答案

24.2-3
24.2-4
24.3-1 见图 24-6 24.3-2
24.3-3
24.3-4 24.3-5 24.3-6
24.3-7
24.3-8 这种情况下不会破坏已经更新的点的距离。 24.4**** 24.5****
25.1-1 见图 25-1 25.1-2 为了保证递归定义式 25.2 的正确性 25.1-3
8.3-3 8.3-4
8.3-5(*) 8.4-1 见图 8-4 8.4-2
8.4-3 3/2,1/2 8.4-4(*) 8.4-5(*)
9.1-1
9.1-2 9.2-1 9.3-1
第九章
9.3-2 9.3-3
9.3-4 9.3-5
9.3-6 9.3-7
9.3-8
9.3-9
15.1-1
6.4-4
6.4-5
6.5-1 据图 6-5 6.5-2
6.5-3 6.5-4 6.5-5
6.5-6 6.5-7
6.5-8
7.1-1 见图 7-1 7.1-2
7.1-3 7.1-4 7.2-1 7.2-2
7.2-3 7.2-4 7.2-5
第七章
7.2-6 7.3-1
7.3-2
7.4-1 7.4-2
5.3-6
6.1-1 6.1-2 6.1-3 6.1-4 6.1-5 6.1-6
第6章
6.1-7
6.2-1 见图 6-2 6.2-2
6.2-3
6.2-4
6.2-5 对以 i 为根结点的子树上每个点用循环语句实现 6.2-6
6.3-1
见图 6-3 6.3-2
6.3-3
6.4-1 见图 6-4 6.4-2 HEAPSORT 仍然正确,因为每次循环的过程中还是会运行 MAX-HEAP 的过程。 6.4-3

《算法导论》习题答案

《算法导论》习题答案

《算法导论》习题答案Chapter2 Getting Start2.1 Insertion sort2.1.2 将Insertion-Sort重写为按非递减顺序排序2.1.3 计算两个n位的二进制数组之和2.2 Analyzing algorithms2.2.1将函数用符号表示2.2.2写出选择排序算法selection-sort 当前n-1个元素排好序后,第n个元素已经是最大的元素了.最好时间和最坏时间均为2.3 Designing algorithms计算递归方程的解(1) 当时,,显然有T((2) 假设当时公式成立,即,则当,即时,2.3.4 给出insertion sort的递归版本的递归式2.3-6 使用二分查找来替代insertion-sort中while循环j?n;if A[i]+A[j]&lt;xi?i+1elsej?j-1if A[i]+A[j]=xreturn trueelsereturn false时间复杂度为。

或者也可以先固定一个元素然后去二分查找x减去元素的差,复杂度为。

Chapter3 Growth of functions3.1Asymptotic notation3.1.2证明对于b时,对于,时,存在,当时,对于,3.1-4 判断与22n是否等于O(2n)3.1.6 证明如果算法的运行时间为,如果其最坏运行时间为O(g(n)),最佳运行时间为。

最坏时间O(g(n)),即;最佳时间,即3.1.7:证明定义3.2 Standard notation and common functions 3.2.2 证明证明当n&gt;4时,,是否多项式有界~与设lgn=m,则?lgn~不是多项式有界的。

mememmmm2设,,是多项式有界的3.2.5比较lg(lg*n)与lg*(lgn)lg*(lgn)= lg*n-1设lg*n=x,lgx&lt;x-1较大。

算法导论中文版答案

算法导论中文版答案
len=j;//更新 len
} cout<<len<<endl; } return 0; } 15.5-1
15.5-2 15.5-3
15.5-4
16.1-1
第 16 章
16.1-2 16.1-3
16.1-4 16.2-1 16.2-2
16.2-3
16.2-4
16.2-5 16.2-6
16.2-7
25.3-6
5.3-6
6.1-1 6.1-2 6.1-3 6.1-4 6.1-5 6.1-6
第6章
6.1-7
6.2-1 见图 6-2 6.2-2
6.2-3
6.2-4
6.2-5 对以 i 为根结点的子树上每个点用循环语句实现 6.2-6
6.3-1
见图 6-3 6.3-2
6.3-3
6.4-1 见图 6-4 6.4-2 HEAPSORT 仍然正确,因为每次循环的过程中还是会运行 MAX-HEAP 的过程。 6.4-3
6.4-4
6.4-5
6.5-1 据图 6-5 6.5-2
6.5-3 6.5-4 6.5-5
6.5-6 6.5-7
6.5-8
7.1-1 见图 7-1 7.1-2
7.1-3 7.1-4 7.2-1 7.2-2
7.2-3 7.2-4 7.2-5
第七章
7.2-6 7.3-1
7.3-2
7.4-1 7.4-2
16.3-1 16.3-2
16.3-3 16.3-4
16.3-5
16.3-6 那就推广到树的结点有三个孩子结点,证明过程同引理 16.3 的证明。 16.3-7 16.3-8
第 24 章
24.1-1 同源顶点 s 的运行过程,见图 24-4 24.1-2

算法导论习题答案 (2)

算法导论习题答案 (2)
If a is equivalent to zero, then the probability that a(x) = 0 is 1. By definition, if a is equivalent to zero, then a(x) = 0 for all x ≤ {0, . . . , p − 1}.
Problem Set 2 Solutions
Reading: Chapters 5-9, excluding 5.4 and 8.4 Both exercises and problems should be solved, but only the problems should be turned in.
Exercise 2-1. Do Exercise 5.2-4 on page 98 in CLRS. Exercise 2-2. Do Exercise 8.2-3 on page 170 in CLRS.
Problem 2-1. Randomized Evaluation of Polynomials
1. A description of the algorithm in English and, if helpful, pseudo-code.
2. At least one worked example or diagram to show more precisely how your algorithm works.
A finite field has a finite number of elements. In this problem, we consider the field of integers modulo p. That is, we consider two integers a and b to be “equal” if and only if they have the same remainder when divided by p, in which case we write a ≥ b mod p. This field, which we denote as Z/p, has p elements, {0, . . . , p − 1}.
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

2.1-2 重写过程INSERTION-SORT,使之按非升序(而不是按非降序)排序。

伪代码如下:
INSERTION-SORT(A)
for j←to length[A]
do key←A[J]
i←j-1
while i>0 and A[i]<key
do A[i+1]←A[i]
i←i-1
A[i+1]←key
2.1-3 考虑下面的查找问题:
输入:一列数A=<a1,a2,…,an>和一个值V。

输出:下标i,使得V=A[i],或者当V不再A中出现时为NIL。

写出针对这个问题的线性查找的伪代码,它顺序地扫描整个序列以查找V。

利用循环不变式证明算法的正确性。

确保所给出的循环不变式满足三个必要的性质。

伪代码如下:
LINEAR-SEARCH(A,V)
flag←0
for i←1 to length[A]
do if A[i]==V
then print i
flag←1
if flag==0
then print NIL
循环不变式的证明如下:
初始化:首先,先来证明在第一轮迭代之前,它是成立的。

此时,flag初始化为0,表示未找到这样一个小标i,使得A[i]=V.若为1,则表示已找到一个或多个这样的下标。

那么,很显然,在还未开始之前flag=0是正确的,也就证明了循环不变式在循环的第一轮迭代开始之前是成立的。

保持:接下来证明每一轮循环都能使循环不变式保持成立。

我们看到,在第一个for循环体内,随着i逐个从1到遍历完整个数列的过程中,只要有一个下标i,使得A[i]等于V,那么在输出i的同时,将flag重新标记为1,表示已找到。

无论接下来是否还有这样满足条件的i出现,flag的值不变,仍为1,反之,若遍历完之后,没有找到这样的一个i,那么flag 在这个for循环中未做任何改变,仍为0。

所以,循环不变式的第二个性质也成立。

终止:对此线性查找算法来说,当i大于length[A]的值(即遍历完整个A数列后),for 循环结束。

这时,如果flag未改变(即flag=0),则说明未能找到这样的下标i,输出NIL;反之,若已在for循环中被修改为1,则不会运行此步语句,这也就意味着该算法是正确的。

2.1-4 有两个各存放在数组A和B中的n位二进制整数,考虑它们的相加问题。

两个整数的和以二进制形式存放在具有(n+1)个元素的数组C中。

请给出这个问题的形式化描述,并写出伪代码。

形式化描述如下:
首先,初始化数组C,使其n+1各元素的值都为0。

接着,利用for循环用i同时从n到1反向遍历A、B数组,每遍历一步,作一个判断:若A[i]+B[i]>1,则C[i]=C[i]+1;反之,C[i+1]=A[i]+B[i]。

最后,当i=0时,for循环结束,此时C数组中存储的即是所求的结果。

伪代码如下:
BINRARY-SUM(A,B,C)
for i←1 to n+1
do C[i]←0
for i←n to 1
do if A[i]+B[i]>1
then C[i]=C[i]+1
else C[i+1]=A[i]+B[i]
问题描述:
有两个各存放在数组A和B中的n位二进制整数,考虑它们的相加问题。

两个整数的和以二进制形式存放在具有(n+1)个元素的数组C中。

问题思考:
先假设整数的二进制数组中,高位在前,低位在后,所以得从后面往前面加——即从低位往高位的顺序加,即循环顺序应为从大到小(n到1)。

主要注意的一个问题就是进位的处理,当低位A[i]+B[i]>1时,就会向高位推送一个进位1,那么对于下一次的相加就应该有:
A[i-1]+B[i-1]+进位。

这里把进位描述为carry_flag,并将其初始化为0。

那么就有通用表达式:C[i+1]=(A[i]+B[i]+carry_flag)%2,
这里之所以对2取余,是因为二进制只有0,1(貌似这句话多余了);之所以是C[i+1],而不是C[i],是因为C[n+1](即整数的二进制表示的最低位)的值应该是(A[n]+B[n])%2 的结果,依次类推就有了上面的那个通用表达式,记得每次加完之后都要更新carry_flag。

伪代码:
BINARY-ADD(A,B,C,n)
▷这里假设整数的二进制表示中,高位在前,低位在后
carry_flag ← 0
for j ← n to 1
do key ← A[j]+B[j]+carry_flag
C[j+1] ← key mod 2
if key > 1
carry_flag ← 1
else
carry_flag ← 0
C[0] ← carry_flag
C/C++ 代码:
view sourceprint?
#include <stdio.h>
void binary_add(int* a, int *b, int *c, int length){
int i = 0;
int carry_flag = 0;
for(i=length-1; i>=0; i--){
int tmp = a[i]+b[i]+carry_flag;
c[i+1] = tmp % 2;
if(tmp>1){
carry_flag = 1;
}else{
carry_flag = 0;
}
}
c[0]=carry_flag;
}
void main(){
int i = 0;
int length = 0;
int A[8] = {1,0,1,1,1,0,0,1}; //185的二进制形式,高位在前,低位在后 int B[8] = {1,1,0,0,1,0,1,1}; //203的二进制形式,高位在前,低位在后 int C[9] = {0};
length = sizeof(A)/sizeof(int);
binary_add(A,B,C,length);
for(i=0;i<=length;i++){
printf("%d,",C[i]);
}
}
/*----------------------
* 输出结果为:
* 1,1,0,0,0,0,1,0,0
* 388的二进制表示形式
-------------------------*/
JAVA 代码:
view sourceprint?
public class Test{
int[] A = {1,0,1,1,1,0,0,1}; //185的二进制形式,高位在前,低位在后 int[] B = {1,1,0,0,1,0,1,1}; //203的二进制形式,高位在前,低位在后 int[] C = {0,0,0,0,0,0,0,0,0};
private void binary_add(int[] a, int[] b, int[] c, int length){ int carry_flag = 0;
for(int i=length-1; i>=0; i--){
int tmp = a[i]+b[i]+carry_flag;
c[i+1] = tmp % 2;
if(tmp>1){
carry_flag = 1;
}else{
carry_flag = 0;
}
}
c[0]=carry_flag;
}
public static void main(String[] args){
Test test = new Test();
test.binary_add(test.A, test.B, test.C, test.A.length); for(int i=0; i<=test.A.length; i++){
System.out.print(test.C[i]+",");
}
}
}
/*-----------------------
* 输出结果为:
* 1,1,0,0,0,0,1,0,0,
* 即十进制388
-------------------------*/。

相关文档
最新文档