算法导论 第三版 第五章 答案 英
《计算机算法基础》第三版,课后习题答案
i的非降次序输入时,重复②的讨论。
解:
①按照p
i/w
i的非增序可得
(p
5/w
5,p
1/w
1,p
6/w
6,p
3/w
3,p
7/w
7,p
2/w
2,p
4/w
4)= (6,5,9/2,3,3,5/3,1)
W的次序为(1,2,4,5,1,3,7),解为(1,1,1,1,1,2/3,0)
所以最优解为:
k=I
k+2k,考察原树的外部路径长度为E
k+1= E
k-(h-1)+2h,内部路径长度为I
k+1=I
k+(h-1),所以E
k+1= I
k+2k+h+1= I
k+1+2k+2= I
k+1+2(k+1),综合①②③知命题成立。
4.10过程MERGESORT的最坏情况时间是O(nlogn),它的最好情况时间是什么?能说归并分类的时间是Θ(nlogn)吗?
i的非增次序考虑这些物品,只要正被考虑的物品能装进的就将其装入背包。证明这种策略不一定能得到最优解。
证明:
当按照p
i/w
i的非增次序考虑物品存放背包时,如果所装入的物品恰能装满背包时,易证为最优解,否则未必是最优解。
可举例如下:
设n=3,M=6,(p
1,p
2,p
3)=(3,4,8),(w
1,w
2,w
=(A
11+A
22)(B
11+B
22)+A
11(B
12+B
算法导论习题答案 (5)
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.
算法导论 第五章 概率分析和随机算法
算法导论 第三版 第七章 答案 英
Exercise 7.2-4
Let’s say that by “almost sorted” we mean that A[i] is at most c positions from its correct place in the sorted array, for some constant c. For INSERTIONSORT, we run the inner-while loop at most c times before we find where to insert A[j] for any particular iteration of the outer for loop. Thus the running time time is O(cn) = O(n), since c is fixed in advance. Now suppose we run QUICKSORT. The split of PARTITION will be at best n − c to c, which leads to O(n2) running time.
Chapter 7
Michelle Bodnar, Andrew Lohr
April 12, 2016
Exercise 7.1-1
13 19 9 5 12 8 7 4 21 2 6 11 13 19 9 5 12 8 7 4 21 2 6 11 13 19 9 5 12 8 7 4 21 2 6 11 9 19 13 5 12 8 7 4 21 2 6 11 9 5 13 19 12 8 7 4 21 2 6 11 9 5 13 19 12 8 7 4 21 2 6 11 9 5 8 19 12 13 7 4 21 2 6 11 9 5 8 7 12 13 19 4 21 2 6 11 9 5 8 7 4 13 19 12 21 2 6 11 9 5 8 7 4 13 19 12 21 2 6 11 9 5 8 7 4 2 19 12 21 13 6 11 9 5 8 7 4 2 6 12 21 13 19 11 9 5 8 7 4 2 6 11 21 13 19 12 Exercise 7.1-2
算法导论作业5答案概要
6 Problem 5-2. Join operation on red-black trees Handout 22: Problem Set 5 The join operation takes two dynamic� sets �� and �� and an element � such that for any ��������� and ������� , we have key ������� key ����� key ����� . It returns a set ���������������� . In this problem, we investigate how to implement the join operation on red-black trees. (a Given a red-black tree � , we store its black-height as the field bh ��. Argue that this field can be maintained by RB-I NSERT and RB-D ELETE (as given in the textbook, on pages 280 and 288 respectively without requiring extra storage in the nodes of the tree and without increasing the asymptotic running times. Show that while descending through � , we can determine the black-height of each node we visit in ������� time per node visited. Solution: Starting at the root, we can proceed to a leaf, couting the number of black nodes on the path. This does not require any extra storage in the nodes of the tree and will take ����������� time. Since RB-I NSERT and RB-D ELETE also run in����������� time, the asymptotic running time is not increased. While descending through � , we decrement bh �� by � 1 everytime we encounter a blacknode. The black-height of a node, � , is then bh �� minus the number of black nodes encountered (excluding node � itself. This decrement can be done in ������� time per node visited. We wish to implement the operation RB-J OIN ������������� , which may destroy �� and �� and returns a red-black tree ���������������� . Let � be the total number of nodes in �� and �� . (b Assume that bh ������ bh ���� . Describe an ����������� -time algorithm that finds a black � node ����� in � with the largest key from among those nodes whose black-height is bh � . Solution: Since �� is a binary search tree, the largest element at any level is on the rightmost path. So, we decend down the rightmost path, calculating bh at each node (as described ���� in the previous part, until we reach the black node whose black-height is bh � , which is what we want. Thus the running time is at most the height of the tree, i.e. ����������� . (Calculating the black-height takes ������� per node, as shown in the previous part. ���� (c Let ��� be the subtree rooted at � . Describe how �������������� can replace ��� in ������� time without destroying the binary-search-tree property. Solution:Handout 22: Problem Set 5 Insert � into where � was in �� . Form �������������� by letting ��� be the left subtree� of � , and ��� be the right subtree of � . Given that this join operation is such that � key ������� key����� key ����� where ������� and ������� , the binary search tree property is maintained and this operation takes ������� time. Consider the following red-black properties: 7 � every node is either red or black � every leaf is black nodes (d What color should we make � so that the above red-black properties are maintained? Solution: We should make � red. Since ��� already has black-height = bh ������� , � must be red to �������������� = bh �������maintain the same black-height, bh ��� Consider the following red-black properties: �for each node, all paths from the node to descendant leaves contain the same number of black � the root is black � if a node is red, then both its children are black (e Describe how the above two properties can be enforced in ����������� time. Solution:Use RB-I NSERT-F IXUP on the new tree, to perform the recoloring and rotations nec-essary to enforce these two properties. We know that RB-I NSERT-F IXUP runs in����������� time, thus we conclude that the enforcement can be done in����������� time. (f Argue that the running time of RB-J OIN is����������� . Solution: RB-J OIN is implemented by using all the previous parts: The black-height can be calculated and maintained in ������� time. The required black node, � , can be found in ����������� time. Then, the join is done in�����������time, and finally, after assigning � the right color, the red-black tree properties can be enforced in ����������� time. So the total runing time is �����������。
算法导论课程作业答案
算法导论课程作业答案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。
编译原理第三版课后习题答案解析
目录P36-6 (2)P36-7 (2)P36-8 (2)P36-9 (3)P36-10 (3)P36-11 (3)P64–7 (4)P64–8 (5)P64–12 (5)P64–14 (7)P81–1 (8)P81–2 (9)P81–3 (12)P133–1 (12)P133–2 (12)P133–3 (14)P134–5 (15)P164–5 (19)P164–7 (19)P217–1 (19)P217–3 (20)P218–4 (20)P218–5 (21)P218–6 (22)P218–7 (22)P219–12 (22)P270–9 (24)P36-6(1)L G ()1是0~9组成的数字串(2)最左推导:N ND NDD NDDD DDDD DDD DD D N ND DD D N ND NDD DDD DD D ⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒0010120127334556568最右推导:N ND N ND N ND N D N ND N D N ND N ND N D ⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒⇒77272712712701274434886868568P36-7G(S)O N O D N S O AO A AD N→→→→→1357924680|||||||||||P36-8文法:E T E T E T TF T F T F F E i→+-→→|||*|/()| 最左推导:E E T T TF T i T i T F i F F i i F i i i E T T F F F i F i E i E T i T T i F T i i T i i F i i i ⇒+⇒+⇒+⇒+⇒+⇒+⇒+⇒+⇒⇒⇒⇒⇒⇒+⇒+⇒+⇒+⇒+⇒+********()*()*()*()*()*()*()最右推导:E E T E TF E T i E F i E i i T i i F i i i i i E T F T F F F E F E T F E F F E i F T i F F i F i i i i i ⇒+⇒+⇒+⇒+⇒+⇒+⇒+⇒+⇒⇒⇒⇒⇒+⇒+⇒+⇒+⇒+⇒+⇒+**********()*()*()*()*()*()*()*()语法树:/********************************EE FTE +T F F T +iiiEEFTE-T F F T -iiiE EFT+T F FTiii*i+i+ii-i-ii+i*i*****************/P36-9句子iiiei 有两个语法树:S iSeS iSei iiSei iiiei S iS iiSeS iiSei iiiei ⇒⇒⇒⇒⇒⇒⇒⇒P36-10/**************)(|)(|S T TTS S →→***************/P36-11/*************** L1:ε||cC C ab aAb A AC S →→→ L2:bcbBc B aA A AB S ||→→→εL3:εε||aBb B aAb A AB S →→→ L4:AB B A A B A S |01|10|→→→ε ***************/第三章习题参考答案P64–7(1)101101(|)*1 ε ε 1 0 11 确定化:0 1 {X} φ {1,2,3} φ φ φ {1,2,3} {2,3} {2,3,4} {2,3} {2,3} {2,3,4} {2,3,4} {2,3,5} {2,3,4} {2,3,5} {2,3} {2,3,4,Y} {2,3,4,Y}{2,3,5}{2,3,4,}1 00 0 1 1 00 1 0 1 1 1 最小化:X 1 2 3 4 Y5 X Y60 12 35 4{,,,,,},{}{,,,,,}{,,}{,,,,,}{,,,}{,,,,},{},{}{,,,,}{,,}{,,,},{},{},{}{,,,}{,012345601234513501234512460123456012341350123456012310100==== 3012312401234560110112233234012345610101}{,,,}{,,}{,},{,}{},{},{}{,}{}{,}{,}{,}{}{,}{}{},{},{,},{},{},{}===== 010 0 1 00 1 0 1 1 1P64–8(1)01)0|1(*(2))5|0(|)5|0()9|8|7|6|5|4|3|2|1|0)(9|8|7|6|5|4|3|2|1(*(3)******)110|0(01|)110|0(10P64–12(a)aa,b a确定化:a b {0} {0,1} {1} {0,1} {0,1} {1} {1}{0}φ5 01 2 4 3 01φφ φ给状态编号:a b 0 1 2 1 1 2 2 0 3 333aaa b b bba最小化:{,},{,}{,}{}{,}{}{,}{,}{,}{}{,},{},{}012301101223032330123a ba b ====a ab bab (b)b b aa b aa bb aa a已经确定化了,进行最小化0 1 2 3 01 2 02 3 14 5最小化:{{,}, {,,,}}012345011012423451305234523452410243535353524012435011012424{,}{}{,}{,}{,,,}{,,,}{,,,}{,,,}{,}{,}{,}{,}{,}{,}{,}{,}{{,},{,},{,}}{,}{}{,}{,}{,}a b a b a b a b a b a =============={,}{,}{,}{,}{,}{,}{,}10243535353524 b a bb b aa baP64–14(1) 01 0 (2):(|)*0100 1 ε ε确定化:0 1 {X,1,Y}{1,Y}{2}1 2 01YX YX 2 1{1,Y} {1,Y} {2} {2} {1,Y} φ φφ φ 给状态编号:0 1 0 1 2 1 1 2 2 1 3 3330 1 01 1 10 最小化:{,},{,}{,}{}{,}{}{,}{,}{,}{}{,},{},{}0123011012231323301230101====1 1 1 0第四章P81–1(1) 按照T,S 的顺序消除左递归ε|,)(||^)(T S T TS T T a S S G '→''→→' 递归子程序: procedure S; beginif sym='a' or sym='^' then abvance else if sym='('0 2 13 01 3then begin advance;T;if sym=')' then advance; else error; end else error end;procedure T; begin S;'T end;procedure 'T ; beginif sym=',' then begin advance; S;'T end end; 其中:sym:是输入串指针IP 所指的符号 advance:是把IP 调至下一个输入符号 error:是出错诊察程序 (2)FIRST(S)={a,^,(} FIRST(T)={a,^,(} FIRST('T )={,,ε} FOLLOW(S)={),,,#} FOLLOW(T)={)} FOLLOW('T )={)} 预测分析表a^() , # S S a →S →^S T →()TT ST →' T ST →' T ST →''T'→T ε '→'T ST ,是LL(1)文法P81–2文法:|^||)(|*||b a E P F F F P F T T T F T E E E T E →'→''→→''→+→''→εεε(1)FIRST(E)={(,a,b,^} FIRST(E')={+,ε} FIRST(T)={(,a,b,^} FIRST(T')={(,a,b,^,ε} FIRST(F)={(,a,b,^} FIRST(F')={*,ε} FIRST(P)={(,a,b,^} FOLLOW(E)={#,)} FOLLOW(E')={#,)} FOLLOW(T)={+,),#} FOLLOW(T')={+,),#}FOLLOW(F)={(,a,b,^,+,),#} FOLLOW(F')={(,a,b,^,+,),#} FOLLOW(P)={*,(,a,b,^,+,),#} (2)考虑下列产生式:'→+'→'→'→E E T T F F P E a b ||*|()|^||εεεFIRST(+E)∩FIRST(ε)={+}∩{ε}=φ FIRST(+E)∩FOLLOW(E')={+}∩{#,)}=φ FIRST(T)∩FIRST(ε)={(,a,b,^}∩{ε}=φ FIRST(T)∩FOLLOW(T')={(,a,b,^}∩{+,),#}=φ FIRST(*F')∩FIRST(ε)={*}∩{ε}=φFIRST(*F')∩FOLLOW(F')={*}∩{(,a,b,^,+,),#}=φ FIRST((E))∩FIRST(a) ∩FIRST(b) ∩FIRST(^)=φ 所以,该文法式LL(1)文法. (3)+ * ()ab^#EE TE →' E TE →' E TE →' E TE →'E' '→+E E'→E ε '→E εTT F T →' T F T →' T F T →' T F T →'T''→T ε'→T T '→T ε '→T T '→T T '→T T '→T εFF P F →'F P F →' F P F →' F P F →'F' '→F ε '→'F F * '→F ε '→F ε '→F ε '→F ε '→F ε '→F εPP E →() P a → P b → P →^(4)procedure E; beginif sym='(' or sym='a' or sym='b' or sym='^' then begin T; E' end else error endprocedure E'; beginif sym='+'then begin advance; E endelse if sym<>')' and sym<>'#' then error endprocedure T; beginif sym='(' or sym='a' or sym='b' or sym='^' then begin F; T' end else error endprocedure T'; beginif sym='(' or sym='a' or sym='b' or sym='^' then Telse if sym='*' then error endprocedure F; beginif sym='(' or sym='a' or sym='b' or sym='^' then begin P; F' end else error endprocedure F'; beginif sym='*'then begin advance; F' end endprocedure P; beginif sym='a' or sym='b' or sym='^' then advanceelse if sym='(' thenbeginadvance; E;if sym=')' then advance else error endelse errorend;P81–3/***************(1) 是,满足三个条件。
算法导论 第三版 第九章 答案 英
2Hale Waihona Puke is less than roughly 4n/14 of the elements. So, we are never calling it recursively on more than 10n/14 elements. So, T (n) ≤ T (n/7) + T (10n/14) + O(n). So, we can show by substitution this is linear. Suppose T (n) < cn for n < k , then, for m ≥ k , T (m) ≤ T (m/7) + T (10m/14) + O(m) ≤ cm(1/7 + 10/14) + O(m). So, as long as we have that the constant hidden in the big-Oh notation is less than c/7, we have the desired result. Suppose now that we use groups of size 3 instead. So, For similar reasons, we have that the recurrence we are able to get is T (n) = T ( n/3 ) + T (4n/6) + O(n) ≥ T (n/3) + T (2n/3) + O(n). So, we will show it is ≥ cn lg(n). T (m) ≥ c(m/3) lg(m/3) + c(2m/3) lg(2m/3) + O(m) ≥ cm lg(m) + O(m). So, we have that it grows more quickly than linear. Exercise 9.3-2 We know that the number of elements greater than or equal to x and the number of elements less than or equal to x is at least 3n/10 − 6. Then for n ≥ 140 we have 3n/10 − 6 = Exercise 9.3-3 We can modify quicksort to run in worst case n lg(n) time by choosing our pivot element to be the exact median by using quick select. Then, we are guaranteed that our pivot will be good, and the time taken to find the median is on the same order of the rest of the partitioning. Exercise 9.3-4 Create a graph with n vertices and draw a directed edge from vertex i to vertex j if the ith and j th elements of the array are compared in the algorithm and we discover that A[i] ≥ A[j ]. Observe that A[i] is one of the i − 1 smaller elements if there exists a path from x to i in the graph, and A[i] is one of the n − i larger elements if there exists a path from i to x in the graph. Every vertex i must either lie on a path to or from x because otherwise the algorithm can’t distinguish between i ≤ x and i ≥ x. Moreover, if a vertex i lies on both a path to x and a path from x then it must be such that x ≤ A[i] ≤ x, so x = A[i]. In this case, we can break ties arbitrarily. Exercise 9.3-5 To use it, just find the median, partition the array based on that median. If i is less than half the length of the original array, recurse on the first half, if i is half the length of the array, return the element coming from the median finding 3 n n + − 6 ≥ n/4 + 140/20 − 6 = n/4 + 1 ≥ n/4 . 4 20
高级英语第三版第五课课后参考答案
• 2. it released their inhibited violent energies which, after the shooting was over, were .turned in both Europe and America to the destruction of an obsolescent nineteenth-century society (obsolete)
• Flourish has the sense of increasing towards or being in a very desirable condition, or one of maximum development .Boom has the sense of sudden, swift and vigorous growth. Aggressiveness here has the sense of the quality of enterprise and initiative, of being bold and active; whereas aggression refers to an unprovoked attack or to the practice or habit of being quarrelsome. • flourish意为向很理想的状况发展或正处于该状 况,即发展的鼎盛时期。boom意为突然迅速地蓬 勃发展。aggressiveness在这里指大胆积极的开 拓进取。aggression指无故地攻击别人或喜欢争 吵。
• 12. Each town had its "fast" set which prided itself on its unconventionality (para8)
Ch10算法导论 第三版 第十章 答案 英
Chapter10Michelle Bodnar,Andrew LohrApril12,2016Exercise10.1-14414134141841Exercise10.1-2We will call the stacks T and R.Initially,set T.top=0and R.top=n+1. Essentially,stack T uses thefirst part of the array and stack R uses the last part of the array.In stack T,the top is the rightmost element of T.In stack R, the top is the leftmost element of R.Algorithm1PUSH(S,x)1:if S==T then2:if T.top+1==R.top then3:error“overflow”4:else5:T.top=T.top+16:T[T.top]=x7:end if8:end if9:if S==R then10:if R.top−1==T.top then11:error“overflow”12:else13:R.top=R.top−114:T[T.top]=x15:end if16:end if1Algorithm2POP(S)if S==T thenif T.top==0thenerror“underflow”elseT.top=T.top−1.return T[T.top+1]end ifend ifif S==R thenif R.top==n+1thenerror“underflow”elseR.top=R.top+1.return R[R.top−1]end ifend ifExercise10.1-34414131313838Exercise10.1-4Algorithm3ENQUEUEif Q.head==Q.tail+1,or Q.head==1and Q.tail==Q.length then error“overflow”end ifQ[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.head+1end ifExercise10.1-5As in the example code given in the section,we will neglect to check for overflow and underflow errors.2Algorithm4DEQUEUEerror“underflow”end ifx=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifreturn xAlgorithm5HEAD-ENQUEUE(Q,x) Q[Q.head]=xif Q.head==1thenQ.head=Q.lengthelseQ.head=Q.head−1end ifAlgorithm6TAIL-ENQUEUE(Q,x) Q[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.tail+1end ifAlgorithm7HEAD-DEQUEUE(Q,x) x=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifAlgorithm8TAIL-DEQUEUE(Q,x) x=Q[Q.tail]if Q.tail==1thenQ.tail=Q.lengthelseQ.tail=Q.tail−1end if3Exercise10.1-6The operation enqueue will be the same as pushing an element on to stack 1.This operation is O(1).To dequeue,we pop an element from stack2.If stack 2is empty,for each element in stack1we pop it off,then push it on to stack2. Finally,pop the top item from stack2.This operation is O(n)in the worst case.Exercise10.1-7The following is a way of implementing a stack using two queues,where pop takes linear time,and push takes constant time.Thefirst of these ways,consists of just enqueueing each element as you push it.Then,to do a pop,you dequque each element from one of the queues and place it in the other,but stopping just before the last element.Then,return the single element left in the original queue.Exercise10.2-1To insert an element in constant time,just add it to the head by making it point to the old head and have it be the head.To delete an element,it needs linear time because there is no way to get a pointer to the previous element in the list without starting at the head and scanning along.Exercise10.2-2The PUSH(L,x)operation is exactly the same as LIST-INSERT(L,x).The POP operation sets x equal to L.head,calls LIST-DELETE(L,L.head),then returns x.Exercise10.2-3In addition to the head,also keep a pointer to the last element in the linked list.To enqueue,insert the element after the last element of the list,and set it to be the new last element.To dequeue,delete thefirst element of the list and return it.Exercise10.2-4First let L.nil.key=k.Then run LIST-SEARCH’as usual,but remove the check that x=L.nil.Exercise10.2-5To insert,just do list insert before the current head,in constant time.To search,start at the head,check if the element is the current node being in-spected,check the next element,and so on until at the end of the list or you4found the element.This can take linear time in the worst case.To delete,again linear time is used because there is no way to get to the element immediately before the current element without starting at the head and going along the list.Exercise10.2-6Let L1be a doubly linked list containing the elements of S1and L2be a doubly linked list containing the elements of S2.We implement UNION as fol-lows:Set L1.nil.prev.next=L2.nil.next and L2.nil.next.prev=L1.nil.prev so that the last element of L1is followed by thefirst element of L2.Then set L1.nil.prev=L2.nil.prev and L2.nil.prev.next=L1.nil,so that L1.nil is the sentinel for the doubly linked list containing all the elements of L1and L2. Exercise10.2-7Algorithm9REVERSE(L)a=L.head.nextb=L.headwhile a=NIL dotmp=a.nexta.next=bb=aa=tmpend whileL.head=bExercise10.2-8We will store the pointer value for L.head separately,for convenience.In general,A XOR(A XOR C)=C,so once we know one pointer’s true value we can recover all the others(namely L.head)by applying this rule.Assuming there are at least two elements in the list,thefirst element will contain exactly the address of the second.Algorithm10LISTnp-SEARCH(L,k)p=NILx=L.headwhile x=NIL and x.key=k dotemp=xx=pXORx.npp=tempend whileTo reverse the list,we simply need to make the head be the“last”ele-5Algorithm11LISTnp-INSERT(L,x)x.np=L.headL.nil.np=xXOR(L.nil.npXORL.head)L.head=xAlgorithm12LISTnp-Delete(L,x)L.nil.np=L.nil.npXORL.headXORL.head.npL.head.np.np=L.head.np.npXORL.headment before L.nil instead of thefirst one after this.This is done by settingL.head=L.nil.npXORL.head.Exercise10.3-1A multiple array version could be L=2,/34567/124819511/23456A single array version could be L=4,127/410481371916105191311/16 Exercise10.3-2Algorithm13Allocate-Object()if free==NIL thenerror“out of space”elsex=freefree=A[x+1]end ifExercise10.3-3Allocate object just returns the index of some cells that it’s guaranteed tonot give out again until they’ve been freed.The prev attribute is not modified because only the next attribute is used by the memory manager,it’s up to the code that calls allocate to use the prev and key attributes as it seesfit.Exercise10.3-4For ALLOCATE-OBJECT,we will keep track of the next available spot inthe array,and it will always be one greater than the number of elements being stored.For FREE-OBJECT(x),when a space is freed,we will decrement the6Algorithm14Free-Object(x)A[x+1]=freefree=xposition of each element in a position greater than that of x by1and update pointers accordingly.This takes linear time.Exercise10.3-5See the algorithm COMP ACT IF Y−LIST(L,F)Exercise10.4-1181274510221Note that indices8and2in the array do not appear,and,in fact do not represent a valid tree.Exercise10.4-2See the algorithm PRINT-TREE.Exercise10.4-3Exercise10.4-4See the algorithm PRINT-TREE.Exercise10.4-5See the algorithm INORDER-PRINT’(T)Exercise10.4-6Our two pointers will be left and right.For a node x,x.left will point to the leftmost child of x and x.right will point to the sibling of x immediately to its right,if it has one,and the parent of x otherwise.Our boolean value b,stored at x,will be such that b=depth(x)mod2.To reach the parent of a node, simply keep following the“right”pointers until the parity of the boolean value changes.Tofind all the children of a node,start byfinding x.left,then follow7Algorithm15COMPACTIFY-LIST(L,F)if n=m thenreturnend ife=max{max i∈[m]{|key[i]|},max i∈L{|key[i]|}}increase every element of key[1..m]by2efor every element of L,if its key is greater than e,reduce it by2e f=1while key[f]<e dof++end whilea=L.headif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE−OBJECT(a)f++while key[f]<e dof++end whileend ifwhile a=L.head doif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE−OBJECT(a)f++while key[f]<e dof++end whileend ifend while8Algorithm16PRINT-TREE(T.root) if T.root==NIL thenreturnelsePrint T.root.keyPRINT-TREE(T.root.left)PRINT-TREE(T.root.right)end ifAlgorithm17INORDER-PRINT(T) let S be an empty stackpush(S,T)while S is not empty doU=pop(S)if U=NIL thenprint U.keypush(S,U.left)push(S,U.right)end ifend whileAlgorithm18PRINT-TREE(T.root) if T.root==NIL thenreturnelsePrint T.root.keyx=T.root.left−childwhile x=NIL doPRINT-TREE(x)x=x.right−siblingend whileend if9Algorithm19INORDER-PRINT’(T) a=T.leftprev=Twhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend whileprint T.keya=T.rightwhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend while10the“right”pointers until the parity of the boolean value changes,ignoring thislast node since it will be x.Problem10-1For each,we assume sorted means sorted in ascending orderunsorted,single sorted,single unsorted,double sorted,double SEARCH(L,k)n n n nINSERT(L,x)1111DELET E(L,x)n n11SUCCESSOR(L,x)n1n1P REDECESSOR(L,x)n n n1 MINIMUM(L,x)n1n1MAXIMUM(L,x)n n n1 Problem10-2In all three cases,MAKE-HEAP simply creates a new list L,sets L.head=NIL,and returns L in constant time.Assume lists are doubly linked.To realizea linked list as a heap,we imagine the usual array implementation of a binaryheap,where the children of the i th element are2i and2i+1.a.To insert,we perform a linear scan to see where to insert an element suchthat the list remains sorted.This takes linear time.Thefirst element in thelist is the minimum element,and we canfind it in constant time.Extract-minreturns thefirst element of the list,then deletes it.Union performs a mergeoperation between the two sorted lists,interleaving their entries such thatthe resulting list is sorted.This takes time linear in the sum of the lengthsof the two lists.b.To insert an element x into the heap,begin linearly scanning the list untilthefirst instance of an element y which is strictly larger than x.If no suchlarger element exists,simply insert x at the end of the list.If y does exist,replace y t by x.This maintains the min-heap property because x≤y andy was smaller than each of its children,so x must be as well.Moreover,xis larger than its parent because y was thefirst element in the list to exceedx.Now insert y,starting the scan at the node following x.Since we checkeach node at most once,the time is linear in the size of the list.To get theminimum element,return the key of the head of the list in constant time.To extract the minimum element,wefirst call MINIMUM.Next,we’ll replacethe key of the head of the list by the key of the second smallest element yin the list.We’ll take the key stored at the end of the list and use it toreplace the key of y.Finally,we’ll delete the last element of the list,and callMIN-HEAPIFY on the list.To implement this with linked lists,we need tostep through the list to get from element i to element2i.We omit this detailfrom the code,but we’ll consider it for runtime analysis.Since the value ofi on which MIN-HEAPIFY is called is always increasing and we never need11to step through elements multiple times,the runtime is linear in the length of the list.Algorithm20EXTRACT-MIN(L)min=MINIMUM(L)Linearly scan for the second smallest element,located in position i.L.head.key=L[i]L[i].key=L[L.length].keyDELETE(L,L[L.length])MIN-HEAPIFY(L[i],i)return minAlgorithm21MIN-HEAPIFY(L[i],i)1:l=L[2i].key2:r=L[2i+1].key3:p=L[i].key4:smallest=i5:if L[2i]=NIL and l<p then6:smallest=2i7:end if8:if L[2i+1]=NIL and r<L[smallest]then9:smallest=2i+110:end if11:if smallest=i then12:exchange L[i]with L[smallest]13:MIN-HEAPIFY(L[smallest],smallest)14:end ifUnion is implemented below,where we assume A and B are the two list representations of heaps to be merged.The runtime is again linear in the lengths of the lists to be merged.c.Since the algorithms in part b didn’t depend on the elements being distinct,we can use the same ones.Problem10-3a.If the original version of the algorithm takes only t iterations,then,we havethat it was only at most t random skips though the list to get to the desired value,since each iteration of the original while loop is a possible random jump followed by a normal step through the linked list.b.The for loop on lines2-7will get run exactly t times,each of which is constantruntime.After that,the while loop on lines8-9will be run exactly X t times.So,the total runtime is O(t+E[X t]).12Algorithm22UNION(A,B)1:if A.head=NIL then2:return B3:end if4:i=15:x=A.head6:while B.head=NIL do7:if B.head.key≤x.key then8:Insert a node at the end of list B with key x.key 9:x.key=B.head.key10:Delete(B,B.head)11:end if x=x.next12:end while13:return Aing equation C.25,we have that E[X t]= ∞i=1P r(X t≥i).So,we needto show that P r(X t≥i)≤(1−i/n)t.This can be seen because having X t being greater than i means that each random choice will result in an element that is either at least i steps before the desired element,or is after the desired element.There are n−i such elements,out of the total n elements that we were pricking from.So,for a single one of the choices to be from such a range, we have a probability of(n−i)/n=(1−i/n).Since each of the selections was independent,the total probability that all of them were is(1−i/n)t, as stly,we can note that since the linked list has length n,the probability that X t is greater than n is equal to zero.d.Since we have that t>0,we know that the function f(x)=x t is increasing,so,that means that x t≤f(x).So,n−1r=0r t=nr t dr≤nf(r)dr=n t+1e.E[X t]≤nr=1(1−r/n)t=nr=1ti=0ti(−r/n)i=ti=0nr=1ti(−r/n)i=ti=0ti(−1)in i−1+n−1r=0(r)t/n≤ti=0ti(−1)in i−1+n i+1/n ≤ti=0ti(−1)in ii+1=1t+1ti=0t+1i+1(−n)i≤(1−n)t+1t+1f.We just put together parts b and e to get that it runs in time O(t+n/(t+1)).But,this is the same as O(t+n/t).13g.Since we have that for any number of iterations t that the first algorithm takes to find its answer,the second algorithm will return it in time O (t +n/t ).In particular,if we just have that t =√n .The second algorithm takestime only O (√n ).This means that tihe first list search algorithm is O (√n )as well.h.If we don’t have distinct key values,then,we may randomly select an element that is further along than we had been before,but not jump to it because it has the same key as what we were currently at.The analysis will break when we try to bound the probability that X t ≥i .14。
算法导论(第二版)习题答案(英文版)
Last update: December 9, 2002
1.2 − 2 Insertion sort beats merge sort when 8n2 < 64n lg n, ⇒ n < 8 lg n, ⇒ 2n/8 < n. This is true for 2 n 43 (found by using a calculator). Rewrite merge sort to use insertion sort for input of size 43 or less in order to improve the running time. 1−1 We assume that all months are 30 days and all years are 365.
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
算法导论 第三版 第一章 答案 英
Chapter1Michelle Bodnar,Andrew LohrApril12,2016Exercise1.1-1An example of a real world situation that would require sorting would be if you wanted to keep track of a bunch of people’sfile folders and be able to look up a given name quickly.A convex hull might be needed if you needed to secure a wildlife sanctuary with fencing and had to contain a bunch of specific nesting locations.Exercise1.1-2One might measure memory usage of an algorithm,or number of people required to carry out a single task.Exercise1.1-3An array.It has the limitation of requiring a lot of copying when re-sizing, inserting,and removing elements.Exercise1.1-4They are similar since both problems can be modeled by a graph with weighted edges and involve minimizing distance,or weight,of a walk on the graph.They are different because the shortest path problem considers only two vertices,whereas the traveling salesman problem considers minimizing the weight of a path that must include many vertices and end where it began.Exercise1.1-5If you were for example keeping track of terror watch suspects,it would be unacceptable to have it occasionally bringing up a wrong decision as to whether a person is on the list or not.It would befine to only have an approximate solution to the shortest route on which to drive,an extra little bit of driving is not that bad.1Exercise1.2-1A program that would pick out which music a user would like to listen tonext.They would need to use a bunch of information from historical and pop-ular preferences in order to maximize.Exercise1.2-2We wish to determine for which values of n the inequality8n2<64n log2(n)holds.This happens when n<8log2(n),or when n≤43.In other words,insertion sort runs faster when we’re sorting at most43items.Otherwise mergesort is faster.Exercise1.2-3We want that100n2<2n.note that if n=14,this becomes100(14)2=19600>214=16384.For n=15it is100(15)2=22500<215=32768.So,the answer is n=15.Problem1-1We assume a30day month and365day year.1Second1Minute1Hour1Day1Month1Year1Century lg n21×10626×10723.6×10928.64×101022.592×101223.1536×101323.15576×1015√n1×10123.6×10151.29×10197.46×10216.72×10249.95×10269.96×1030 n1×1066×1073.6×1098.64×10102.59×10123.15×10133.16×1015 n lg n1894818.64×1064.18×1088.69×1092.28×10112.54×10122.20×1014 n210007745600002939381609968561569256176151 n3100391153244201373631593146679 2n19253136414451n!91112131516172。
算法导论第三版答案
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.
算法导论答案Ch3
f (n) =∞ g (n)
Ω(g (n, m)) = {f (n, m) : there exist positive constants c, n0 , and m0 such that f (n, m) ≥ cg (n, m) for all n ≥ n0 or m ≥ m0 }
Θ(g (n, m)) = {f (n, m) : there exist positive constants c1 , c2 , n0 , and m0 such that c1 g (n, m) ≤ f (n, m) ≤ c2 g (n, m) for all n ≥ n0 or m ≥ m0 } Exercise 3.2-1 Let n1 < n2 be arbitrary. From f and g being monatonic increasing, we know f (n1 ) < f (n2 ) and g (n1 ) < g (n2 ). So f (n1 ) + g (n1 ) < f (n2 ) + g (n1 ) < f (n2 ) + g (n2 ) 2
n→∞
2e n
n
≤ lim
n→∞
2e n
n
1 =0 2n
nn 1 en n −.5 n √ = lim √ e = lim O ( n ) e ≥ lim 1 n→∞ n! n→∞ n→∞ c1 n n→∞ 2πn(1 + Θ( n )) lim ≥ lim en en = lim =∞ n→∞ c1 n n→∞ c1
n a/b n if and only if if and only if n − 21 /b ≥ −a if and only if n + a ≥ (1/2) (n + a)b ≥ cnb . Therefore (n + a)b = Ω(nb ). By Theorem 3.1, (n + a)b = Θ(nb ).
算法导论中文版答案
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
算法导论第三版第六章答案英
算法导论第三版第六章答案英Chapter6Michelle Bodnar,Andrew LohrDecember31,2016Exercise6.1-1At least2h and at most2h+1?1.Can be seen because a complete binarytree of depth h?1hasΣh?1i=02i=2h?1elements,and the number of elementsin a heap of depth h is between the number for a complete binary tree of depth h?1exclusive and the number in a complete binary tree of depth h inclusive.Exercise6.1-2Write n=2m?1+k where m is as large as possible.Then the heap consists of a complete binary tree of height m?1,along with k additional leaves along the bottom.The height of the root is the length of the longest simple path to one of these kleaves,which must have length m.It is clear from the way we de?ned m that m= lg n .Exercise6.1-3If there largest element in the subtee were somewhere other than the root, it has a parent that is in the subtree.So,it is larger than it’s parent,so,the heap property is violated at the parent of the maximum element in the subtreeExercise6.1-4The smallest element must be a a leaf node.Suppose that node x contains the smallest element and x is not a leaf.Let y denote a child node of x.By the max-heap property,the value of x is greater than or equal to the value of y.Since the elements of the heap are distinct,the inequality is strict.This contradicts the assumption that x contains the smallest element in the heap. Exercise6.1-5Yes,it is.The index of a child is always greater than the index of the parent, so the heap property is satis?ed at each vertex. 1Exercise6.1-6No,the array is not a max-heap.7is contained in position9of the array,so its parent must be in position4,which contains6.This violates the max-heap property.Exercise6.1-7It su?ces to show that the elements with no children are exactly indexed by{ n/2 +1,...,n}.Suppose that we had an i in this range.It’s childeren would be located at2i and2i+1but both of these are≥2 n/2 +2>n and so are not in the array.Now,suppose we had an element with no kids,this means that2i and2i+1are both>n,however,this means that i>n/2.This means that i∈{ n/2 +1,...,n}.Exercise6.2-1271731613101571248902717101613315712489027171016138157124830Exercise6.2-2Algorithm1MIN-HEAPIFY(A,i)1:l=LEF T(i)2:r=RIGHT(i)3:if l≤A.heap?size and A[l]4:smallest=l5:else smallest=i6:end if7:if r≤A.heap?size and A[r]8:smallest=r9:end if10:if smallest=i then11:exchange A[i]with A[smallest]12:MIN-HEAPIFY(A,smallest)13:end ifThe running time of MIN-HEAPIFY is the same as that of MAX-HEAPIFY. Exercise6.2-3The array remains unchanged since the if statement on line line8will be false.2Exercise6.2-4If i>A.heap?size/2then l and r will both exceed A.heap?size so the if statement conditions on lines3and6of the algorithm will never be satis?ed. Therefore largest=i so the recursive call will never be made and nothing will happen.This makes sense because i necessarily corresponds to a leaf node,so MAX–HEAPIFY shouldn’t alter the heap.Exercise6.2-5Iterative Max Heapify(A,i)while il=LEFT(i)r=LEFT(i)largest=iif l≤A.heap-size and A[l]>A[i]thenlargest=lend ifif l≤A.heap-size and A[r]>A[i]thenlargest=rend ifif largest=i thenexchange A[i]and A[largest]elsereturn Aend ifend whilereturn AExercise6.2-6Consider the heap resulting from A where A[1]=1and A[i]=2for 2≤i≤n.Since1is the smallest element of the heap,it must be swapped through each level of the heap until it is a leaf node.Since the heap has height lg n ,MAX-HEAPIFY has worst-case time?(lg n).Exercise6.3-1531710841962295317228419610953192284176109584192231761098451922317610984221953176109842219103176593Exercise6.3-2If we had started at1,we wouldn’t be able to guarantee that the max-heap property is maintained.For example,if the array A is given by[2,1,1,3]then MAX-HEAPIFY won’t exchange2with either of it’s children,both1’s.How-ever,when MAX-HEAPIFY is called on the left child,1,it will swap1with3. This violates the max-heap property because now2is the parent of3.Exercise6.3-3All the nodes of height h partition the set of leaves into sets of size between 2h?1+1and2h,where all but one is size2h.Just by putting all the children of each in their own part of trhe partition.Recall from6.1-2that the heap has height lg(n) ,so,by looking at the one element of this height(the root),we get that there are at most2 lg(n) leaves.Since each of the vertices of height h partitions this into parts of size at least2h?1+1,and all but one corresponds to a part of size2h,we can let k denote the quantity we wish to bound,so,(k?1)2h+k(2h?1+1)≤2 lg(n) ≤n/2sok≤n+2h2h+1+2h+1≤n2h+1≤n2h+1Exercise6.4-14513225717208451320257172845252013717284255201371728425132057172842513208717254413208717252520134871725252013178742525513178742202517135874220252135874172025132587417202513852741720254852713172025845271317202587524131720254752813172025745281317202524578131720255427813172025245781317202542578131720252457813172025Exercise6.4-2We’ll prove the loop invariant of HEAPSORT by induction:Base case:At the start of the?rst iteration of the for loop of lines2-5we have i=A.length.The subarray A[1..n]is a max-heap since BUILD-MAX-HEAP(A)was just called.It contains the n smallest elements,and the empty subarray A[n+1..n]trivially contains the0largest elements of A in sorted order.Suppose that at the start of the i th iteration of of the for loop of lines2-5, the subarray A[1..i]is a max-heap containing the i smallest elements of A[1..n] and the subarray A[i+1..n]contains the n?i largest elements of A[1..n]in sorted order.SinceA[1..i]is a max-heap,A[1]is the largest element in A[1..i]. Thus it is the(n?(i?1))th largest element from the original array since the n?i largest elements are assumed to be at the end of the array.Line3swaps A[1]with A[i],so A[i..n]contain the n?i+1largest elements of the array, and A[1..i?i]contains the i?1smallest elements.Finally,MAX-HEAPIFY is called on A,1.Since A[1..i]was a max-heap prior to the iteration and only the elements in positions1and i were swapped,the left and right subtrees ofnode1,up to node i?1,will be max-heaps.The call to MAX-HEAPIFY will place the element now located at node1into the correct position and restore the5max-heap property so that A[1..i?1]is a max-heap.This concludes the next iteration,and we have veri?ed each part of the loop invariant.By induction, the loop invariant holds for all iterations.After the?nal iteration,the loop invariant says that the subarray A[2..n] contains the n?1largest elements ofA[1..n],sorted.Since A[1]must be the n th largest element,the whole array must be sorted as desired.Exercise6.4-3If it’s already sorted in increasing order,doing the build max heap-max-heap call on line1will takeΘ(n lg(n))time.There will be n iterations of the for loop, each takingΘ(lg(n))time because the element that was at position i was the smallest and so will have lg(n) steps when doing max-heapify on line5.So, it will beΘ(n lg(n))time.If it’s already sorted in decreasing order,then the call on line one will only takeΘ(n)time,since it was already a heap to begin with,but it will still take n lg(n)peel o?the elements from the heap and re-heapify.Exercise6.4-4Consider calling HEAPSORT on an array which is sorted in decreasing order. Every time A[1]is swapped with A[i],MAX-HEAPIFY will be recursively called a number of times equal to the height h of the max-heap containing the elements of positions1through i?1,and has runtime O(h).Since there are2k nodes at height k,the runtime is bounded below bylg ni=12i log(2i)=lg ni=1i2i=2+( lg n ?1)2 lg n =?(n lg n).Exercise6.4-5Since the call on line one could possibly take only linear time(if the input was already a max-heap for example),we will focus on showing that the for loop takes n log n time.This is the case because each time that the last element is placed at the beginning to replace the max element being removed,it has to go through every layer,because it was already very small since it was at the bottom level of the heap before.Exercise6.5-1The following sequence of pictures shows how the max is extracted from the heap.1.Original heap:615 13540126298172.we move the last element to the top of theheap 3.13>9>1so,we swap1and13.4.Since12>5>1,we swap1and12.75.Since6>2>1,we swap1and6.Exercise6.5-2The following sequence of pictures shows how10is inserted into the heap, then swapped with parent nodes until the max-heap property is restored.The node containing the new key is heavily shaded.1.Original heap:815 13540126298172.MAX-HEAP-INSERT(A,10)is called,so we?rst append a node assignedvalue?∞:3.The key value of the new node is updated:4.Since the parent key is smaller than10,the nodes are swapped:95.Since the parent node is smaller than10,the nodes are swapped:Exercise6.5-3Heap-Minimum(A)1:return A[1]Heap-Extract-Min(A)1:if A.heap-size<1then2:Error“heap under?ow”3:end if4:min=A[1]5:A[1]=A[A.heap?size]6:A.heap?size??7:Min-heapify(A,1)8:return minHeap-decrease-key(A,i,key)101:if key?A[i]then2:Error“new key larger than old key”3:end if4:A[i]=key5:while i>1and A[P arent(i)]6:exchange A[i]with A[P arent(i)]7:i=P arent(i)8:end whileMin-Heap-Insert(A,key)1:A.heap?size++2:A[A.heap?size]=∞3:Heap-Decrease-Key(A,A.heap-size,key)Exercise6.5-4If we don’t make an assignment to A[A.heap?size]then it could contain any value.In particular,when we call HEAP-INCREASE-KEY,it might be the case that A[A.heap?size]initially contains a value larger than key,causing an error.By assigning?∞to A[A.heap?size]we guarantee that no error will occur.However,we could have assigned any value less than or equal to key to A[A.heap?size]and the algorithm would still work.Exercise6.5-5Initially,we have a heap and then only change the value at i to make it larger.This can’t invalidate the ordering between i and it’s children,the only other thing that needs to be related to i is that i is less than it’s parent,which may be false.Thus we have the invariant is true at initialization.Then,when we swap i with its parent if it is larger,since it is larger than it’s parent,it must also be larger than it’s sibling,also,since it’s parent was initially above its kids in the heap,we know that it’s parent is larger than it’s kids.The only relation in question is then the new i and it’s parent.At termination,i is the root,so it has no parent,so the heap property must be satis?ed everywhere.Exercise6.5-6Replace A[i]by key in the while condition,and replace line5by“A[i]= A[P ARENT(i)].”After the end of the while loop,add the line A[i]=key. Since the key value doesn’t change,there’s no sense in assigning it until we know where it belongs in the heap.Instead,we only make the assignment of the parent to the child node.At the end of the while loop,i is equal to the position where key belongs since it is either the root,or the parent is at least11key,so we make the assignment.Exercise6.5-7Have a?eld in the structure that is just a count of the total number of elements ever added.When adding an element,use thecurrent value of that counter as the key.Exercise6.5-8The algorithm works as follows:Replace the node to be deleted by the last node of the heap.Update the size of the heap,then call MAX-HEAPIFY to move that node into its proper position and maintain the max-heap property. This has running timeO(lg n)since the number of times MAX-HEAPIFY is recursively called is as most the height of the heap,which is lg n . Algorithm2HEAP-DELETE(A,i)1:A[i]=A[A.heap?size]2:A.heap?size=A.heap?size+13:MAX-HEAPIFY(A,i)Exercise6.5-9Construct a min heap from the heads of each of the k lists.Then,to?nd the next element in the sorted array,extract the minimum element(in O lg(k) time).Then,add to the heap the next element from the shorter list from which the extracted element originally came(also O(lg(k))time).Since?nding the next element in the sorted list takes only at most O(lg(k))time,to? nd the whole list,you need O(n lg(k))total steps.Problem6-1a.They do not.Consider the array A= 3,2,1,4,5 .If we run Build-Max-Heap,we get 5,4,1,3,2 .However,if we run Build-Max-Heap’,we will get 5,4,1,2,3 instead.b.Each insert step takes at most O(lg(n)),since we are doing it n times,weget a bound on the runtime of O(n lg(n)).Problem6-2a.It will su?ce to show how to access parent and child nodes.In a d-ary array,PARENT(i)= i/d ,and CHILD(k,i)=di?d+1+k,where CHILD(k,i) gives the k th child of the node indexed by i.12b.The height of a d-ary heap of n elements is with1of log d n.c.The following is an implementation of HEAP-EXTRACT-MAX for a d-aryheap.An implementation of DMAX-HEAPIFY is also given,which is the analog of MAX-HEAPIFY for d-ary heap.HEAP-EXTRACT-MAX con-sists of constant time operations,followed by a call to DMAX-HEAPIFY.The number of times this recursively calls itself is bounded by the height of the d-ary heap,so the running time is O(d log d n).Note that the CHILD function is meant to be the one described in part(a).Algorithm3HEAP-EXTRACT-MAX(A)for a d-ary heap1:if A.heap?size<1then2:error“heap under?ow”3:end if4:max=A[1]5:A[1]=A[A.heap?size]6:A.heap?size=A.heap?size?17:DMAX-HEAPIFY(A,1)Algorithm4DMAX-HEAPIFY(A,i)1:largest=i2:for k=1to d do3:if CHILD(k,i)≤A.heap?size and A[CHILD(k,i)]>A[i]then4:if A[CHILD(k,i)]>largest then5:largest=A[CHILD(k,i)]6:end if7:end if8:end for9:if largest=i then10:exchange A[i]with A[largest]11:DMAX-HEAPIFY(A,largest)12:end ifd.The runtime of this implementation of INSERT is O(log d n)since the whileloop runs at most as many times as the height of the d-ary array.Note that when we call PARENT,we mean it as de?ned in part(a).e.This is identical to the implementation of HEAP-INCREASE-KEY for2-aryheaps,but with the PARENT function interpreted as in part(a).The run-time is O(log d n)since the while loop runs at most as many times as the height of the d-ary array.13Algorithm5INSERT(A,key)1:A.heap?size=A.heap?size+12:A[A.heap?size]=key3:i=A.heap?size4:while i>1and A[P ARENT(i)5:exchange A[i]with A[P ARENT(i)]6:i=P ARENT(i)7:end whileAlgorithm6INCREASE-KEY(A,i,key)1:if key2:error“new key is smaller than current key”3:end if4:A[i]=key5:while i>1and A[P ARENT(i)6:exchange A[i]with A[P ARENT(i)]7:i=P ARENT(i)8:end whileProblem6-3a.2345 891214 16∞∞∞∞∞∞∞b.For every i,j,Y[1,1]≤Y[i,1]≤Y[i,j].So,if Y[1,1]=∞,we know thatY[i,j]=∞for every i,j.This means that no elements exist.If Y is full,it has no elements labeled∞,in particular,the element Y[m,n]is not labeled ∞.c.Extract-Min(Y,i,j),extracts the minimum value from the young tableau Yobtained by Y [i ,j ]=Y[i +i?1,j +j?1].Note that in running this algorithm,several accesses may be made out of bounds for Y,de? ne these to return∞.No store operations will be made on out of bounds locations.Since the largest value of i+j that this can be called with is n+m,and this quantity must increase by one for each call,we have that the runtime is bounded by n+m.d.Insert(Y,key)Since i+j is decreasing at each step,starts as n+m and isbounded by2below,we know that this program has runtime O(n+m). e.Place the n2elements into a Young Tableau by calling the algorithm frompart d on each.Then,call the algorithm from part c n2to obtain the numbers in increasing order.Both of these operations take time at most2n∈O(n), and are done n2times,so,the total runtime is O(n3)141:min=Y[i,j]2:if Y[i,j+1]=Y[i+1,j]=∞then3:Y[i,j]=∞4:return min5:end if6:if Y[i,j+1]7:Y[i,j]=Y[i,j+1]8:Y[i,j+1]=min9:return Extract-min(y,i,j+1)10:else11:Y[i,j]=Y[i+1,j]12:Y[i+1,j]=min13:return Extract-min(y,i+1,j)14:end if1:i=m,j=n2:Y[i,j]=key3:while Y[i?1,j]>Y[i,j]or Y[i,j?1]>Y[i,j]do 4:if Y[i?1,j]5:Swap Y[i,j]and Y[i,j?1]6:j??7:else8:Swap Y[i,j]and Y[i?1,j]9:i??10:end if11:end while15f.Find(Y,key).Let Check(y,key,i,j)mean to return true if Y[i,j]=key,oth-erwise do nothingi=j=1while Y[i,j]Check(Y,key,i,j)i++end whilewhile i>1and jCheck(i,j)if Y[i,j]j++elsei–end ifend whilereturn false16。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1
1: 2: 3: 4: 5: 6: 7: 8: 9: 10:
for all eternity do a = BiasedRandom b = BiasedRandom if a > b then return 1 end if if a < b then return 0 end if end for
Chapter 5
Michelle Bodnar, Andrew Lohr April 12, 2016
Exercise 5.1-1 We may of been presented the candidates in increasing order of goodness. This would mean that we can apply transitivity to determine our preference between any two candidates Exercise 5.1-2
Algorithm 1 RANDOM(a,b) 1: n = lg(b − a + 1) 2: Initialize an array A of length n 3: while true do 4: for i = 1 to n do 5: A[i] = RAN DOM (0, 1) 6: end for 7: if A holds the binary representation of one of the numbers in a through b then 8: return number represented by A 9: end if 10: end while Each iteration of the while loop takes n time to run. The probability that the while loop stops on a given iteration is (b − a + 1)/2n . Thus the expected running time is the expected number of times run times n. This is given by: n
loop. This program will expect to go through the loop a number of times equal to:
∞
j (1 − 2p(p − 1))j (2p(p − 1)) =
j =0
1 − 2p(p − 1) 2p(p − 1)(1 − 2p(p − 1)) = (2p(p − 1))2 2p(p − 1)
i≥1
i 1−
b−a+1 2n
i −1
b−a&2n
2n b−a+1
2
=n
2n = O(lg(b−a)). b−a+1
Exercise 5.1-3 Clearly since a and b are IID, the probability this algorithm returns one is equal to the probability it returns 0. Also, since there is a constant positive probability (2p(p − 1)) that the algorithm returns on each iteration of the for
Note that the formula used for the sum of jαj can be obtained by differentiawting both sides of the geometric sum formula for αj with respect to α Exercise 5.2-1 You will hire exactly one time if the best candidate is presented first. There are (n − 1)! orderings with the best candidate first, so, it is with probability (n−1)! 1 = n that you only hire once. You will hire exactly n times if the candin! dates are presented in increasing order. This fixes the ordering to a single one, 1 and so this will occur with probability n !. Exercise 5.2-2 Since the first candidate is always hired, we need to compute the probability that that exactly one additional candidate is hired. Since we view the candidate ranking as reading an random permutation, this is equivalent to the probability that a random permutation is a decreasing sequence followed by an increase, followed by another decreasing sequence. Such a permutation can be thought of as a partition of [n] into 2 parts. One of size k and the other of size n − k , where 1 ≤ k ≤ n − 1. For each such partition, we obtain a permutation with a single increase by ordering the numbers each partition in decreasing order, then concatenating these sequences. The only thing that can go wrong is if the numbers n through n − k + 1 are in the first partition. Thus there are n k −1 permutations which correspond to hiring the second and final person on step k + 1. Summing, we see that the probability you hire exactly twice is