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

合集下载

算法导论课程作业答案

算法导论课程作业答案

算法导论课程作业答案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。

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

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

26.1-2
26.2-1
26.2-4
14
《算法导论(第二版) 》参考答案 26.3-1 s–1–6–t s–2–8–t s–3–7–t 26.3-3
26.4-2 根据 26.22 对每个顶点执行 relabel 操作的次数最多为 2|V|-1 所以对每条边检测次数最多为 2*(2|V|-1)次 O(V) 在剩余网络中最多 2|E|条边 O(E) 所以为 O(VE)
f1[ j ] f 2 [ j 1] t2, j 1 a1, j f 2 [ j ] f1[ j 1] t1, j 1 a2, j
所以有:
f1[ j ] f 2 [ j ] f 2 [ j 1] t2, j 1 a1, j f1[ j 1] t1, j 1 a2, j
6
《算法导论(第二版) 》参考答案
最终答案:((A1A2)((A3A4)(A5A6))) 15.2-2
15.3-2 没有重叠的子问题存在 15.3-4 这题比较简单,由 P328 的(15.6)(15.7)展开两三步就可以看出来. 15.4-3 先初始化 c 数组元素为无穷大
7
《算法导论(第二版) 法, 最好是像书上画一颗递归树然后进行运算。
1
《算法导论(第二版) 》参考答案
注意题目中的要求使用递归树的方法,最好是像书上画一颗递归树然后进行运 算。 4.2.2 证略 4.2.3 由 2 i n 得 i=lgn
T (n) 2 i cn cn
i 0
由课本 P328(15.6) (15.7)式代入,可得:
min( f1[ j 1] a1, j , f 2 [ j 1] t2, j 1 a1, j ) min( f 2 [ j 1] a2, j , f1[ j 1] t1, j 1 a2, j ) min( f1[ j 1], f 2 [ j 1] t2, j 1 ) a1, j min( f 2 [ j 1], f1[ j 1] t1, j 1 ) a2, j f 2 [ j 1] t2, j 1 a1, j f1[ j 1] t1, j 1 a2, j

中科大算法导论期末试卷及答案

中科大算法导论期末试卷及答案
2. (卷 1)已知 f1(n)=Θ(g1(n)),f2(n)=Θ(g2(n)),请问是否有 f1(n)+ f2(n)= Θ( max( g1(n),g2(n) ) )?
解:存在������1(n) + ������2(������) = ������(max(������1(������), ������2(������) 证明: ������1(������) = ������(������1(n)) 则存在 a1>0,a2>0, n1>0 使得 n>n1 时有 ������1 ∗ ������1(n) < ������1(������) < ������2 ∗ ������1(n) ������2(������) = ������(������2(n)) 则存在 b1>0,b2>0, n2>0 使得 n>n2 时有 ������1 ∗ ������2(n) < ������2(������) < ������2 ∗ ������2(n) 取 c1=min(a1,b1) >0, c2=2*max(a2,b2) >0, n0=max(n1,n2)>0 当 n>n0 时,有 ������1(n) + ������2(������) > ������1 ∗ ������1(n) + ������1 ∗ ������2(n)
= ������2(������������ − 5 ������������������������) − 2������ > 2������3 − 2������ > 2������0(������02 − 1) =12 即当 c=7, n0=2 时,对 n>n0, 5������2������������������������ + 2������ < ������������3恒成立, 5������2������������������������ + 2������ = ������(������3)

算法导论习题答案 (5)

算法导论习题答案 (5)
c(j) = min {c(i − 1) + linecost(i, j)} .
Three-hole punch your paper on submissions. You will often be called upon to “give an algorithm” to solve a certain problem. Your write-up should take the form of a short essay. A topic paragraph should summarize the problem you are solving and what your results are. The body of the essay should provide the following:
(a) Argue that this problem exhibits optimal substructure.
Solution: First, notice that linecost(i, j) is defined to be � if the words i through j do not fit on a line to guarantee that no lines in the optimal solution overflow. (This relies on the assumption that the length of each word is not more than M .) Second, notice that linecost(i, j) is defined to be 0 when j = n, where n is the total number of words; only the actual last line has zero cost, not the recursive last lines of subprob­ lems, which, since they are not the last line overall, have the same cost formula as any other line.

中科院计算机算法设计与分析各章作业 历年习题.

中科院计算机算法设计与分析各章作业 历年习题.

设在新机器上用 t 秒时间能解决输入规模为 N 的问题,则
由于新复杂度
T新 ( N )

N2
,新机器的运行速度为 t新

t0 64

代入关系式T新(N) *t新 t ,得
N
2
*
t0 64

t

3* 2n
*t0

解得
N 8 3 2n
3)若进一步改进算法,最新的算法的时间复杂度为 T (n) 8 ,其余条件不
1).f (n) O(F(n)), g(n) O(G(n)) f (n) / g(n) O(F(n) / G(n)) ;错 2).f (n) O(F(n)), g(n) O(G(n)) f (n) / g(n) (F(n) / G(n)) ;错 3).f (n) O(F(n)), g(n) O(G(n)) f (n) / g(n) (F(n) / G(n)) ;错 4).f (n) (F(n)), g(n) (G(n)) f (n) / g(n) (F(n) / G(n)) ;错 5).f (n) (F(n)), g(n) (G(n)) f (n) / g(n) (F(n) / G(n)) 。错 6). f (n) (F(n)), g(n) (G(n)) f (n) / g(n) (F(n) / G(n)) 对
for(int i=0; i<m; i++) for(int j=0; j<p; j++){ T sum=0; for(int k=0; k<n; k++) Sum+=a[i][k]*b[k][j]; C[i][j]=sum; }

第四次作业答案

第四次作业答案

1.235。

由于本题求二叉树的结点数最多是多少,第7层共有27-1=64个结点,已知有10个叶子,其余54个结点均为分支结点。

它在第八层上有108个叶子结点。

所以该二叉树的结点数最多可达(27-1+108)=235。

(注意;本题并未明说完全二叉树的高度,但根据题意,只能8层。

)2.1023(=210-1)3.证明:设度为1和2 的结点数是n1和n2,则二叉树结点数n为n=m+n1+n2 (1)由于二叉树根结点没有分枝所指,度为1和2的结点各有1个和2个分枝,度为0 的结点没有分枝,故二叉树的结点数n与分枝数B有如下关系n=B+1=n1+2*n2+1 (2)由(1)和(2),得n2=m-1。

即n个结点的二叉树,若叶子结点数是m,则非叶子结点中有(m-1)个度为2,其余度为1。

4.根据顺序存储的完全二叉树的性质,编号为i的结点的双亲的编号是⎣i/2⎦,故A[i]和A[j]的最近公共祖先可如下求出:while(i/2!=j/2)if(i>j) i=i/2; else j=j/2;退出while后,若i/2=0,则最近公共祖先为根结点,否则最近公共祖先是i/2。

5. 结点个数在20到40的满二叉树且结点数是素数的数是31,其叶子数是16。

6.设分枝结点和叶子结点数分别是为n k和n0,因此有n=n0+n k (1) 另外从树的分枝数B与结点的关系有 n=B+1=K*n k +1 (2)由(1)和(2)有 n0=n-n k=(n(K-1)+1)/K7.(1)设n=1,则e=0+2*1=2(只有一个根结点时,有两个外部结点),公式成立。

设有n个结点时,公式成立,即E n=I n+2n (1)现在要证明,当有n+1个结点时公式成立。

增加一个内部结点,设路径长度为l,则I n+1=I n+l (2)该内部结点,其实是从一个外部结点变来的,即这时相当于也增加了一个外部结点(原外部结点变成内部结点时,增加两个外部结点),则E n+1=E n+l+2 (3)由(1)和(2),则(3)推导为E n+1=I n+2n+l+2=I n+1-l+2n+l+2=I n+1+2(n+1)故命题成立8.前序遍历是“根左右”,中序遍历是“左根右”,后序遍历是“左右根”。

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

中科大算法导论第一,二次和第四次作业答案
第一次作业
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 略

中科大算法导论作业标准标准答案

中科大算法导论作业标准标准答案

第8次作业答案16.1-116.1-2543316.3-416.2-5参考答案:16.4-1证明中要三点:1.有穷非空集合2.遗传性3.交换性第10次作业参考答案16.5-1题目表格:解法1:使用引理16.12性质(2),按wi单调递减顺序逐次将任务添加至Nt(A),每次添加一个元素后,进行计算,{计算方法:Nt(A)中有i个任务时计算N0 (A),…,Ni(A),其中如果存在Nj (A)>j,则表示最近添加地元素是需要放弃地,从集合中删除};最后将未放弃地元素按di递增排序,放弃地任务放在所有未放弃任务后面,放弃任务集合内部排序可随意.解法2:设所有n个时间空位都是空地.然后按罚款地单调递减顺序对各个子任务逐个作贪心选择.在考虑任务j时,如果有一个恰处于或前于dj地时间空位仍空着,则将任务j赋与最近地这样地空位,并填入; 如果不存在这样地空位,表示放弃.答案(a1,a2是放弃地):<a5, a4, a6, a3, a7,a1, a2>or <a5, a4, a6, a3, a7,a2, a1>划线部分按上表di递增地顺序排即可,答案不唯一16.5-2(直接给个计算例子说地不清不楚地请扣分)题目:本题地意思是在O(|A|)时间内确定性质2(性质2:对t=0,1,2,…,n,有Nt(A)<=t,Nt(A)表示A中期限不超过t地任务个数)是否成立.解答示例:思想:建立数组a[n],a[i]表示截至时间为i地任务个数,对0=<i<n,如果出现a[0]+a[1]+…+a[i]>i,则说明A不独立,否则A独立.伪代码:int temp=0;for(i=0;i<n;i++) a[i]=0; ******O(n)=O(|A|)for(i=0;i<n;i++) a[di]++; ******O(n)=O(|A|)for(i=0;i<n;i++) ******O(n)=O(|A|) {temp+=a[i];//temp就是a[0]+a[1]+…+a[i]if(temp>i)//Ni(A)>iA不独立;}17.1-1(这题有歧义,不扣分)a) 如果Stack Operations包括Push Pop MultiPush,答案是可以保持,解释和书上地Push Pop MultiPop差不多.b) 如果是Stack Operations包括Push Pop MultiPush MultiPop,答案就是不可以保持,因为MultiPush,MultiPop交替地话,平均就是O(K).17.1-2本题目只要证明可能性,只要说明一种情况下结论成立即可17.2-1第11次作业参考答案17.3-1题目:答案:备注:最后一句话展开:采用新地势函数后对i 个操作地平摊代价:)1()())1(())(()()(1''^'-Φ-Φ+=--Φ--Φ+=Φ-Φ+=-Di Di c k Di k Di c D D c c i i i i i i17.3-2题目:答案:第一步:此题关键是定义势能函数Φ,不管定义成什么首先要满足两个条件 对所有操作i ,)(Di Φ>=0且)(Di Φ>=)(0D Φ比如令k j+=2i ,j,k 均为整数且取尽可能大,设势能函数)(Di Φ=2k;第二步:求平摊代价,公式是)1()(^-Φ-Φ+=Di Di c c i i 按上面设置地势函数示例:当k=0,^i c =…=2当k !=0,^i c =…=3 显然,平摊代价为O(1)17.3-4题目:答案:结合课本p249,p250页对栈操作地分析很容易有下面结果17.4-3题目:答案:αα=(第i次循环之后地表中地entry 假设第i个操作是TABLE_DELETE, 考虑装载因子:inum size数)/(第i次循环后地表地大小)=/i i第12 次参考答案19.1.1题目:答案:如果x不是根,则degree[sibling[x]]=degree[child[x]]=degree[x]-1如果x是根,则sibling为二项堆中下一个二项树地根,因为二项堆中根链是按根地度数递增排序,因此degree[sibling[x]]>degree[x]19.1.2题目:答案:如果x是p[x]地最左子节点,则p[x]为根地子树由两个相同地二项树合并而成,以x为根地子树就是其中一个二项树,另一个以p[x]为根,所以degree[p[x]]=degree[x]+1;如果x不是p[x]地最左子节点,假设x是p[x]地子节点中自左至右地第i个孩子,则去掉p[x]前i-1个孩子,恰好转换成第一种情况,因而degree[p[x]]=degree[x]+1+(i-1)=degree[x]+i;综上,degree[p[x]]>degree[x]19.2.2题目:题目:19.2.519.2.6第13次作业参考答案20.2-1题目:解答:20.2-3 题目:解答:20.3-1 题目:答案:20.3-2 题目:答案:第14次作业参考答案这一次请大家自己看书处理版权申明本文部分内容,包括文字、图片、以及设计等在网上搜集整理.版权为个人所有This article includes some parts, including text, pictures, and design. Copyright is personal ownership.6ewMy。

算法导论参考 答案

算法导论参考 答案

第二章算法入门由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。

另,思考题2-3 关于霍纳规则,有些部分没有完成,故没把解答写上去,我对其 c 问题有疑问,请有解答方法者提供个意见。

给出的代码目前也仅仅为解决问题,没有做优化,请见谅,等有时间了我再好好修改。

插入排序算法伪代码INSERTION-SORT(A)1 for j ←2 to length[A]2 do key ←A[j]3 Insert A[j] into the sorted sequence A[1..j-1]4 i ←j-15 while i > 0 and A[i] > key6 do A[i+1]←A[i]7 i ←i − 18 A[i+1]←keyC#对揑入排序算法的实现:public static void InsertionSort<T>(T[] Input) where T:IComparable<T>{T key;int i;for (int j = 1; j < Input.Length; j++){key = Input[j];i = j - 1;for (; i >= 0 && Input[i].CompareTo(key)>0;i-- )Input[i + 1] = Input[i];Input[i+1]=key;}}揑入算法的设计使用的是增量(incremental)方法:在排好子数组A[1..j-1]后,将元素A[ j]揑入,形成排好序的子数组A[1..j]这里需要注意的是由于大部分编程语言的数组都是从0开始算起,这个不伪代码认为的数组的数是第1个有所丌同,一般要注意有几个关键值要比伪代码的小1.如果按照大部分计算机编程语言的思路,修改为:INSERTION-SORT(A)1 for j ← 1 to length[A]2 do key ←A[j]3 i ←j-14 while i ≥ 0 and A[i] > key5 do A[i+1]←A[i]6 i ←i − 17 A[i+1]←key循环丌变式(Loop Invariant)是证明算法正确性的一个重要工具。

算法导论参考答案

算法导论参考答案

第二章算法入门由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。

另,思考题2-3 关于霍纳规则,有些部分没有完成,故没把解答写上去,我对其 c 问题有疑问,请有解答方法者提供个意见。

给出的代码目前也仅仅为解决问题,没有做优化,请见谅,等有时间了我再好好修改。

插入排序算法伪代码INSERTION-SORT(A)1 for j ←2 to length[A]2 do key ←A[j]3 Insert A[j] into the sorted sequence A[1..j-1]4 i ←j-15 while i > 0 and A[i] > key6 do A[i+1]←A[i]7 i ←i − 18 A[i+1]←keyC#对揑入排序算法的实现:public static void InsertionSort<T>(T[] Input) where T:IComparable<T>{T key;int i;for (int j = 1; j < Input.Length; j++){key = Input[j];i = j - 1;for (; i >= 0 && Input[i].CompareTo(key)>0;i-- )Input[i + 1] = Input[i];Input[i+1]=key;}}揑入算法的设计使用的是增量(incremental)方法:在排好子数组A[1..j-1]后,将元素A[ j]揑入,形成排好序的子数组A[1..j]这里需要注意的是由于大部分编程语言的数组都是从0开始算起,这个不伪代码认为的数组的数是第1个有所丌同,一般要注意有几个关键值要比伪代码的小1.如果按照大部分计算机编程语言的思路,修改为:INSERTION-SORT(A)1 for j ← 1 to length[A]2 do key ←A[j]3 i ←j-14 while i ≥ 0 and A[i] > key5 do A[i+1]←A[i]6 i ←i − 17 A[i+1]←key循环丌变式(Loop Invariant)是证明算法正确性的一个重要工具。

算法导论作业2答案

算法导论作业2答案

Introduction to Algorithm s Day 10 Massachusetts Institute of Technology 6.046J/18.410J Singapore-MIT Alliance SMA5503 Professors Erik Demaine,Lee Wee Sun,and Charles E.Leiserson Handout12Exercise2-1.Do Exercise5.3-1on page104of CLRS.Solution:R ANDOMIZE-I N-P LACEExchangefor todo ExchangeFor our base case,we have initialized to2.Therefore we must show that for each possible1-permutation,the subarray A[1]contains this1-permutation with probability. Clearly this is the case,as each element has a chance of of being in thefirst position.Exercise2-2.Do Exercise6.1-2on page129of CLRS.Solution:By definition,a element heap has a height of.Therefore where is and our base case is correct.Now we use induction,and assume that all trees with nodes or fewer has a height of. Next we consider a tree with nodes.Looking at the node,we know its height is one greater than its parent(and since we’re not in the base case,all nodes have a parent).The parent of the th node in the tree is also the th node in the tree.Therefore its height is.Then the th node in the tree has a height of. Therefore by induction we have shown that the height of an node tree is.Exercise2-3.Do Exercise6.4-3on page136of CLRS.Solution:The running time of H EAPSORT on an array of length that is already sorted in increasing order is because even though it is already sorted,it will be transformed back into a heap and sorted.The running time of H EAPSORT on an array of length that is sorted in decreasing order will be.This occurs because even though the heap will be built in linear time,every time the element is removed and the H EAPIFY is called it will cover the full height of the tree. Exercise2-4.Do Exercise7.2-2on page153of CLRS.Solution:The running time will be because every time partition is called,all of the elements will be put into the subarray of elements smaller than the partition.The recurrence will bewhich is clearlyExercise2-5.Do Problem7-3on page161of CLRS.Solution:(a)This sort is intuitively correct because the largest rd of the elements will eventually be sorted amung their peers.If they are in thefirst third of the array to begin with,they will be sorted into the middle third.If they are in the middle or last third,then they will obviously be sorted into their proper position.Similarly any element which belongs in the each of the thirds will be sorted into position by the three sub-sorts.(b)Which solves to(c)S TOOGE S ORT is slower than all of the other algorithms we have studied.I NSERTION, M ERGE S ORT,H EAPSORT,and Q UICKSORT.Therefore all other sorts are faster and these professors do not deserve tenure for this work!Problem2-1.Average-case performance of quicksortWe have shown that the expected time of randomized quicksort is,but we have not yet analyzed the average-case performance of ordinary quicksort.We shall prove that,under the assumption that all input permutations are equally likely,not only is the running time of ordinary quicksort,but it performs essentially the same comparisons and exchanges between input elements as randomized quicksort.Consider the implementation of P ARTITION given in lecture on a subarray:P ARTITION123for to4do if5then6exchange7exchange8returnLet be a set of distinct elements which are provided in random order(all orders equally likely) as the input array to P ARTITION,where is the size of the array.Let denote the initial value of.(a)Argue that is a random permutation of,that is,that all permuta-tions of the input subarray are equally likely.Solution:Given that is random(all orders are equally likely),there are possiblepermutations of the elements.Each element has a probabilityof being chosen as the pivot,therefore the number of permutations of the remainingelements is.Consequently the permutations are equallylikely.Define as follows:ififif(b)Consider two input arrays and consisting of the elements of suchthat for all.Suppose that we run P ARTITIONon and and trace the two executions to record the branches taken,indices calculated,and exchanges performed—but not the actual array values ma-nipulated.Argue briefly that the two execution traces are identical.Argue further thatP ARTITION performs the same permutation on both inputs.Solution:P ARTITION takes different branches based only on the comparisons made in thefunction.This is clear by observing line4of the function,as it is the only place wherethe sequence of instructions may differ.As the arrays have identical functionvalues,they must take the same branches,calculate the same indicies and perform thesame exchanges.Consequently P ARTITION will perform the same partition on botharrays,which follows directly as the exchanges performed are identical.Define a sequence to be an input pattern if,for ,and.Define a sequence to be an output pattern ififififWe say that a permutation of satisfies a pattern iffor all.(c)How many input patterns are there?How many output patterns are there?Solution:There are input patterns because we can choose positions out of possible positions to have.There is one()output pattern because the pattern must be exactly negative ones followed by a0,followed byones.(d)How many permutations of satisfy a particular input pattern?How manypermutations of satisfy a particular output pattern?Solution:permutations are possible of to satisfy a particular input pattern.This is the total number of ways to rearrange the elements which have a value ofamongst themselves,and rearrange those with a value of1amongst themselves.Thereare also permutations possible to satisfy a particular output patternfor the same reason.Let be an input pattern,and let be an output pattern.Define to be the set of permutations of that satisfy,and likewise define to be the set of permutations of that satisfy.(e)Argue that P ARTITION implements a bijection from to.(Hint:Use the factfrom group theory that composing afixed permutation with each of the possiblepermutations yields the set of all permutations.)Solution:All members of satisfy and so they all have the same result when the functionis applied to its elements.Therefore by part(b)when all these inputs are given toP ARTITION they are subject to the same ing the hint,we then knowthat after all of the distinct inputs are run through P ARTITION that they will produceall distinct outputs.From part we know that and are thesame size,and also we have proven that P ARTITION is onto,and therefore P ARTITIONmust be a bijection!(f)Suppose that before the call to P ARTITION,the input subarray is a randompermutation of,where.Argue that after P ARTITION,the tworesulting subarrays are random permutations of their respective elements.Solution:Using our solution from part(e),we know that after P ARTITION is run on,we getall values in the set.Therefore we get all permutations of the ones and allpermutations of the negative ones.Furthermore,we get each sub-array permu-tations an equal number of times and so the subarrays are also random permutations.(g)Use induction to show that,under the assumption that all input permutations areequally likely,at each recursive call of Q UICKSORT,every element of be-longing to is equally likely to be the pivot.Solution:The base case for the initial array;we know that it is randomly permuted,and so bypart and each of its subarrays will also be randomly permuted after P ARTITION.Therefore we can inductively apply at each partition to prove that every subarraywill also be randomly permuted.(h)Use the analysis of R ANDOMIZED-Q UICKSORT to conclude that the average-caserunning time of Q UICKSORT on elements is.Solution:By part(g)we know that under the assumption that the input pattern is random everyelement is equally likely to be chosen as the pivot at each recursive call which then pro-duces the same random distribution of quicksort traces as R ANDOMIZED-Q UICKSORT.Therefore as their distribution is the same,the expected-case analysis for R ANDOMIZED-Q UICKSORT will apply to the average case of Q UICKSORT.Therefore the average case of Q UICKSORTalso takes time.Problem2-2.Analysis of-ary heapsA-ary heap is like a binary heap,but(with one possible exception)nonleaf nodes have children instead of2children.(a)How would you represent a-ary heap in an array?Solution:The-ary heap would be similar to a binary heap with the parent and child indexescalculated as follows:th-Child[]whereThe root of the tree would be at index.Alternate Solution:A-ary heap can be represented in a-dimensional array asfollows.The root is kept in,its children are kept in order in through,their children are kept in order in through,and so on.The two procedures that map a node with index to its parent and to its th child(for),respectively,are;D-ARY-P ARENTreturnD-ARY-C HILDreturnTo convince yourself that these procedures really work,verify thatD-ARY-P ARENT D-ARY-C HILDfor any.Notice that the binary heap procedures are a special case of the above procedures when.(b)What is the height of a-ary heap of elements in terms of and?Solution:CORRECTIONA-ary heap would have a height of.We know thatwhich solves to.(c)Give an efficient implementation of E XTRACT-M AX in a-ary max-heap.Analyze itsrunning time in terms of and.Solution:H EAPIFY12for to3if and4then5if6then7Exchange8H EAPIFYThe running time of H EAPIFY is because at each depth we are doing loops,and we recurse to the depth of the tree.In H EAPIFY we compare the the th node and each of its children tofind the maximum value for all of the nodes.Then ifthe maximum child is greater than the th node,we switch the two nodes and recurse on the child.E XTRACT-M AX(A,n)1234H EAPIFY(A,1,n,d)5returnThe running time of this algorithm,is clearly constant work plus the time of H EAPIFY which as shown above is.E XTRACT-M AX works by storing the value of the maximum element,moving the minimum element into the root of the heap,and then calling heapify to restore the heap property.(d)Give an efficient implementation of I NSERT in a-ary max-heap.Analyze its runningtime in terms of and.Solution:See next problem part for I NCREASE-K EY definition.I NSERT123I NCREASE-K EYFrom the following problem part,we know I NCREASE-K EY runs in time, therefore since I NSERT only adds constant time operations it is also.It is rather trivially correct as the algorithm has not changed because all calculations involving the number of children are performed by I NCREASE K EY.(e)Give an efficient implementation of I NCREASE-K EY,whichfirst setsand then updates the-ary max-heap structure appropriately.Analyze its running time in terms of and.Solution:I NCREASE-K EY12if3while and 6。

算法导论第二次作业答案

算法导论第二次作业答案

Solution: First, let’s analyze the Activity Selection Problem again: This is a problem using greedy algorithm: Input: 1. n activities a1, a2, . . . , an; 2. for i = 1, 2, . . . , n, the activity ai has a start time si and a finish time fi: [si, fi) Output: Pick a maximum set of activities that are compatible in time.
Solution: First, let’s analyze the Huffman Code again:
This is a problem using greedy algorithm:
Input: 1. n symbols s1, s2, . . . , sn ; 2. every symbol si has a frequency fi
Assume the time period of each activity is shown as following table:
i
123
si
157
fi
469
duration 3 1 2
We will choose the a2 which has the least duration among all three activities. However, it is obvious that the best arrangement is to choose {a1, a3}. So the approach of selecting the activity of least duration from among those that are compatible with previously selected activities does not work.

算法导论习题答案 (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.。

算法导论 答案

算法导论 答案

算法导论答案算法导论是计算机科学领域中一门重要的课程,其目的是介绍和探讨算法的基本原理和设计方法。

本文将从几个不同角度来讨论算法导论的主题,包括算法的定义、算法分析、算法设计等,并提供一些常见的算法应用示例。

一、算法的定义与特点算法是一个用于完成特定任务的有限一系列指令或规则的集合。

算法的设计应具备以下几个特点:确定性、有穷性、可行性和输入/输出。

1. 确定性:对于给定的输入,算法的每个步骤都必须是明确且唯一的。

不同的输入应得到不同的输出。

2. 有穷性:算法必须经过有限的步骤后能终止。

这是因为计算机程序需要在有限时间内完成,而无限循环的算法则无法给出结果。

3. 可行性:算法的每个步骤都应该是可行执行的,即能够在可接受的时间内完成。

4. 输入/输出:算法应该具有输入和输出,即根据给定的输入,通过算法能够得到相应的输出。

二、算法的分析与效率评估算法的分析与效率评估是算法导论的重要内容。

在设计和选择算法时,需要考虑到其执行时间和内存需求等方面。

1. 时间复杂度:用于衡量算法所需执行的时间。

常见的时间复杂度表示方法有大O记法,例如O(n)、O(nlogn)等。

时间复杂度越低,算法执行效率越高。

2. 空间复杂度:用于衡量算法所需的内存空间。

空间复杂度的衡量单位通常是字节或比特。

与时间复杂度一样,空间复杂度越低,算法的内存需求越小。

三、算法的设计方法算法设计是算法导论的核心内容之一,主要包括贪心算法、分治算法、动态规划算法等。

1. 贪心算法:贪心算法是一种基于每一步局部最优解的策略来解决问题的算法。

它常应用于问题的最优解为局部最优解的情况,但不一定能得到全局最优解。

2. 分治算法:分治算法是一种将问题划分为多个相互独立的子问题,再合并子问题的解来得到整体解的算法。

适合解决规模较大且问题可被划分的情况。

3. 动态规划算法:动态规划算法是一种将复杂问题拆分为更小、更简单的子问题来解决的算法。

它利用了子问题的重叠性质,将子问题的解保存起来,避免了重复计算。

算法导论作业1答案

算法导论作业1答案

Introduction to Algorithm s Day 10 Massachusetts Institute of Technology 6.046J/18.410J Singapore-MIT Alliance SMA5503 Professors Erik Demaine,Lee Wee Sun,and Charles E.Leiserson Handout11Exercise1-1.Do Exercise2.3-5on page37in CLRS.Solution:Procedure B INARY-S EARCH takes a sorted array,a value,and a range low high of the array, in which the value should be searched for.The procedure compares to the midpoint of the range and decides to eliminate half the range from further consideration.Both iterative and recursive versions are given.These versions should be initially called with the range length.I TERATIVE-B INARY-S EARCH low high1while low high2do mid low high3if mid4then return mid5if mid6then low mid7else high mid8return NILR ECURSIVE-B INARY-S EARCH low high1if low high2then return NIL3mid low high4if mid5then return mid6if mid7then return R ECURSIVE-B INARY-S EARCH mid high8else return R ECURSIVE-B INARY-S EARCH low midBoth procedures terminate the search unsuccessfully when the range is empty(i.e.,low high) and terminate successfully if the value has been found.Based on the comparison of to the middle element in the searched range,the search continues with the range halved.The recurrence for these procedures is therefore,whose solution is.Exercise1-2.Do Exercise2.3-7on page37in CLRS.Solution:The following algorithm solves the problem:1.Sort the elements in using mergesort.2.Remove the last element from.Let be the value of the removed element.3.If is nonempty,look for in using binary search.4.If contains such an element,then STOP,since we have found and such that.Otherwise,repeat Step2.5.If is empty,then no two elements in sum to.Notice that when we consider an element of during th iteration,we don’t need to look at the elements that have already been considered in previous iterations.Suppose there exists, such that.If,i.e.if has been reached prior to,then we would have found when we were searching for during th iteration and the algorithm would have terminated then.Step1takes time.Step2takes time.Step3requires at most time.Steps2–4 are repeated at most times.Thus,the total running time of this algorithm is.We can do a more precise analysis if we notice that Step3actually requires time at th iteration. However,if we evaluate,we get,which is.So the total running time is still.Exercise1-3.Do Exercise3.1-1on page50in CLRS.Solution:By the definition of-notation(CLRS p.42)we must show that there exist positive constants, ,and such that for,Without loss of generality,let max(.Clearly,.Also, since,.Thus,selecting and and satisfies the definition.Exercise1-4.Do Exercise4.1-6on page67in CLRS.Solution:Let or,equivalently,.The recurrence becomesWe will need one more substitution:Let.The recurrence then becomes:By the master method,.Equivalently,in terms of we have. Going back to(),we getExercise1-5.Rank the following functions by order of growth;that is,find an arrangement of the functions satisfying,,...,.Parti-tion your list into equivalence classes such that and are in the same class if and only if .)5.6.Finally Stirling’s approximation bounds are useful in ranking expression with factorials:So here’s the ranking(listed from left to right by row)The oscillating function does notfit in the ranking because although and ,it is not-related to.The equivalence classes determined by the relationship are:1.Problem1-1.Asymptotic notation for multivariate functionsThe generalization of asymptotic notation from one variable to multiple variables is surprisingly tricky.One proper generalization of-notation for two variables is the following: Definition1there exist positive constants,,and such thatfor all orConsider the following alternative definition:Definition2there exist positive constants,,and such thatfor all and(a)Explain why Definition2is a“bogus”definition.That is,what anomalies does thedefinition of permit that are counterintuitive?You mayfind it helpful to illustrateyour answer with a diagram of relevant regions of the plane.Solution:The distinction between these two interpretations can best be illustrated with a di-agram of the space parameterized by and;see Figure1.The definition ofrequires that the inequality hold in the shaded rectangle in Figure1(a),defined by and,leaving the strips and uncovered.In contrast, the definition of requires in addition that the inequality hold for sufficiently largevalues in those strips,i.e.,for the shaded region in Figure1(b).Ideally,we would alsohope for the inequality to hold for all values of and,as in Figure1(c);we call thisthe unrestricted interpretation.(a)and(b)or(c)UnrestrictedFigure1:Three candidate regions in which a statement about a two-variable function should hold.The definition of is bogus because it allows to be outsidefor infinitely many pairs of values.Recall that for univariate functions,anequivalent interpretation of what means is the following:there existsa constant such that for all butfinitely many1values of.We shouldthus expect the definition of notation in multivariate functions to allow for onlyfinitely many points(tuples)to be outside the stated range.1or equivalently,“for infinitely many values of”Definition3A two-variable function is monotonically increasingifandfor all nonnegative and.(b)Explain this definition in plain English.Solution:A function is monotonically increasing if whenever either(or both)of thefunction’s arguments increase,the function’s value either increases or remains con-stant,but never decreases.ii...However,this is true only if we assume that and,iii...v...vi...(d)Prove that the following two functions are not multiplicatively separable:i.ii.Solution:i.Proof by contradiction:Suppose the function was multiplicatively separable.Then we would have:And so would not be bounded in terms of the argument itself,independent of the other argumentIndeed,in this case,would not necessarily hold under the“or”interpretation if it holds under the“and”interpretation.For example, consider the functionforforforLet.Then holds whenever and but is not necessarily true under the“or”definition.ii.Similarly,2notice thatforforwith.Then holds whenever and but is not necessarily true under the“or”definition.(The’s are necessary to deal with the possibility that takes on values less than.)Thus,suffices in this case.(g)Conclude that.Solution:Let.By parts(a)and(b),for all and,Therefore,holds under the unrestricted interpretation and thusin particular the‘or’definition.(h)(Extra credit.)Give a proper generalization of to two variables.Justify your defini-tion.Solution:Awaiting ideas from students...Problem1-2.Tree TraversalThe following pseudocode is a standard recursive tree-traversal algorithm for counting the number of nodes in a tree.The initial call is C OUNT-N ODES.C OUNT-N ODES1if NIL2then return3else return C OUNT-N ODES leftC OUNT-N ODES rightDefine size to be the number of nodes in the subtree rooted at node,and let denote the worst-case running time of C OUNT-N ODES.(a)Give a recurrence for in terms of left and right.Solution:left right(b)Use the substitution method to prove that size.Solution:For convenience,let denote,that is,the size of the tree whose root is node .In order to prove that,we need to show that there exists a constant such that.Proof.Let be an upper bound on the term3.Assume that there exists some constant such that:for all trees with,.That is,we assume that the statement holds for all trees whose size is less than.We want to prove that.From part(a),we have:left right.Since right and left are smaller than,we haveleft rightleft rightleft right3notice that the term does not depend on the size of the treeConsider the loop invariantC OUNT-N ODES-T AIL left right(1) where is the number of times the while loop(lines2–4)in C OUNT-N ODES-T AIL has been executed.(c)Prove that if Equation(1)holds for,then it holds for.Solution:Let be the new value of after one more execution of the loop.Since afterexecutions we haveC OUNT-N ODES-T AIL left rightat the end of the-st execution we will haveC OUNT-N ODES-T AIL left rightC OUNT-N ODES-T AIL left right C OUNT-N ODES-T AIL left rightC OUNT-N ODES-T AIL left rightSo it holds forC OUNT-N ODES-T AIL left rightHowever,we need to prove that Equation(1)holds.Proof.Base Case:Consider a tree of size1.The loop will execute only once and at the end of the loop,as predicted by Equation(1).So the base case holds.Inductive step:The inductive step was taken care of in part(c).(e)Prove by induction that C OUNT-N ODES-T AIL correctly computes size.Solution:Base case:tree of size.As shown above,the algorithm returns,which is the right answer.Inductive step:assume that the algorithm returns the right result for all trees up to.We want to prove that it will return the right result for any tree ofas well.Consider a tree.As shown in part(d),the algorithm returnsC OUNT-N ODES-T AIL left rightSince all left subtrees have size at most,we know thatC OUNT-N ODES-T AIL left rightcorrectly counts the number of leaves of all the left subtrees.Since the tree consists of right-most nodes plus all their left subtrees,thealgorithm returns the right result for trees of as well.Problem1-3.Polynomial multiplicationIf we have two linear polynomials and,we can multiply them using the four coefficient multiplicationsto form the polynomial(a)Give a divide-and-conquer algorithm for multiplying two polynomials of degree-boundbased on this formula.Solution:We can use this idea to recursively multiply polynomials of degree,where isa power of2,as follows:Let and be polynomials of degree,and divide each into the upperand lower terms:where,,,and are polynomials of degree.The polynomial product is thenThe four polynomial products,,,and 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,re-cursive polynomial multiplication gives us a running time of(c)Show how to multiply two linear polynomials and using only threecoefficient multiplications.Solution:We can use the following3multiplications:so the polynomial product is(d)Give a divide-and-conquer algorithm for multiplying two polynomials of degree-boundbased 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 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):Alternative solution Instead of breaking a polynomial into two smaller poly-nomials and such that,as we did above,we could do the following:Collect all the even powers of and substitute to create the polynomial .Then collect all the odd powers of,factor out and substitute to create the second polynomial.Then we can see thatBoth and 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,we need to compute(where),which takes time per level and does not affect the asymptotic running time.。

算法导论答案(经典)

算法导论答案(经典)

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
16.3-1 16.3-2Leabharlann 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
24.1-3
24.1-4 24.1-5* 24.1-6 修改 Bellman-Ford 算法,先找到负环上的一个节点,再依次找到负环上的一个节点,再依 次找到负环上的其他节点。 24.2-1 见图 24-5 24.2-2 最后一次不影响结果
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 章
25.1-4 25.1-5
25.1-6 25.1-7 25.1-8
25.1-9 25.1-10 25.2-1 见图 25-4 25.2-2 25.2-3 25.2-4

算法导论中文版答案

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

15.
else do A[k]=R[j]
16.
j++
17.
k++
18. while(i<=n1) 19. do A[k++]=L[i++]
6. for j ←1 to n2 7. do R[j] ←A[q+j]
20. while(j<=n2) 21. do A[k++]=R[j++]
8. i ←1
9. j ←1
个递归的解也是Ω(nlgn)。得到解为Θ(nlgn)。
证明:假设当n 1时,T(n) 1是唯一的边界条件, T (n) cn lg n c 1 lg1 0,假设T(n) cn lg n对n / 2成立
T (n) 2T (n / 2) n 2cn / 2lg(n / 2) n
cn lg(n / 2) n cn lg n - (c 1)n cn lg n(当c 1时) 所以,T (n) O(n lg n),下面证T (n) (n lg n)
2
2
22
c n 1 lg( n 1) c n lg( n ) (n)
2
2
22
c n 1 lg(n 1) c n 1 c n lg(n) c n lg 2 (n)
2
2
2
2
cn lg(n 1) c lg(n 1) c n lg(n) c (2n 1) (n)
2
2
2
2
cn lg n c n(lg(n 1) lg n) c lg(n 1) c (2n 1) (n)
再证(n lg n),即要证T (n) cn lg n
设T (n / 2) c(n / 2) lg(n / 2)成立,
则T (n) T (n / 2) T (n / 2) (n)
c(n
/
2)
lg(n
/
2)
c(n
/
2)
lg(n
/
2)
(n)
c
n 2
lg(
n) 2
c
n
2
1
lg(=0,1,...n-1区间上,当q=0或q=n-1时,q2+(n-q-1)2取得最 大值。
• 求导,取极值。 • 或者进行变换
8.2-4在O(1)的时间内,回答出输入的整数中有多少个落在区 间[a...b]内。给出的算法的预处理时间为O(n+k)
• 利用计数排序,由于在计数排序中有一个存储数值个数的临时存储区 C[0...k],利用这个数组即可
则T (n) T (n / 2) T (n / 2) (n) c(n / 2) lg(n / 2) c(n / 2) lg(n / 2) (
c n 1 lg( n 1) c n lg( n ) (n)
2
2
22
c n 1 lg( n 1) c n lg( n ) (n) cn lg n
第二次作业
• 3.2-3 证明等式lg(n!)=Θ(nlgn)。并证明等式n!=ω(2n)和
n!=o(nn)。
证明:由于(
n
)
n 2
n! nn , 两边取对数可知:lg(n!) (n lg n)
2
3.2-4函数⌈lgn⌉! 是否多项式有界?函数⌈lglgn⌉! 呢
• 4.1-2 证明T (n) 2T (n / 2 n的解为O(n lg n). 证明这
c n lg( n ) c n 1 lg( n 1) (n)
22
2
2
c n lg n c n lg 2 c n 1 lg(n 1) c n 1 lg 2 (n)
2
2
2
2
c n lg n c (2n 1) c n lg(n 1) c lg(n 1) (n)
2
2
2
2
cn lg n c n lg n c n lg(n 1) c (2n 1) c lg(n 1) (n) 0
c n lg(n) c n 1lg(n 1) (n) cn lg n
22
2
2
c n lg(n) c n 1lg(n 1) (n) cn lg n 0
22
2
2
c n lg(1 1) c lg(n 1) 2n 1c (n) 0
2 n2
2
lg(1 1)是递增函数,取n 2,有lg(1 1) 1
或者修改PARTITION(A, p, r),增加对A[i]==x时的处理。对于A[i]==x的数据, 一半放在x左边,一半放在x右边 通过设置一个flag 初始为1 当flag>0时 才进行交换 交换flag=-flag
int Partition(int A[], int p, int r)
{ int x = A[r],i=p-1; int flag = 1; for (int j = p;j< r-1;j++) { if (x >=A[i]&&flag>0)//x=A[i]时,flag大于0和小于0的数量约为一半, { swap(A[i],A[j]); } if (x ==A[i]) { flag=-flag;//这样就能让i++次数减半。 } } swap(A[i + 1],A[r]); return i + 1
取c 1/ 3,n 2时,有T (n) cn lg n,T (n) (n lg n)
所以T (n) (n lg n).
• 4.1-4证明合并排序算法的“准确”递归式(4.2)的解为
Θ(nlgn)
(1)
如果n 1
T (n) T (n / 2) T (n / 2) (n) 如果n 1
n
n
c n lg(1 1) c lg(n 1) 2n 1c (n) (n) c lg(n 1) 3n 1c
2 n2
2
2
2
c (n 1 lg(n 1)) ((1) 2c)n 2
取n 3,有n 1 lg(n 1) 0,取c 1 (1),有((1) 2c) 0 2
c n lg(n) c n 1lg(n 1) (n) cn lg n
• [a..b]区间整数个数为C[b]-C[a-1]
• 题目已经提示运用桶排序,主要是正确设置桶
• 点均匀分布,则每个桶的尺寸应相等,即每个桶在圆中所占据的面积相等。 把圆分为n个部分,第一个部分是以原点为圆心的圆,其他部分是以原点为圆 心的圆环。
第一次作业
2.2-3 再次考虑线性查找问题 (见练习2.1-3)。在平均情况 下,需要检查输入序列中的多 少个元素?假定待查找的元素 是数组中任何一个元素的可能 性是相等的。在最坏情况下有 怎样呢?用Θ形式表示的话,线 性查找的平均情况和最坏情况 运行时间怎样?对你的答案加
以说明。
• 线性查找问题
• 输入:一列数A=<a1,a2,…,an>和一 个值v。
2
2
2
lg(n 1) lg n lg(1 1 )是递增函数,取n 1,有lg(1 1 ) 1
n
n
则有T (n) cn lg n c n c lg(n 1) 2n 1 c (n)
22
2
cn lg n c (lg(n 1) n 1) n (4(1) c)
2
2
4
取n 3,有lg(n 1) n 1 0, 取c 4(1),有4(1) c 0 2
2
n2
2
2
2
c (2 lg(n 1) n 2) n (4(1) c)
4
4
取n 3,有2 lg(n 1) n 2 0, 取c 4(1),有4(1) c 0
c n 1 lg( n 1) c n lg( n ) (n) cn lg n
2
2
22
即T (n) cn lg n
2
2
2
2
cn lg n c n(lg(n 1) lg n) c (2n 1) c lg(n 1) (n)
2
2
2
lg(n 1) lg n lg(1 1 )是递增函数,取n 2, 有 lg(1 1 ) 1
n
n
T (n) cn lg n c (3n 1) c lg(n 1) (n)
}
• 7.2-3 证明:当数组A包含不同的元素、且按降序排序时, QUICKSORT的运行时间为Θ(n2)。
• 证明:数组元素各不相同,且按降序排列时,每次递归调 用都会产生一个元素数目为n-1的分块和一个1的分块。 故有T(n)=T(n-1)+Θ(n) 有T(n)=T(n-1)+cn+d =T(n-2)+cn+c(n-1)+2d =T(n-3)+cn+c(n-1)+c(n-2)+3d =... =T(1)+cn+c(n-1)+c(n-2)+...+c(1)+nd =T(1)+cn(n+1)/2+nd =Θ(n2)
2
2
cn lg n 1 (1 c)n c lg(n 1) c 0 n
lg(n 1) lg(1 1)是递增函数,取n 2,则lg(n 1) 1
n
n
n
cn lg n 1 (1 c)n c lg(n 1) c (1 2c)n c lg(n 1) c n
取c 1/ 3,则(1 2c)n c lg(n 1) c c[n lg(n 1) 1] 0
用哨兵元素,而是在一旦数组L或R 中的所有元素都被复制回数组A后,
11. 12.
while((i<=n1) and (j<=n2)) do if L[i]<=R[j]
相关文档
最新文档