算法导论第二章第一节答案
- 格式:docx
- 大小:19.34 KB
- 文档页数:5
学习资料第二章算法初步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。
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 }。
算法导论答案第一章:算法概述啊算法的定义算法是一系列解决问题的明确指令。
它是一个有穷步骤集,其中每个步骤或操作由确定性和可行性特征。
算法是通过将预期的输入转换为输出来解决问题的工具。
第二章:插入排序插入排序的思想插入排序是一种简单直观的排序算法,其基本思想是将待排序的序列分为已排序和未排序两部分,每次从未排序的部分中取出一个元素,并将其插入到已排序部分的正确位置,直到所有元素都被排序。
插入排序的算法实现以下是插入排序的伪代码: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是待排序序列的长度。
目录第二章 (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。
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 numbers 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 computed 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), recursive 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 polynomials 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.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
-------------------------*/。