算法导论 第三版 第七章 答案 英

算法导论 第三版 第七章 答案 英
算法导论 第三版 第七章 答案 英

Chapter7

Michelle Bodnar,Andrew Lohr

April12,2016

Exercise7.1-1

13199512874212611

13199512874212611

13199512874212611

91913512874212611

95131912874212611

95131912874212611

95819121374212611

95871213194212611

95874131912212611

95874131912212611

95874219122113611

95874261221131911

95874261121131912

Exercise7.1-2

If all elements in the array have the same value,PARTITION returns r.To make PARTITION return q= (p+r)/2 when all elements have the same value,modify line4of the algorithm to say this:if A[j]≤x and j(mod2)= (p+1)(mod2).This causes the algorithm to treat half of the instances of the same value to count as less than,and the other half to count as greater than.

Exercise7.1-3

The for loop makes exactly r?p iterations,each of which takes at most constant time.The part outside the for loop takes at most constant time.Since r?p is the size of the subarray,PARTITION takes at most time proportional to the size of the subarray it is called on.

Exercise7.1-4

To modify QUICKSORT to run in non-increasing order we need only modify line4of PARTITION,changing≤to≥.

1

Exercise7.2-1

By de?nition ofΘ,we know that there exists c1,c2so that theΘ(n)term is between c1n and c2n.We make that inductive hypothesis be that c1m2≤T(m)≤c2m2for all m

c1n2≤c1(n?1)2+c1n≤T(n?1)+Θ(n)

=T(n)=T(n?1)+Θ(n)≤c2(n?1)2+c2n≤c2n2

Exercise7.2-2

The running time of QUICKSORT on an array in which evey element has the same value is n2.This is because the partition will always occur at the last po-sition of the array(Exercise7.1-2)so the algorithm exhibits worst-case behavior.

Exercise7.2-3

If the array is already sorted in decreasing order,then,the pivot element is less than all the other elements.The partition step takesΘ(n)time,and then leaves you with a subproblem of size n?1and a subproblem of size0.This gives us the recurrence considered in7.2-1.Which we showed has a solution that isΘ(n2).

Exercise7.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 INSERTION-SORT,we run the inner-while loop at most c times before we?nd 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?xed in advance.Now suppose we run QUICK-SORT.The split of PARTITION will be at best n?c to c,which leads to O(n2) running time.

Exercise7.2-5

The minimum depth corresponds to repeatedly taking the smaller subprob-lem,that is,the branch whose size is proportional toα.Then,this will fall to

1in k steps where1≈(α)k n.So,k≈logα(1/n)=?lg(n)

lg(α).The longest depth

corresponds to always taking the larger subproblem.we then have and identical expression,replacingαwith1?α.

Exercise7.2-6

2

Without loss of generality,assume that the entries of the input array are distinct.Since only the relative sizes of the entries matter,we may assume that A contains a random permutation of the numbers1through n.Now?x 0<α≤1/2.Let k denote the number of entries of A which are less than A[n].PARTITION produces a split more balanced than1?αtoαif and

only ifαn≤k≤(1?α)n.This happens with probability(1?α)n?αn+1

n =

1?2α+1/n≈1?2α.

Exercise7.3-1

We analyze the expected run time because it represents the more typical time cost.Also,we are doing the expected run time over the possible random-ness used during computation because it can’t be produced adversarially,unlike when doing expected run time over all possible inputs to the algorithm.

Exercise7.3-2

In the worst case,RANDOM returns the index of the largest element each time it’s called,soΘ(n)calls are made.In the best case,RANDOM returns the index of the element in the middle of the array and the array has distinct elements,soΘ(lg n)calls are made.

Exercise7.4-1

By de?nition ofΘ,we know that there exists c1,c2so that theΘ(n)term is between c1n and c2n.We make that inductive hypothesis be that c1m2≤T(m)≤c2m2for all m

c1n2≤c1max

q∈[n]

n2?2n(q+2)+(q+1)2+(q+1)2+n

=max

q∈[n]

c1(n?q?2)2+c1(q+1)2+c1n

≤max

q∈[n]

T(n?q?2)+T(q+1)+Θ(n)

=T(n)

Similarly for the other direction

Exercise7.4-2

We’ll use the substitution method to show that the best-case running time is?(n lg n).Let T(n)be the best-case time for the procedure QUICKSORT on an input of size n.We have the recurrence

T(n)=min

1≤q≤n?1

(T(q)+T(n?q?1))+Θ(n).

Suppose that T(n)≥c(n lg n+2n)for some constant c.Substituting this guess

3

into the recurrence gives

T(n)≥min

1≤q≤n?1

(cq lg q+2cq+c(n?q?1)lg(n?q?1)+2c(n?q?1))+Θ(n)

=cn

2

lg(n/2)+cn+c(n/2?1)lg(n/2?1)+cn?2c+Θ(n)

≥(cn/2)lg n?cn/2+c(n/2?1)(lg n?2)+2cn?2cΘ(n)

=(cn/2)lg n?cn/2+(cn/2)lg n?cn?lg n+2+2cn?2cΘ(n)

=cn lg n+cn/2?lg n+2?2c+Θ(n)

Taking a derivative with respect to q shows that the minimum is obtained when q=n/2.Taking c large enough to dominate the?lg n+2?2c+Θ(n)term makes this greater than cn lg n,proving the bound.

Exercise7.4-3

We will treat the given expression to be continuous in q,and then,any ex-tremal values must be either adjacent to a critical point,or one of the endpoints. The second derivative with respect to q is4,So,we have that any critical points we?nd will be minima.The expression has a derivative with respect to q of 2q?2(n?q?2)=?2n+4q+4which is zero when we have2q+2=n.So,

there will be a minima at q=n?2

2.So,the maximal values must only be the

endpoints.We can see that the endpoints are equally large because at q=0,it is(n?1)2,and at q=n?1,it is(n?1)2+(n?n+1?1)2=(n?1)2. Exercise7.4-4

We’ll use the lower bound(A.13)for the expected running time given in the section:

E[X]=n?1

i=1

n

j=i+1

2

j?i+1

=n?1

i=1

n?i

k=1

2

k

≥n?1

i=1

2ln(n?i+1)

=2ln n?1

i=1

n?i+1

=2ln(n!)

=2

lg(n!)≥cn lg n

for some constant c since lg(n!)=Θ(n lg n)by Exercise 3.2-3.Therefore RANDOMIZED-QUICKSORT’s expected running time is?(n lg n).

4

Exercise7.4-5

If we are only doing quick-sort until the problem size becomes≤k,then,we will have to take lg(n/k)steps,since,as in the original analysis of randomized quick sort,we expect there to be lg(n)levels to the recursion tree.Since we then just call quicksort on the entire array,we know that each element is within k of its?nal position.This means that an insertion sort will take the shifting of at most k elements for every element that needed to change position.This gets us the running time described.

In theory,we should pick k to minimize this expression,that is,taking a

derivative with respect to k,we want it to be evaluating to zero.So,n?n

k =0,

so k~1

n2.The constant of proportionality will depend on the relative size of

the constants in the nk term and in the n lg(n/k)term.In practice,we would try it with a large number of input sizes for various values of k,because there are gritty properties of the machine not considered here such as cache line size.

Exercise7.4-6

For simplicity of analysis,we will assume that the elements of the array A are the numbers1to n.If we let k denote the median value,the probability of getting at worst anαto1?αsplit is the probability thatαn≤k≤(1?α)n. The number of“bad”triples is equal to the number of triples such that at least two of the numbers come from[1,αn]or at least two of the numbers come from [(1?α)n,n].Since both intervals have the same size,the probability of a bad triple is2(α3+3α2(1?α)).Thus the probability of selecting a“good”triple,and thus getting at worst anαto1?αsplit,is1?2(α3+3α2(1?α))=1+4α3?6α2. Problem7-1

a.We will be calling with the parameters p=1,r=|A|=12.So,throughout,

x=13.

i j

13199512874112621013

61995128741121321111

61395128741121921210

61395128741121921102

And we do indeed see that partition has moved the two elements that are bigger than the pivot,19and21,to the two?nal positions in the array. b.We know that at the beginning of the loop,we have that i

it is true initially so long as|A|≥2.And if it were to be untrue at some iteration,then we would of left the loop in the prior iteration.To show that we won’t access outside of the array,we need to show that at the beginning of every run of the loop,there is a k>i so that A[k]≥x,and a k

5

i

i in the prior iteration of the loop,prior to doing the exchange on line12.

Similarly,for k .

c.If there is more than one run of the main loop,we have that j

it decreases by at least one with every iteration.

Note that at line11in the?rst run of the loop,we have that i=1because A[p]=x≥x.So,if we were to terminate after a single iteration of the main loop,we must also have that j=1

d.We will show the loop invariant that all the elements in A[p..i]are less than

or equal to x which is less than or equal to all the elements of A[j..r].It is trivially true prior to the?rst iteration because both of these sets of elements are empty.Suppose we just?nished an iteration of the loop during which j went from j1to j2,and i went from i1to i2.All the elements in A[i1+1..i2?1] were

Similarly,we have that all the elements in A[j2+1..j1?1]were>x.We have also that A[i2]≤x≤A[j2]after the exchange on https://www.360docs.net/doc/346476899.html,stly,by induction,we had that all the elements in A[p..i1]are less than or equal to x,and all the elements in A[j1..r]are greater than or equal to x.Then, putting it all together,since A[p..i2]=A[p..i1]∪A[i1+1..i2?1]∪{A[i2]}and A[j2..r]=∪{A[j2]}∪A[j2+1..j1?1]∪A[j1..r],we have the desired inequality.

Since at termination,we have that i≥j,we know that A[p..j]?A[p..i],and so,every element of A[p..j]is less than or equal to x,which is less than or equal to every element of A[j+1..r]?A[j..r].

e.After running Hoare-partition,we don’t have the guarantee that the pivot

value will be in the position j,so,we will scan through the list to?nd the pivot value,place it between the two subarrays,and recurse

Problem7-2

a.Since all elements are the same,the initial random choice of index and swap

change nothing.Thus,randomized quicksort’s running time will be the same as that of quicksort.Since all elements are equal,PARTITION(A,P,r)will always return r?1.This is worst-case partitioning,so the runtime isΘ(n2).

b.See the PARTITION’algorithm for modi?cations.

c.See the RANDOMIZED-PARTITION’algorithm for modi?cations.

d.Let d be the number of distinct elements in A.The running time is dominated

by the time spent in the PARTITION procedure,and there can be at most d calls to PARTITION.If X is the number of comparisons performed in line4 of PARTITION over the entire execution of QUICKSORT’,then the running

6

Quicksort(A,p,r)

1:if p

2:x=A[p]

3:q=HoareP artition(A,p,r)

4:i=0

5:while A[i]=x do

6:i=i+1

7:end while

8:if i≤q then

9:exchange A[i]and A[q]

10:else

11:exchange A[i]and A[q+1]

12:q=q+1

13:end if

14:Quicksort(A,p,q-1)

15:Quicksort(A,q+1,r)

16:end if

Algorithm1PARTITION’(A,p,r)

1:x=A[r]

2:exchange A[r]with A[p]

3:i=p?1

4:k=p

5:for j=p+1to r?1do

6:if A[j]

7:i=i+1

8:k=i+2

9:exchange A[i]with A[j]

10:exchange A[k]with A[j]

11:end if

12:if A[j]=x then

13:k=k+1

14:exchange A[k]with A[j]

15:end if

16:end for

17:exchange A[i+1]with A[r]

18:return i+1and k+1

Algorithm2RANDOMIZED-PARTITION’1:i=RANDOM(p,r)

2:exchange A[r]with A[i]

3:return PARTITION’(A,p,r)

7

Algorithm3QUICKSORT’(A,p,r)

1:if p

2:(q,t)=RANDOMIZED?P ART IT ION

3:QUICKSORT’(A,p,q-1)

4:QUICKSORT’(A,t+1,r)

5:end if

time is O(d+X).It remains true that each pair of elements is compared at most once.If z i is the i th smallest element,we need to compute the probability that z i is compared to z j.This time,once a pivot x is chosen with z i≤x≤z j,we know that z i and z j cannot be compared at any subsequent time.This is where the analysis di?ers,because there could be many elements of the array equal to z i or z j,so the probability that z i and z j are compared decreases.However,the expected percentage of distinct

elements in a random array tends to1?1

e ,so asymptotically the expected

number of comparisons is the same.

Problem7-3

a.Since the pivot is selected as a random element in the array,which has size n,

the probabilities of any particular element being selected are all equal,and

add to one,so,are all1

n .As such,E[X i]=Pr[i smallest is picked]=1

n

.

b.We can apply linearity of expectation over all of the events X i.Suppose we

have a particular X i be true,then,we will have one of the sub arrays be length i?1,and the other be n?i,and will of course still need linear time to run the partition procedure.This corresponds exactly to the summand in equation(7.5).

c.

E n

q=1

X q(T(q?1)+T(n?q)+Θ(n))

=

n

q=1

E[X q(T(q?1)+T(n?q)+Θ(n))]

=

n

q=1

(T(q?1)+T(n?q)+Θ(n))/n=Θ(n)+

1

n

n

q=1

(T(q?1)+T(n?q)) =Θ(n)+

1

n

n

q=1

T(q?1)+

n

q=1

T(n?q)

=Θ(n)+

1

n

n

q=1

T(q?1)+

n

q=1

T(q?1)

=Θ(n)+

2

n

n

q=1

T(q?1) =Θ(n)+

2

n

n?1

q=0

T(q)=Θ(n)+

2

n

n?1

q=2

T(q)

8

d.We will prove this inequality in a di?erent way than suggested by the hint.If

we let f(k)=k lg(k)treated as a continuous function,then f (k)=lg(k)+1.

Note now that the summation written out is the left hand approximation of the integral of f(k)from2to n with step size1.By integration by parts, the anti-derivative of k lg k is

1 ln(2)

k2

2

ln(k)?

k2

4

So,plugging in the bounds and subtracting,we get n2lg(n)

2?n2

4ln(2)

?1.

Since f has a positive derivative over the entire interval that the integral is being evaluated over,the left hand rule provides a underapproximation of the integral,so,we have that

n?1

k=2k lg(k)≤

n2lg(n)

2

?

n2

4ln(2)

?1≤

n2lg(n)

2

?

n2

8

where the last inequality uses the fact that ln(2)>1/2.

e.Assume by induction that T(q)≤q lg(q)+Θ(n).Combining(7.6)and(7.7),

we have

E[T(n)]=2

n

n?1

q=2

E[T(q)]+Θ(n)≤

2

n

n?1

q=2

(q lg(q)+T heta(n))+Θ(n)≤

2

n

n?1

q=2

(q lg(q))+

2

n

(nΘ(n))+Θ(n)

≤2

n

(

1

2

n2lg(n)?

1

8

n2)+Θ(n)=n lg(n)?

1

4

n+Θ(n)=n lg(n)+Θ(n)

Problem7-4

a.We’ll proceed by induction.For the base case,if A contains1element then

p=r so the algorithm terminates immediately,leave a single sorted element.

Now suppose that for1≤k≤n?1,TAIL-RECURSIVE-QUICKSORT cor-rectly sorts an array A containing k elements.Let A have size n.We set q equal to the pivot and by the induction hypothesis,TAIL-RECURSIVE-QUICKSORT correctly sorts the left subarray which is of strictly smaller size.Next,p is updated to q+1and the exact same sequence of steps follows as if we had originally called TAIL-RECURSIVE-QUICKSORT(A,q+1,n).

Again,this array is of strictly smaller size,so by the induction hypothesis it correctly sorts A[q+1...n]as desired.

9

b.The stack depth will be Θ(n )if the input array is already sorted.The right subarray will always have size 0so there will be n ?1recursive calls before the while-condition p

c.We modify the algorithm to make the recursive call on the smaller subarray to avoid building pushing too much on the stack:Algorithm 4MODIFIED-TAIL-RECURSIVE-QUICKSORT(A,p,r)1:while p

a.p i is the probability that a randomly selected subset of size three has the A [i ]as it’s middle element.There are 6possible orderings of the three ele-ments selected.So,suppose that S is the set of three elements selected.We will compute the probability that the second element of S is A [i ]among all possible 3-sets we can pick,since there are exactly six ordered 3-sets corre-sponding to each 3-set,these probabilities will be equal.We will compute the probability that S [2]=A [i ].For any such S ,we would need to select the ?rst element from [i ?1]and the third from {i +1,...,n }.So,there are

(i ?1)(n ?i )such 3-sets.The total number of 3-sets is n 3 =n (n ?1)(n ?2)

6.So,

p i =

6(n ?i )(i ?1)n (n ?1)(n ?2)

b.If we let i = n +12

,the previous result gets us an increase of 6( n ?12 )(n ? n +12

)n (n ?1)(n ?2)?

1n in the limit n going to in?nity,we get

lim n →∞

6( n ?12 )(n ? n +12 )

n (n ?1)(n ?2)

1n

=

32

10

c.To save the messiness,suppose n is a multiple of3.We will approximate the

sum as an integral,so,

2n/3

i=n/3p i≈

2n/3

n/3

6(?x2+nx+x?n)

n(n?1)(n?2)

dx=

6(?7n3/81+3n3/18+3n2/18?n2/3)

n(n?1)(n?2)

Which,in the limit n goes to in?nity,is13

27which is a constant that is larger

than1/3as it was in the original randomized quicksort implementation. d.Since the new algorithm always has a“bad”choice that is within a constant

factor of the original quicksort,it will still have a reasonable probability that the randomness leads us into a bad situation,so,it will still be n lg n. Problem7-6

a.Our algorithm will be essentially the same as the modi?ed randomized quick-

sort written in problem2.We sort the a i’s,but we replace the comparison operators to check for overlapping intervals.The only modi?cations needed are made in PARTITION,so we will just rewrite that here.For a given element x in position i,we’ll use x.a and x.b to denote a i and b i respectively. Algorithm5FUZZY-PARTITION(A,p,r)

1:x=A[r]

2:exchange A[r]with A[p]

3:i=p?1

4:k=p

5:for j=p+1to r?1do

6:if b j

7:i=i+1

8:k=i+2

9:exchange A[i]with A[j]

10:exchange A[k]with A[j]

11:end if

12:if b j≥x.a or a j≤x.b then

13:x.a=max(a j,x.a)and x.b=min(b j,x.b)

14:k=k+1

15:exchange A[k]with A[j]

16:end if

17:end for

18:exchange A[i+1]with A[r]

19:return i+1and k+1

When intervals overlap we treat them as equal elements,thus cutting down on the time required to sort.

11

b.For distinct intervals the algorithm runs exactly as regular quicksort does,so

its expected runtime will beΘ(n lg n)in general.If all of the intervals overlap then the condition on line12will be satis?ed for every iteration of the for loop.Thus the algorithm returns p and r,so only empty arrays remain to be sorted.FUZZY-PARTITION will only be called a single time,and since its runtime remainsΘ(n),the total expected runtime isΘ(n).

12

算法导论 第三版 第24章 答案 英

Chapter24 Michelle Bodnar,Andrew Lohr April12,2016 Exercise24.1-1 If we change our source to z and use the same ordering of edges to decide what to relax,the d values after successive iterations of relaxation are: s t x y z ∞∞∞∞0 2∞7∞0 25790 25690 24690 Theπvalues are: s t x y z NIL NIL NIL NIL NIL z NIL z NIL NIL z x z s NIL z x y s NIL z x y s NIL Now,if we change the weight of edge(z,x)to4and rerun with s as the source,we have that the d values after successive iterations of relaxation are: s t x y z 0∞∞∞∞ 06∞7∞ 06472 02472 0247?2 Theπvalues are: s t x y z NIL NIL NIL NIL NIL NIL s NIL s NIL NIL s y s t NIL x y s t NIL x y s t 1

Note that these values are exactly the same as in the worked example.The di?erence that changing this edge will cause is that there is now a negative weight cycle,which will be detected when it considers the edge(z,x)in the for loop on line5.Since x.d=4>?2+4=z.d+w(z,x),it will return false on line7. Exercise24.1-2 Suppose there is a path from s to v.Then there must be a shortest such path of lengthδ(s,v).It must have?nite length since it contains at most|V|?1 edges and each edge has?nite length.By Lemma24.2,v.d=δ(s,v)<∞upon termination.On the other hand,suppose v.d<∞when BELLMAN-FORD ter-minates.Recall that v.d is monotonically decreasing throughout the algorithm, and RELAX will update v.d only if u.d+w(u,v)

算法导论 第三版 第21章 答案 英

Chapter21 Michelle Bodnar,Andrew Lohr April12,2016 Exercise21.1-1 EdgeP rocessed initial{a}{b}{c}{d}{e}{f}{g}{h}{i}{j}{k} (d,i){a}{b}{c}{d,i}{e}{f}{g}{h}{j}{k} (f,k){a}{b}{c}{d,i}{e}{f,k}{g}{h}{j} (g,i){a}{b}{c}{d,i,g}{e}{f,k}{h}{j} (b,g){a}{b,d,i,g}{c}{e}{f,k}{h}{j} (a,h){a,h}{b,d,i,g}{c}{e}{f,k}{j} (i,j){a,h}{b,d,i,g,j}{c}{e}{f,k} (d,k){a,h}{b,d,i,g,j,f,k}{c}{e} (b,j){a,h}{b,d,i,g,j,f,k}{c}{e} (d,f){a,h}{b,d,i,g,j,f,k}{c}{e} (g,j){a,h}{b,d,i,g,j,f,k}{c}{e} (a,e){a,h,e}{b,d,i,g,j,f,k}{c} So,the connected that we are left with are{a,h,e},{b,d,i,g,j,f,k}, and{c}. Exercise21.1-2 First suppose that two vertices are in the same connected component.Then there exists a path of edges connecting them.If two vertices are connected by a single edge,then they are put into the same set when that edge is processed. At some point during the algorithm every edge of the path will be processed,so all vertices on the path will be in the same set,including the endpoints.Now suppose two vertices u and v wind up in the same set.Since every vertex starts o?in its own set,some sequence of edges in G must have resulted in eventually combining the sets containing u and v.From among these,there must be a path of edges from u to v,implying that u and v are in the same connected component. Exercise21.1-3 Find set is called twice on line4,this is run once per edge in the graph,so, we have that?nd set is run2|E|times.Since we start with|V|sets,at the end 1

算法导论第二章答案

第二章算法入门 由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。另,思考题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-1 5 while i > 0 and A[i] > key 6 do A[i+1]←A[i] 7 i ←i ? 1 8 A[i+1]←key C#对揑入排序算法的实现: public static void InsertionSort(T[] Input) where T:IComparable { 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-1

算法导论 第三版 第六章 答案 英

Chapter6 Michelle Bodnar,Andrew Lohr December31,2016 Exercise6.1-1 At least2h and at most2h+1?1.Can be seen because a complete binary tree of depth h?1hasΣh?1 i=02i=2h?1elements,and the number of elements in 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-2 Write 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 k leaves,which must have length m.It is clear from the way we de?ned m that m= lg n . Exercise6.1-3 If 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 subtree Exercise6.1-4 The 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-5 Yes,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. 1

算法导论 第三版 第七章 答案 英

Chapter7 Michelle Bodnar,Andrew Lohr April12,2016 Exercise7.1-1 13199512874212611 13199512874212611 13199512874212611 91913512874212611 95131912874212611 95131912874212611 95819121374212611 95871213194212611 95874131912212611 95874131912212611 95874219122113611 95874261221131911 95874261121131912 Exercise7.1-2 If all elements in the array have the same value,PARTITION returns r.To make PARTITION return q= (p+r)/2 when all elements have the same value,modify line4of the algorithm to say this:if A[j]≤x and j(mod2)= (p+1)(mod2).This causes the algorithm to treat half of the instances of the same value to count as less than,and the other half to count as greater than. Exercise7.1-3 The for loop makes exactly r?p iterations,each of which takes at most constant time.The part outside the for loop takes at most constant time.Since r?p is the size of the subarray,PARTITION takes at most time proportional to the size of the subarray it is called on. Exercise7.1-4 To modify QUICKSORT to run in non-increasing order we need only modify line4of PARTITION,changing≤to≥. 1

算法导论 第三版 第二章 答案 英

Chapter2 Michelle Bodnar,Andrew Lohr April12,2016 Exercise2.1-1 314159264158 314159264158 314159264158 263141594158 263141415958 263141415859 Exercise2.1-2 Algorithm1Non-increasing Insertion-Sort(A) 1:for j=2to A.length do 2:key=A[j] 3://Insert A[j]into the sorted sequence A[1..j?1]. 4:i=j?1 5:while i>0and A[i]

算法导论习题答案

Chapter2 Getting Start 2.1 Insertion sort 2.1.2 将Insertion-Sort 重写为按非递减顺序排序 2.1.3 计算两个n 位的二进制数组之和 2.2 Analyzing algorithms 当前n-1个元素排好序后,第n 个元素已经是最大的元素了. 最好时间和最坏时间均为2()n Θ 2.3 Designing algorithms 2.3.3 计算递归方程的解 22()2(/2)2,1k if n T n T n n if n for k =?=?+ = >? (1) 当1k =时,2n =,显然有()lg T n n n = (2) 假设当k i =时公式成立,即()lg 2lg 22i i i T n n n i ===?, 则当1k i =+,即12i n +=时, 2.3.4 给出insertion sort 的递归版本的递归式 2.3-6 使用二分查找来替代insertion-sort 中while 循环内的线性扫描,是否可以将算法的时间提高到(lg )n n Θ? 虽然用二分查找法可以将查找正确位置的时间复杂度降下来,但

是移位操作的复杂度并没有减少,所以最坏情况下该算法的时间复杂度依然是2()n Θ 2.3-7 给出一个算法,使得其能在(lg )n n Θ的时间内找出在一个n 元素的整数数组内,是否存在两个元素之和为x 首先利用快速排序将数组排序,时间(lg )n n Θ,然后再进行查找: Search(A,n,x) QuickSort(A,n); i←1; j←n; while A[i]+A[j]≠x and i,()()b b n a n +=Θ 0a >时,()()2b b b b n a n n n +<+= 对于121,2b c c ==,12()b b b c n n a c n <+< 0a <时,()b b n a n +<

算法导论 第三版 第十九章 答案 英

Chapter19 Michelle Bodnar,Andrew Lohr April12,2016 Exercise19.2-1 First,we take the subtrees rooted at24,17,and23and add them to the root list.Then,we set H.min to18.Then,we run consolidate.First this has its degree2set to the subtree rooted at18.Then the degree1is the subtree rooted at38.Then,we get a repeated subtree of degree2when we consider the one rooted at24.So,we make it a subheap by placing the24node under18. Then,we consider the heap rooted at17.This is a repeat for heaps of degree1, so we place the heap rooted https://www.360docs.net/doc/346476899.html,stly we consider the heap rooted at23,and then we have that all the di?erent heaps have distinct degrees and are done,setting H.min to the smallest,that is,the one rooted at17. The three heaps that we end up with in our root list are: 23 17 38 30 41 and 1

Ch10算法导论 第三版 第十章 答案 英

Chapter10 Michelle Bodnar,Andrew Lohr April12,2016 Exercise10.1-1 4 41 413 41 418 41 Exercise10.1-2 We will call the stacks T and R.Initially,set T.top=0and R.top=n+1. Essentially,stack T uses the?rst 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 then 2:if T.top+1==R.top then 3:error“over?ow” 4:else 5:T.top=T.top+1 6:T[T.top]=x 7:end if 8:end if 9:if S==R then 10:if R.top?1==T.top then 11:error“over?ow” 12:else 13:R.top=R.top?1 14:T[T.top]=x 15:end if 16:end if 1

Algorithm2POP(S) if S==T then if T.top==0then error“under?ow” else T.top=T.top?1. return T[T.top+1] end if end if if S==R then if R.top==n+1then error“under?ow” else R.top=R.top+1. return R[R.top?1] end if end if Exercise10.1-3 4 41 413 13 138 38 Exercise10.1-4 Algorithm3ENQUEUE if Q.head==Q.tail+1,or Q.head==1and Q.tail==Q.length then error“over?ow” end if Q[Q.tail]=x if Q.tail==Q.length then Q.tail=1 else Q.tail=Q.head+1 end if Exercise10.1-5 As in the example code given in the section,we will neglect to check for over?ow and under?ow errors. 2

算法导论 第八章答案

8.2-4 :在O(1)的时间内,回答出输入的整数中有多少个落在区间[a...b]内。给出的算法的预处理时间为O(n+k) 算法思想:利用计数排序,由于在计数排序中有一个存储数值个数的临时存储区C[0...k],利用这个数组即可。 #include using namespace std; //通过改编计数排序而来,因为有些部分需要注释掉 void counting_sort(int*&a, int length, int k, int*&b, int*&c); int main() { const int LEN =100; int*a =newint[LEN]; for(int i =0; i < LEN; i++) a[i] = (i -50)*(i -50) +4; int* b =new int[LEN]; const int k =2504; int* c =new int[k +1]; counting_sort(a, LEN, k, b, c); //这里需要注释掉 //for(int i = 0; i < LEN; i++) //cout<>m>>n) { if(m >n) cout<<"区间输入不对"< k && m >0) cout<<"个数为"< k && m <=0) cout<<"个数为"<= 0; i--) { b[c[a[i]] - 1] = a[i]; c[a[i]]--; }*/ } PS:计数排序的总时间为O(k+n),在实践中,如果当k = O(n)时,我们常常采用计数排序,

算法导论 第三版 第十六章 答案 英

Chapter16 Michelle Bodnar,Andrew Lohr April12,2016 Exercise16.1-1 The given algorithm would just stupidly compute the minimum of the O(n) numbers or return zero depending on the size of S ij.There are a possible number of subproblems that is O(n2)since we are selecting i and j so that 1≤i≤j≤n.So,the runtime would be O(n3). Exercise16.1-2 This becomes exactly the same as the original problem if we imagine time running in reverse,so it produces an optimal solution for essentially the same reasons.It is greedy because we make the best looking choice at each step. Exercise16.1-3 As a counterexample to the optimality of greedily selecting the shortest, suppose our activity times are{(1,9),(8,11),(10,20)}then,picking the shortest ?rst,we have to eliminate the other two,where if we picked the other two instead,we would have two tasks not one. As a counterexample to the optimality of greedily selecting the task that con?icts with the fewest remaining activities,suppose the activity times are {(?1,1),(2,5),(0,3),(0,3),(0,3),(4,7),(6,9),(8,11),(8,11),(8,11),(10,12)}.Then, by this greedy strategy,we would?rst pick(4,7)since it only has a two con- ?icts.However,doing so would mean that we would not be able to pick the only optimal solution of(?1,1),(2,5),(6,9),(10,12). As a counterexample to the optimality of greedily selecting the earliest start times,suppose our activity times are{(1,10),(2,3),(4,5)}.If we pick the ear-liest start time,we will only have a single activity,(1,10),whereas the optimal solution would be to pick the two other activities. Exercise16.1-4 Maintain a set of free(but already used)lecture halls F and currently busy lecture halls B.Sort the classes by start time.For each new start time which you encounter,remove a lecture hall from F,schedule the class in that room, 1

算法导论 第三版 第十七章 答案 英

Chapter17 Michelle Bodnar,Andrew Lohr April12,2016 Exercise17.1-1 It woudn’t because we could make an arbitrary sequence of MULT IP USH(k),MULT IP OP(k). The cost of each will beΘ(k),so the average runtime of each will beΘ(k)not O(1). Exercise17.1-2 Suppose the input is a1followed by k?1zeros.If we call DECREMENT we must change k entries.If we then call INCREMENT on this it reverses these k changes.Thus,by calling them alternately n times,the total time isΘ(nk). Exercise17.1-3 Note that this setup is similar to the dynamic tables discussed in section 17.4.Let n be arbitrary,and have the cost of operation i be c(i).Then, n i=1c(i)= lg(n) i=1 2i+ i≤n not a power of2 1≤ lg(n) i=1 2i+n=21+ lg(n) ?1+n≤4n?1+n≤5n∈O(n) So,since to?nd the average,we divide by n,the average runtime of each com-mand is O(1). Exercise17.2-1 To every stack operation,we charge twice.First we charge the actual cost of the stack operation.Second we charge the cost of copying an element later on.Since we have the size of the stack never exceed k,and there are always k operations between backups,we always overpay by at least enough.So,the ammortized cost of the operation is constant.So,the cost of the n operation is O(n). Exercise17.2-2 1

算法导论 第三版 第35章 答案 英

Chapter35 Michelle Bodnar,Andrew Lohr April12,2016 Exercise35.1-1 We could select the graph that consists of only two vertices and a single edge between them.Then,the approximation algorithm will always select both of the vertices,whereas the minimum vertex cover is only one vertex.more generally,we could pick our graph to be k edges on a graph with2k vertices so that each connected component only has a single edge.In these examples,we will have that the approximate solution is o?by a factor of two from the exact one. Exercise35.1-2 It is clear that the edges picked in line4form a matching,since we can only pick edges from E ,and the edges in E are precisely those which don’t share an endpoint with any vertex already in C,and hence with any already-picked edge. Moreover,this matching is maximal because the only edges we don’t include are the ones we removed from E .We did this because they shared an endpoint with an edge we already picked,so if we added it to the matching it would no longer be a matching. Exercise35.1-3 We will construct a bipartite graph with V=R∪L.We will try to construct it so that R is uniform,not that R is a vertex cover.However,we will make it so that the heuristic that the professor(professor who?)suggests will cause us to select all the vertices in L,and show that|L|>2|R|. Initially start o?with|R|=n?xed,and L empty.Then,for each i from 2up to n,we do the following.Let k= n i .Select S a subset of the vertices of R of size ki,and so that all the vertices in R?S have a greater or equal degree.Then,we will add k vertices to L,each of degree i,so that the union of their neighborhoods is S.Note that throughout this process,the furthest apart the degrees of the vertices in R can be is1,because each time we are picking the smallest degree vertices and increasing their degrees by1.So,once this has been done for i=n,we can pick a subset of R whose degree is one less than the rest of R(or all of R if the degrees are all equal),and for each vertex in 1

《算法导论2版》课后答案_加强版2

1 算法导论第三次习题课 2008.12.17

2 19.1-1 如果x 是根节点:degree[sibling[x]] > sibling[x] 如果x 不是根节点:degree[sibling[x]] = sibling[x] –119.1-3 略

3 19.2-2 过程略( union 操作) 19.2-3 (1)decrease-key (2)extract-min 过程略 19.2-6 算法思想:找到堆中最小值min ,用min-1代替-∞. [遍历堆中树的根节点]

4 15.1-1 15.1-2 略P195 或P329 15.1-4 f i [j]值只依赖f i [j-1]的值,从而可以从2n 压缩为2个。再加上f*、l*、l i [j]。 Print-station(l, I, j ) //i 为线路,j 为station if j>1 then Print-station(l, l i [j], j-1 ) print “line”I, “station”j;

5 15.2-1 略(见课本) 15.2-2 15.2-4 略 MATRIX-CHAIN-MULTIPLY(A, s, i, j) if j>i x= MATRIX-CHAIN-MULTIPLY(A, s, s(i,j), j) y= MATRIX-CHAIN-MULTIPLY(A, s, s(i,j)+1,j) return MATRIX-MULTIPLY(x, y) else return A i

6 15.3-1 (归纳法)递归调用 枚举15.3-2 没有效果,没有重叠子问题 15.3-4 略 (3)n Ο3/2(4/) n n Θ

相关文档
最新文档