USC算法导论作业
《算法导论》习题答案12、13、14章
![《算法导论》习题答案12、13、14章](https://img.taocdn.com/s3/m/c865dffafab069dc5022010e.png)
第9章 中位数和顺序统计学
9.3-2
大于x的数至少有3n/10-6, n≥140时,易证3n/10-6 ≥n/4 小于x的数同理。
9.3-4
通过比较得到第i小元素,每次保留比较信息。 在比较过程中比这个元素小的元素构成的集合即为i – 1个 小数集合,而比较过程中比这个元素大的元素则构成了n – i 个大元素集合。不需要增加比较次数。
Preprocessing(A,k) for i←0 to k do C[i]←0 for j←1 to length[A] do C[A[j]] ←C[A[j]]+1 for i←1 to k do C[i] ←C[i]+C[i-1] Query(C,k,a,b) if b<a or b<1 or a>k return 0 if a<1 then a=1 if b>k then b=k if a≠1 then return C[b]-C[a-1] else return C[b]
0 +1
k +1
k +1
( k +1) +1
第6章 堆排序
6.4-3 不论递增还是递减,时间均为O(nlgn) 6.4-4 最坏情况下,n-1次调用MAX-HEAPIFY,运 行时间为O(nlgn)
第6章 堆排序
6.5-3
HEAP-MINIMUM(A) if heap-size[A]<1 then error”heap underflow” else return A[1] HEAP-EXTRACT-MIN(A) if heap-size[A]<1 then error”heap underflow” min<-A[1] A[1]<-A[heap-size[A]] heap-size[A]<-heap-size[A]-1 MIN-HEAPIFY(A,1) return min HEAP-DECREASE-KEY(A,i,key) if key>A[i] then error A[i]<-key while i>1 and A[PARENT(i)>A[i] do exchange A[i]<->A[PARENT(i)] i<-PARENT(i) MIN-HEAP-INSERT(A,key) heap-size[A]<-heap-size[A]+1 A[heap-size[A]]<-+∞ HEAP-DECREASE-KEY(A,heap-size[A],key)
USC算法导论作业4
![USC算法导论作业4](https://img.taocdn.com/s3/m/98c85daab0717fd5360cdc47.png)
CSCI303Homework4Problem1(6.1-1):What are the minimum and maximum numbers of elements in a heap of height h?Solution1:A heap is a semi-complete binary tree,so the minimum number of elements in a heap of height h is2h,and the maximum number of elements in a heap of height h is2h+1−1.Problem2(6.1-6):Is the sequence 23,17,14,6,13,10,1,5,7,12 a max-heap?Solution2:The sequence is not a max-heap,because7is a child of6,but7>6.Problem3(6.2-1):Using Figure6.2as a model,illustrate the operation of Max-Heapify(A,3)on the array A= 27,17,3,16,13,10,1,5,7,12,4,8,9,10 .Solution3:Problem4(6.2-6):Show that the worst-case running time of Max-Heapify on a heap of size n isΩ(lg n).(Hint:For a heap with n nodes,give node values that cause Max-Heapify to be called recursively at every node on a path from the root down to a leaf.)Solution4:Consider a heap of n nodes where the root node has been changed to contain the smallest value of all the nodes.Now when we call Max-Heapify on the root,the value will have to be exchanged down with its child at every level,until it reaches the lowest level.This is because,after every swapping,the value will still be smaller than both its children(since it is the minimum),until it reaches the lowest level where it has no more children.In such a heap,the number of exchanges to max-heapify the root will be equal to the height of the tree,which is lg n.So the worst case running time isΩ(lg n).Using Figure 6.3as a model,illustrate the operation of Build-Max-Heap on the array A = 5,3,17,10,84,19,6,22,9 .Solution 5:17841910652293Show that the worst-case running time of Heapsort isΩ(n lg n).Solution6:We can see that Heapsort is a comparison-type sort,and we have shown that all comparison-type sorts must beΩ(n lg n).Problem7(6.5-7):The operation Heap-Delete(A,i)deletes the item in node i from heap A.Give an implementation of Heap-Delete that runs in O(lg n)time for an n-element max-heap.Solution7:Heap-Delete(A,i)A[i]↔A[length(A)]length(A)←length(A)−1Heapify(A,i)The algorithm deletes the element at node i,and replaces it with the last element.Then the algorithm runs Heapify from the node i.Thefirst two lines execute in constant time and Heapify runs in time O(lg n),so this algorithm runs in O(lg n)time.。
算法导论作业5答案概要
![算法导论作业5答案概要](https://img.taocdn.com/s3/m/75dc5b3a58fb770bf78a55b4.png)
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 �����������。
USC算法导论作业2
![USC算法导论作业2](https://img.taocdn.com/s3/m/0798843883c4bb4cf7ecd147.png)
Problem 1 (4.3-2): The recurrence T (n) = 7T (n/2) + n2 describes the running time of an algorithm A. A competing algorithm A has a running time of T (n) = aT (n/4) + n2 . What is the largest integer value for a such that A is asymptotically faster than A? Solution 1: By the master theorem, the worst-case asymptotic complexity of A is Θ(nlg 7 ) ≈ Θ(n2.80735 ), and the worst-case asymptotic complexity of A is Θ(nlog4 a ), if a > 16. For A to be asymptotically faster than A, log4 a < lg 7 = log4 49. Therefore, the largest integer value for a such that A is asymptotically faster than A is 48. Problem 2 (Derived from 4-1 and 4-4): Give asymptotic upper and lower bounds for T (n) in each of the following recurrences. Make your bounds as tight as possible, and justify your answers. a. T (n) = 2T (n/2) + n3 . b. T (n) = 16T (n/4) + n2 . c. T (n) = 7T (n/3) + n2 . d. T (n) = 7T (n/2) + n2 . √ e. T (n) = 2T (n/4) + n. f. T (n) = 3T (n/2) + n lg n. √ g. T (n) = 4T (n/2) + n2 n. h. T (n) = T (9n/10) + n. Solution 2: Use the master method to solve these recurrences. a. Case 3 of master theorem. T (n) = Θ(n3 ). b. Case 2 of master theorem. T (n) = Θ(n2 lg n). c. Case 3 of master theorem. T (n) = Θ(n2 ). d. Case 1 of master theorem. T (n) = Θ(nlg 7 ). √ e. Case 2 of master theorem. T (n) = Θ( n lg n). f. Case 1 of master theorem. T (n) = Θ(nlg 3 ). √ g. Case 3 of master theorem. T (n) = Θ(n2 n). h. Case 3 of master theorem. T (n) = Θ(n). Problem 3 (Derived from 4-1 and 4-4): Give asymptotic upper and lower bounds for T (n) in each of the following recurrences. Make your bounds as tight as possible, and justify your answers. You may assume that T (1) is a constant. a. T (n) = T (n − 1) + n.
算法导论课程作业答案
![算法导论课程作业答案](https://img.taocdn.com/s3/m/ef34f93711a6f524ccbff121dd36a32d7275c75f.png)
算法导论课程作业答案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。
《算法导论(第二版)》(中文版)课后答案
![《算法导论(第二版)》(中文版)课后答案](https://img.taocdn.com/s3/m/1192a52b647d27284b73511e.png)
5
《算法导论(第二版) 》参考答案 do z←y 调用之前保存结果 y←INTERVAL-SEARCH-SUBTREE(y, i) 如果循环是由于y没有左子树,那我们返回y 否则我们返回z,这时意味着没有在z的左子树找到重叠区间 7 if y≠ nil[T] and i overlap int[y] 8 then return y 9 else return z 5 6 15.1-5 由 FASTEST-WAY 算法知:
15
lg n
2 lg n1 1 2cn 2 cn (n 2 ) 2 1
4.3-1 a) n2 b) n2lgn c) n3 4.3-4
2
《算法导论(第二版) 》参考答案 n2lg2n 7.1-2 (1)使用 P146 的 PARTION 函数可以得到 q=r 注意每循环一次 i 加 1,i 的初始值为 p 1 ,循环总共运行 (r 1) p 1次,最 终返回的 i 1 p 1 (r 1) p 1 1 r (2)由题目要求 q=(p+r)/2 可知,PARTITION 函数中的 i,j 变量应该在循环中同 时变化。 Partition(A, p, r) x = A[p]; i = p - 1; j = r + 1; while (TRUE) repeat j--; until A[j] <= x; repeat i++; until A[i] >= x; if (i < j) Swap(A, i, j); else return j; 7.3-2 (1)由 QuickSort 算法最坏情况分析得知:n 个元素每次都划 n-1 和 1 个,因 为是 p<r 的时候才调用,所以为Θ (n) (2)最好情况是每次都在最中间的位置分,所以递推式是: N(n)= 1+ 2*N(n/2) 不难得到:N(n) =Θ (n) 7.4-2 T(n)=2*T(n/2)+ Θ (n) 可以得到 T(n) =Θ (n lgn) 由 P46 Theorem3.1 可得:Ω (n lgn)
USC算法导论作业3
![USC算法导论作业3](https://img.taocdn.com/s3/m/26da13f504a1b0717fd5dd47.png)
CSCI303Homework3Problem1(9-1):Given a set A of n numbers,we wish tofind the k largest in sorted order using a comparison-based algorithm.Find the algorithm that implements each of the following methods with the best asymptotic worst-case running time,and analyze the running time of the algorithms in terms of n and k.a.Sort the numbers,and list the k largest.b.Build a max-priority queue from the numbers,and call Extract-Max k times.e an order-statistic algorithm tofind the i th largest number,partition around that num-ber,and sort the k largest numbers.Solution1:a.Merge-Sort(A,1,n)return A[n−k...k]This algorithm takes only as long as it takes to Merge-Sort a list of n numbers,so its running time isΘ(n lg n).b.Build-Max-Heap(A)for i←1to kB[i]←Heap-Extract-Max(A)return BThis algorithmfirst calls Build-Max-Heap on A,which has worst-case asymptotic com-plexity O(n).Then it calls Heap-Extract-Max k times,each of which has worst-case asymptotic complexity O(lg n).So the worst-case asymptotic complexity for this algorithm is O(n+k lg n).c.i←Select(A,k)A[n]↔A[i]Partition(A)Merge-Sort(A,n−k,n)return A[n−k...k]This algorithmfirst calls Select,which has worst-case asymptotic complexity O(n), then calls Partition,which also has worst-case asymptotic complexity O(n),then calls Merge-Sort to sort just the last k elements,which has worst-case asymptotic complexity O(k lg k).So the worst-case asymptotic complexity for this algorithm is O(n+k lg k).Problem2(9.3-5):Suppose that you have a“black-box”worst-case linear-time median subroutine.Give a simple, linear-time algorithm that solves the selection problem for an arbitrary order statistic.Solution2:Simple-Select(A,p,r,i)if p=rreturn A[p]A[r]↔A[Index-Of-Median(A,p,r)] Partition(A,p,r)k← r−p+12if i=kreturn A[k]else if i<kreturn Simple-Select(A,1,k−1,i)elsereturn Simple-Select(A,k+1,r,i−k)Problem3(9.3-8):Let X[1,...,n]and Y[1,...,n]be two arrays,each containing n numbers already in sorted order. Give an O(lg n)-time algorithm tofind the median of all2n elements in arrays X and Y. Solution3:Two-List-Median(X,p,q,Y,s,t)mx←Index-Of-Median(X,p,q)my←Index-Of-Median(Y,s,t)X[mx]↔X[q]Y[my]↔Y[t]Partition(X,p,q)Partition(Y,s,t)if X[mx]=Y[my]return X[mx]else if X[mx]>Y[my]return Two-List-Median(X,p,mx−1,Y,my+1,t)elsereturn Two-List-Median(X,mx+1,q,Y,s,my−1)Problem4(8.1-1):What is the smallest possible depth of a leaf in a decision tree for a comparison sort?Solution4:Given an array A that contains n elements,the smallest possible depth of a leaf in a decision tree to sort A using a comparison-type sort is n−1.To verify that A is in sorted order takes n−1 comparisons,and if fewer comparisons are used then at least one element was not compared to any of the others,so that element might not be in the correct position.Problem 5(Derived from 8.1-4):You are given a sequence of n elements to sort and a number k such that k divides n .The input sequence consists of n/k subsequences,each containing k elements.The elements in a given subsequence are all smaller than the elements in the succeeding subsequence and larger than the elements in the preceding subsequence.Thus,all that is needed to sort the whole sequence of length n is to sort the k elements in each of the n/k subsequences.Show an Ω(n lg k )lower bound on the number of comparisons needed to solve this varient of the sorting problem using a comparison-type sorting algorithm.(Hint:It is not rigorous to simply combine the lower bounds for the individual subsequences.)Solution 5:We will construct a decision tree for this varient of the sorting problem and show that it has height at least n lg k .Each leaf of the decision tree corresponds to a permutation of the original sequence.How many permutations are there?Each subsequence has k !permutations,and there are n/k subsequences,so there are (k !)n/k permutations of the whole sequence.Thus the decision tree has (k !)n/k leaves.A binary tree with (k !)n/k leaves has height at least lg (k !)n/k .lg (k !)n/k =n/k lg(k !)=Θ(n/k ·k lg k )=Θ(n lg k )Therefore the lower bound on the number of comparisons needed to solve this varient of the sorting problem using a comparison-type sorting algorithm is Ω(n lg k ).。
《算法导论》习题答案
![《算法导论》习题答案](https://img.taocdn.com/s3/m/5bc52e28dd36a32d73758181.png)
n/2
n! nn , n! o(nn )
3.2.4 是否多项式有界 lg n !与 lg lg n !
设lgn=m,则 m! 2 m ( )m e2m ( )m em(ln m1) mln m1 nln ln n
∴lgn!不是多项式有界的。
T (n) O(lg n)
4.1.2 证明 T (n) 2T (n) n 的解为 O(n lg n)
设 T (n) c n lg n
T (n) 2c n lg n n c lg n n n c(n 1) lg(n / 2) n cn lg n c lg n cn n cn(lg n 1) n c(lg n 2n)
虽然用二分查找法可以将查找正确位置的时间复杂度降下来,但 是移位操作的复杂度并没有减少, 所以最坏情况下该算法的时间复杂 度依然是 (n2 )
2.3-7 给出一个算法, 使得其能在 (n lg n) 的时间内找出在一个 n 元
素的整数数组内,是否存在两个元素之和为 x
首先利用快速排序将数组排序,时间 (n lg n) ,然后再进行查找:
sin(n / 2) 2 1,所以 af (n / b) cf (n) 不满足。 2(sin n 2)
4.1.6 计算 T (n) 2T (
令 m lg n, T (2 ) 2T (2
m m/ 2
n ) 1 的解
) 1
令 T(n)=S(m),则 S (m) 2S (m / 2) 1 其解为 S (m) (m),T (n) S (m) (lg n)
4.2 The recursion-tree method 4.2.1 4.2.2 4.2.3 4.2.5 略
USC算法导论作业4
![USC算法导论作业4](https://img.taocdn.com/s3/m/9de2c81478563c1ec5da50e2524de518964bd326.png)
USC算法导论作业4CSCI303Homework4Problem1(6.1-1):What are the minimum and maximum numbers of elements in a heap of height h?Solution1:A heap is a semi-complete binary tree,so the minimum number of elements in a heap of height h is2h,and the maximum number of elements in a heap of height h is2h+1?1.Problem2(6.1-6):Is the sequence 23,17,14,6,13,10,1,5,7,12 a max-heap?Solution2:The sequence is not a max-heap,because7is a child of6,but7>6.Problem3(6.2-1):Using Figure6.2as a model,illustrate the operation of Max-Heapify(A,3)on the array A= 27,17,3,16,13,10,1,5,7,12,4,8,9,10 .Solution3:Problem4(6.2-6):Show that the worst-case running time of Max-Heapify on a heap of size n is?(lg n).(Hint:For a heap with n nodes,give node values that cause Max-Heapify to be called recursively at every node on a path from the root down to a leaf.)Solution4:Consider a heap of n nodes where the root node has been changed to contain the smallest value of all the nodes.Now when we call Max-Heapify on the root,the value will have to be exchanged down with its child at every level,until it reaches the lowest level.This is because,after every swapping,the value will still be smaller than both its children(since it is the minimum),until it reaches the lowest level where it has no more children.In such a heap,the number of exchanges to max-heapify the root will be equal to the height of the tree,which is lg n.So the worst case running time is?(lg n).Using Figure 6.3as a model,illustrate the operation of Build-Max-Heap on the array A = 5,3,17,10,84,19,6,22,9 .Solution 5:17841910652293Show that the worst-case running time of Heapsort is?(n lg n).Solution6:We can see that Heapsort is a comparison-type sort,and we have shown that all comparison-type sorts must be?(n lg n).Problem7(6.5-7):The operation Heap-Delete(A,i)deletes the item in node i from heap A.Give an implementation of Heap-Delete that runs in O(lg n)time for an n-element max-heap.Solution7:Heap-Delete(A,i)A[i]?A[length(A)]length(A)←length(A)?1Heapify(A,i)The algorithm deletes the element at node i,and replaces it with the last element.Then the algorithm runs Heapify from the node i.The?rst two lines execute in constant time and Heapify runs in time O(lg n),so this algorithm runs in O(lg n)time.。
算法导论(第二版)习题答案(英文版)
![算法导论(第二版)习题答案(英文版)](https://img.taocdn.com/s3/m/6a8905a50029bd64783e2c67.png)
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
算法导论习题答案
![算法导论习题答案](https://img.taocdn.com/s3/m/0b06054303020740be1e650e52ea551810a6c937.png)
算法导论习题答案算法导论习题答案算法导论是一本经典的计算机科学教材,讲述了算法设计与分析的基本原理。
在学习过程中,习题是不可或缺的一部分,通过解答习题可以帮助我们巩固所学的知识。
本文将针对算法导论中的一些习题进行解答,帮助读者更好地理解算法导论的内容。
习题1-1:证明对于任意两个实数a和b,有|a + b| ≤ |a| + |b|。
解答:根据绝对值的定义,我们可以将|a + b|、|a|和|b|分别表示为以下三种情况:1. 当a + b ≥ 0,a ≥ 0,b ≥ 0时,|a + b| = a + b,|a| = a,|b| = b。
此时,|a + b| ≤ |a| + |b| 成立。
2. 当a + b < 0,a < 0,b < 0时,|a + b| = -(a + b),|a| = -a,|b| = -b。
此时,|a + b| ≤ |a| + |b| 成立。
3. 当a + b ≥ 0,a < 0,b < 0时,|a + b| = a + b,|a| = -a,|b| = -b。
此时,|a + b| ≤ |a| + |b| 成立。
综上所述,无论a和b的取值如何,都有|a + b| ≤ |a| + |b| 成立。
习题2-1:证明插入排序的运行时间是O(n^2)。
解答:插入排序是一种简单直观的排序算法,它的基本思想是将待排序的元素一个个地插入到已排好序的序列中。
在最坏情况下,即待排序的序列是逆序排列时,插入排序的运行时间最长。
假设待排序的序列长度为n,那么第一次插入需要比较1次,第二次插入需要比较2次,依次类推,第n次插入需要比较n-1次。
总的比较次数为1 + 2 + 3+ ... + (n-1) = n(n-1)/2。
因此,插入排序的运行时间是O(n^2)。
习题3-1:证明选择排序的运行时间是O(n^2)。
解答:选择排序是一种简单直观的排序算法,它的基本思想是每次从待排序的序列中选择最小的元素,放到已排序序列的末尾。
算法导论第二次作业答案
![算法导论第二次作业答案](https://img.taocdn.com/s3/m/25452ffd998fcc22bcd10d7b.png)
Solution: First, let’s analyze the Activity Selection Problem again: This is a problem using greedy algorithm: Input: 1. n activities a1, a2, . . . , an; 2. for i = 1, 2, . . . , n, the activity ai has a start time si and a finish time fi: [si, fi) Output: Pick a maximum set of activities that are compatible in time.
Solution: First, let’s analyze the Huffman Code again:
This is a problem using greedy algorithm:
Input: 1. n symbols s1, s2, . . . , sn ; 2. every symbol si has a frequency fi
Assume the time period of each activity is shown as following table:
i
123
si
157
fi
469
duration 3 1 2
We will choose the a2 which has the least duration among all three activities. However, it is obvious that the best arrangement is to choose {a1, a3}. So the approach of selecting the activity of least duration from among those that are compatible with previously selected activities does not work.
算法导论习题
![算法导论习题](https://img.taocdn.com/s3/m/498b478d02d276a200292ec1.png)
//在合并排序中对小数组采用插入排序#include<stdio.h>void main(){void MERGE_SORT(int a[],int p,int r,int k);int a[12]; //={3,0,1,10,9,5,4,12,7,8,2,6};int k=3,n=12;int i,j,s;int tmp=0;printf("请输入12个正整数:\n");for(i=0;i<12;i++)scanf("%d",&a[i]);for(i=0;i<=3;i++){for(j=i*3+1;j<i*3+3;j++){s=j;while(s>=i*3+1){if(a[s]<a[s-1])tmp=a[s],a[s]=a[s-1],a[s-1]=tmp;s--;}}}printf("第一步对4个长度3的子列表进行插入排序的结果为:\n");for(i=0;i<12;i++)printf("%d,",a[i]);printf("\n");MERGE_SORT(a,0,3,3);printf("第二步对4个子列表进行合并排序的结果为:\n");for(i=0;i<12;i++)printf("%d,",a[i]);printf("\n");} void MERGE_SORT(int a[],int p,int r,int k) {void MERGE(int a[],int p,int q,int r,int k);int q;if(p<r){q=(p+r)/2;MERGE_SORT(a,p,q,k);MERGE_SORT(a,q+1,r,k);MERGE(a,p,q,r,k);}}void MERGE(int a[],int p,int q,int r,int k) {int n1=(q-p+1)*k,n2=(r-q)*k;int i,j,s;int *L=new int[n1];int *R=new int[n2];for(i=0;i<n1;i++)L[i]=a[p*k+i];for(j=0;j<n2;j++)R[j]=a[(q+1)*k+j];i=0;j=0;for(s=p*3;s<=(r+1)*3-1;s++){if(i>n1-1)a[s]=R[j++];else if(j>n2-1)a[s]=L[i++];else if(L[i]<R[j])a[s]=L[i++];elsea[s]=R[j++];}}//用分治法在数组中查找逆序对#include<stdio.h>void main(){int count_inversion(int a[],int p,int r);int a[5]={5,4,3,2,1};printf("数组的逆序对是%d个\n",count_inversion(a,0,4));}int merge_inversion(int a[],int p,int q,int r){int n1=q-p+1;int n2=r-q;int *L=new int[n1];int *R=new int[n2];int i,j,k,v;for(i=0;i<n1;++i)L[i]=a[p+i];for(j=0;j<n2;++j)R[j]=a[q+1+j];i=0;j=0;v=0;for(k=p;k<=r;++k){if(i>n1-1)a[k]=R[j++];else if(j>n2-1)a[k]=L[i++];else if(L[i]>R[j]){a[k]=R[j++];v+=n1-i;}elsea[k]=L[i++];}delete L;delete R;return v;}int count_inversion(int a[],int p,int r){int v=0,q;if(p<r){q=(p+r)/2;v+=count_inversion(a,p,q);v+=count_inversion(a,q+1,r);v+=merge_inversion(a,p,q,r);}return v;}//用插入方法建堆#include"stdio.h"void HEAP_INCREASE_KEY(int a[],int i,int key) {int tmp;if(key>a[i-1])a[i-1]=key;while(i>1&&a[i/2-1]<a[i-1]){tmp=a[i/2-1],a[i/2-1]=a[i-1],a[i-1]=tmp;i=i/2;}}void MAX_HEAP_INSERT(int a[],int key,int heap_size){heap_size+=1;a[heap_size-1]=0;HEAP_INCREASE_KEY(a,heap_size,key); }void BUILD_MAX_HEAP(int a[],int lengh){int heap_size=1;int i;for(i=2;i<=lengh;i++){MAX_HEAP_INSERT(a,a[i-1],heap_size);heap_size++; //堆的长度要随着循环的次数增长}}void main(){int j;int a[10]={15,84,62,16,29,35,6,18,9,17};BUILD_MAX_HEAP(a,10);for(j=0;j<10;j++)printf("%d\n",a[j]);}#include"stdio.h"void MAX_D_HEAPIFY(int a[],int i,int d,int heap_size){int n=d,j,largest;int tmp;int *child=new int[n];for(j=0;j<n;j++)child[j]=(i-1)*d+2+j;if(child[0]<=heap_size&&a[child[0]-1]>a[i-1])largest=child[0];elselargest=i;for(j=1;j<n;j++){if(child[j]<=heap_size&&a[child[j]-1]>a[largest-1])largest=child[j];}if(largest!=i){tmp=a[largest-1],a[largest-1]=a[i-1],a[i-1]=tmp;MAX_D_HEAPIFY(a,largest,d,heap_size);}}void BUILD_MAX_D_HEAP(int a[],int d,int heap_size){int i,j;j=heap_size%d;if(j==0||j==1)i=heap_size/d;elsei=heap_size/d+1;//由叶子节点求父节点有两种情况for(i;i>=1;i--)MAX_D_HEAPIFY(a,i,d,heap_size);}int EXTRACT_MAX(int a[],int d,int heap_size) {int tmp;tmp=a[heap_size-1];a[heap_size-1]=a[0];a[0]= tmp;heap_size--;MAX_D_HEAPIFY(a,1,d,heap_size);return a[heap_size];}void main(){inta[20]={52,47,16,58,23,26,14,18,59,68,47,19,35,29, 61,82,74,75,98,81};// int b[18]={25,11,15,9,8,17,21,40,18,11,10,20,14,15,19, 21,7,10};int d=5,j,largest;BUILD_MAX_D_HEAP(a,5,20);// BUILD_MAX_D_HEAP(b,5,18);for(j=0;j<20;j++)printf("%d\n",a[j]);largest=EXTRACT_MAX(a,5,20);for(j=0;j<20;j++)printf("%d\n",a[j]);printf("%d\n",largest);/* for(j=0;j<18;j++)printf("%d\n",b[j]);*/#include"stdio.h"void MAX_D_HEAPIFY(int a[],int i,int d,int heap_size){int n=d,j,largest;int tmp;int *child=new int[n];for(j=0;j<n;j++)child[j]=(i-1)*d+2+j;if(child[0]<=heap_size&&a[child[0]-1]>a[i-1])largest=child[0];elselargest=i;for(j=1;j<n;j++){if(child[j]<=heap_size&&a[child[j]-1]>a[largest-1])largest=child[j];}if(largest!=i){tmp=a[largest-1],a[largest-1]=a[i-1],a[i-1]=tmp;MAX_D_HEAPIFY(a,largest,d,heap_size);}}void BUILD_MAX_D_HEAP(int a[],int d,int heap_size){int i,j;j=heap_size/d;if(j==0||j==1)i=heap_size/d;elsei=heap_size/d+1;//由叶子节点求父节点有两种情况for(i;i>=1;i--)MAX_D_HEAPIFY(a,i,d,heap_size);}void HEAP_INCREASE_KEY(int a[],int i,int d,int key){int tmp,j;if(a[i-1]<=key)a[i-1]=key;while(i>1){if(i%d==0||i%d==1)j=i/d;elsej=i/d+1;if(a[j-1]<a[i-1]){tmp=a[j-1],a[j-1]=a[i-1],a[i-1]=tmp;i=j;}else break;}}void INSERT(int a[],int key,int d,int heap_size) {heap_size+=1;a[heap_size-1]=0;HEAP_INCREASE_KEY(a,heap_size,d,key); }void main(){inta[20]={52,47,16,58,23,26,14,18,59,68,47,19,35,29, 61,82,74,75,98,81};int j,s=0;BUILD_MAX_D_HEAP(a,5,19);for(j=0;j<20;j++){printf("%d,",a[j]);s+=1;if(s%6==0)printf("\n");}INSERT(a,a[19],5,19);s=0;printf("\n");for(j=0;j<20;j++){printf("%d,",a[j]);s+=1;if(s%6==0)printf("\n");}}#include"stdio.h"void MAX_D_HEAPIFY(int a[],int i,int d,int heap_size){int n=d,j,largest;int tmp;int *child=new int[n];for(j=0;j<n;j++)child[j]=(i-1)*d+2+j;if(child[0]<=heap_size&&a[child[0]-1]>a[i-1])largest=child[0];elselargest=i;for(j=1;j<n;j++){if(child[j]<=heap_size&&a[child[j]-1]>a[largest-1])largest=child[j];}if(largest!=i){tmp=a[largest-1],a[largest-1]=a[i-1],a[i-1]=tmp;MAX_D_HEAPIFY(a,largest,d,heap_size);}}void BUILD_MAX_D_HEAP(int a[],int d,int heap_size){int i,j;j=heap_size/d;if(j==0||j==1)i=heap_size/d;elsei=heap_size/d+1;//由叶子节点求父节点有两种情况for(i;i>=1;i--)MAX_D_HEAPIFY(a,i,d,heap_size);}void HEAP_DECREASE_KEY(int a[],int i,int d,int key,int heap_size){if(a[i-1]>=key)a[i-1]=key;MAX_D_HEAPIFY(a,i,d,heap_size);}void main(){inta[20]={52,47,16,58,23,26,14,18,59,68,47,19,35,29, 61,82,74,75,98,81};int key=1,s=0,j;BUILD_MAX_D_HEAP(a,5,20);for(j=0;j<20;j++){printf("%d,",a[j]);s+=1;if(s%6==0)printf("\n");}printf("\n");s=0;HEAP_DECREASE_KEY(a,3,5,key,20);for(j=0;j<20;j++){printf("%d,",a[j]);s+=1;if(s%6==0)printf("\n");}}#include"stdio.h"void main(){//int a[10]={6,4,12,7,9,11,5,13,18,8};int a[10]={20,18,17,14,16,10,8,9,8,15};int i=9,j;int heap_size;void BULD_MAX_HEAP(int a[]);int HEAP_DELETE(int a[],int i);BULD_MAX_HEAP(a);heap_size=HEAP_DELETE(a,i);printf("删除第i个元素后的堆是:\n");for(j=0;j<heap_size;j++)printf("%d\n",a[j]);}void BULD_MAX_HEAP(int a[]){void MAX_HEAPIFY(int a[],int j,int heap_size);int heap_size=10;int j;for(j=4;j>=0;j--)MAX_HEAPIFY(a,j,heap_size);printf("堆a是:\n");for(j=0;j<heap_size;j++)printf("%4d",a[j]);printf("\n");}void MAX_HEAPIFY(int a[],int j,int heap_size) {int left=2*(j+1);int right=2*(j+1)+1;//结点与数组下标之间要转换int largest=0,temp;if(left<=heap_size&&a[left-1]>a[j])largest=left-1;elselargest=j;if(right<=heap_size&&a[right-1]>a[largest])largest=right-1;if(largest!=j){temp=a[largest];a[largest]=a[j];a[j]=temp;MAX_HEAPIFY(a,largest,heap_size);}}int HEAP_DELETE(int a[],int i){int temp,key=a[9],key1=a[i-1];int heap_size=10;temp=a[9];a[9]=a[i-1];a[i-1]=temp;heap_size--;if(key>key1){while(i>1&&a[i/2-1]<a[i-1])//如果a[9]大于i结点的值,则通过不断与父结点的比较//来确它的位置{temp=a[i/2-1],a[i/2-1]=a[i-1],a[i-1]=temp;i=i/2;}}elseMAX_HEAPIFY(a,i-1,heap_size);//如果a[9]比i结点的值要小,则从i结点开始堆维护return heap_size;}//建立最小堆#include"stdio.h"void MIN_HEAPIFY(int a[],int i,int heap_size){int small,tmp;int left=2*i,right=2*i+1;if(left<=heap_size&&a[left-1]>a[i-1])small=left;elsesmall=i;if(right<=heap_size&&a[right-1]>a[small-1]) small=right;if(small!=i){tmp=a[small-1],a[small-1]=a[i-1],a[i-1]=tmp;MIN_HEAPIFY(a,small,heap_size);}}void BUILD_MIN_HEAP(int a[],int heap_size) {int i;for(i=(heap_size/2);i>=1;i--)MIN_HEAPIFY(a,i,heap_size);}void HEAPSORT(int a[],int lengh){int i,tmp;int heap_size=lengh;BUILD_MIN_HEAP(a,heap_size);for(i=lengh;i>=2;i--){tmp=a[i-1],a[i-1]=a[0],a[0]=tmp;heap_size--;MIN_HEAPIFY(a,1,heap_size);}}void main(){int a[10]={23,6,21,3,7,5,8,54,14,10};int i;HEAPSORT(a,10);for(i=0;i<10;i++)printf("%d\n",a[i]);}//PARTITION的最初版本#include"stdio.h" int HOARE_PARTITION(int a[],int p,int r){int x,tmp;int i,j;x=a[p-1];i=p-1;j=r+1;while(1){while(a[--j-1]>x);while(a[++i-1]<x);if(i<j)tmp=a[i-1],a[i-1]=a[j-1],a[j-1]=tmp;elsereturn j;}}void QUICK_SORT(int a[],int p,int r){int q;if(p<r){q=HOARE_PARTITION(a,p,r);QUICK_SORT(a,p,q);QUICK_SORT(a,q+1,r);}}void main(){int i;inta[20]={10,58,46,23,26,48,47,59,68,23,12,19,17,24, 43,81,76,72,98,46};QUICK_SORT(a,1,20);for(i=0;i<20;i++)printf("%d\n",a[i]);/*对插入排序来说,当其输入已“几乎”排好序时,运行时间是很快的。
算法导论第十五章习题答案
![算法导论第十五章习题答案](https://img.taocdn.com/s3/m/d15c713b1611cc7931b765ce05087632311274dd.png)
算法导论第十五章习题答案算法导论第十五章习题答案算法导论是一本经典的计算机科学教材,其中第十五章涵盖了图算法的内容。
本文将针对该章节中的习题进行解答,并对其中一些问题进行深入探讨。
1. 习题15.1-1题目要求证明:对于任意的有向图G=(V,E),如果图中不存在从节点u到节点v的路径,则在每个强连通分量中,节点u和节点v都在同一个强连通分量中。
证明:假设存在一个强连通分量C,其中节点u在C中,节点v在C'中(C'为除了C之外的其他强连通分量)。
由于不存在从u到v的路径,所以在C中不存在从u到v的路径。
但是根据强连通分量的定义,C中的任意两个节点之间都存在路径。
所以存在一条从v到u的路径。
这与C'中的节点v不在C中矛盾,所以假设不成立,节点u和节点v必定在同一个强连通分量中。
2. 习题15.2-2题目要求证明:在一个有向无环图中,存在一个拓扑排序,使得任意两个非根节点u和v,u在v之前。
证明:假设存在一个有向无环图G=(V,E),不存在上述所要求的拓扑排序。
即对于任意的拓扑排序,存在两个非根节点u和v,u在v之后。
那么我们可以得到一条从u到v的路径。
由于图中不存在环,所以路径上的节点不会重复。
我们可以将路径上的节点按照拓扑排序的顺序排列,得到一个新的拓扑排序,使得u在v之前。
这与假设矛盾,所以原命题成立。
3. 习题15.3-3题目要求证明:在一个有向图G=(V,E)中,如果存在一条从节点u到节点v的路径,那么在图的转置G^T中,存在一条从节点v到节点u的路径。
证明:假设存在一条从节点u到节点v的路径。
那么在图的转置G^T中,边(u,v)变成了边(v,u)。
所以存在一条从节点v到节点u的路径。
因此,原命题成立。
4. 习题15.4-1题目要求:给出一个算法,判断一个有向图G=(V,E)是否是有向无环图。
算法思路:我们可以使用深度优先搜索(DFS)来判断是否存在环。
具体步骤如下:1. 对于图中的每个节点v,设置一个状态标记visited[v]为false。
算法导论作业3答案
![算法导论作业3答案](https://img.taocdn.com/s3/m/b59c1b12a2161479171128a7.png)
Introduction to Algorithm s Day 14 Massachusetts Institute of Technology 6.046J/18.410J Singapore-MIT Alliance SMA5503 Professors Erik Demaine, Lee Wee Sun, and Charles E. Leiserson Handout 17Problem Set 3 SolutionsMIT students: This problem set is due in lecture on Day 11.Reading: Chapters 8 and 9Both exercises and problems should be solved, but only the problems should be turned in. Exercises are intended to help you master the course material. Even though you should not turn in the exercise solutions, you are responsible for material covered by the exercises.Mark the top of each sheet with your name, the course number, the problem number, your recitation instructor and time, the date, and the names of any students with whom you collaborated. MIT students: Each problem should be done on a separate sheet (or sheets) of three-hole punched paper.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 your essay should provide the following:1. A description of the algorithm in English and, if helpful, pseudocode.2. At least one worked example or diagram to show more precisely how your algorithm works.3. A proof (or indication) of the correctness of the algorithm.4. An analysis of the running time of the algorithm.Remember, your goal is to communicate. Graders will be instructed to take off points for convoluted and obtuse descriptions.Exercise 3-1. Do exercise 8.1-2 on page 167 of CLRS.Exercise 3-2. Do exercise 8.1-3 on page 168 of CLRS.Exercise 3-3. Do exercise 8.2-3 on page 170 of CLRS.Exercise 3-4. Do exercise 8.4-2 on page 177 of CLRS.Exercise 3-5. Do exercise 9.3-1 on page 192 of CLRS.Exercise 3-6. Show that the second smallest of n elements can be found with n+Θ(lg n)comparisons in the worst case. (Hint: Also find the smallest element.)Problem 3-1. Largest i numbers in sorted orderGiven a set of n numbers, we wish to find the i largest in sorted order using a comparison-based algorithm. Find the algorithm that implements each of the following methods with the best asymptotic worst-case running time, and analyze the running times of the algorithms in terms of n and i.(a) Sort the numbers, and list the i largest.Solution:Use any optimal sorting algorithm, such as MergeSort or HeapSort. Then this can bedone in Θ(n lg n).(b) Build a max-priority queue from the numbers, and call E XTRACT-M AX i times.Solution:Call Build-Heap, Θ(n). Then call Extract-Max, Θ(lg i), i times. So, total runningtime is Θ(n+i lg i).(c) Use an order-statistic algorithm to find the i th largest number, partition around thatnumber, and sort the i largest numbers.Solution:Select the i-th largest number using SELECT, Θ(n), call partition, Θ(n), and then sortthe i largest numbers, Θ(i lg i). So our algorithm takes Θ(n+i lg i).Problem 3-2. At the wading poolYou work at a summer camp which holds regular outings for the n children which attend. One of these outings is to a nearby wading pool which always turns out to be something of a nightmare at the end because there are n wet, cranky children and a pile of 2n shoes (n left shoes and n right shoes) and it is not at all clear which kids go with which shoes. Not being particularly picky, all you care about is getting kids into shoes that fit. The only way to determine if a shoe is a match for a child is to try the shoe on the child’s foot. After trying on the shoe, you will know that it either fits, is too big, or is too small. It is important to note that you cannot accurately compare children’s feet directly with each other, nor can you compare the shoes. You know that for every kid, there are at least two shoes (one left shoe and one right shoe) that will fit, and your task is to shoe all of the children efficiently so that you can go home. There are enough shoes that each child will find a pair which fits her. Assume that each comparison (trying a shoe on a foot) takes one time unit.(a) Describe a deterministic algorithm that uses Θ(n 2) comparisons to pair children withshoes.Solution:For each child, try on all the shoes until you find the two shoes that fit. T (n )= T (n − 2) + O (n ) = Θ(n 2).(b) Prove a lower bound of Ω(n lg n ) for the number of comparisons that must be madeby an algorithm solving this problem. (Hint: How many leaves does the decision tree have?)Solution:There are n ! ways that left shoes can be assigned to children and n ! ways that right shoes can be assigned to children. So the decision tree should have n !2 leaves. n !2 ≥ n ! h ≥ lg(n !)h ≥ lg ( ne )n by Stirling’s Approximation = n lg n − n lg e= Ω(n lg n )(c) How might you partition the children into those with a smaller shoe size than a “pivot”child, and those with a larger shoe size than the pivot child?Solution:Take the pivot child and try on all the shoes until you find one that fits. This should take Θ(n ) time as there are 2n shoes. Then try the shoe on all the children. If the shoe is too small, then they have larger feet than the pivot child. If the shoe is too big, then they have smaller feet than the pivot child. This should also take Θ(n ) time making our partition algorithm run in linear time.(d) Give a randomized algorithm whose expected number of comparisons is O (n lg n ),and prove that this bound is correct. What is the worst-case number of comparisons for your algorithm?Solution:This is similar to quicksort. Pick a random child. Partition the children around that child as in part (c). Then take the shoe you used to partition the children and partition the shoes around it. Take the two shoes and pivot child and put them in the group of paired children. Then recurse on the two groups of shoes and children. This should have the same analysis as randomized quicksort because we have only added an extra call to partition which will still make the work done at each level Θ(n ).。
《算法导论》习题答案
![《算法导论》习题答案](https://img.taocdn.com/s3/m/94db00f13086bceb19e8b8f67c1cfad6195fe917.png)
《算法导论》习题答案Chapter2 Getting Start2.1 Insertion sort2.1.2 将Insertion-Sort重写为按非递减顺序排序2.1.3 计算两个n位的二进制数组之和2.2 Analyzing algorithms2.2.1将函数用符号表示2.2.2写出选择排序算法selection-sort 当前n-1个元素排好序后,第n个元素已经是最大的元素了.最好时间和最坏时间均为2.3 Designing algorithms计算递归方程的解(1) 当时,,显然有T((2) 假设当时公式成立,即,则当,即时,2.3.4 给出insertion sort的递归版本的递归式2.3-6 使用二分查找来替代insertion-sort中while循环j?n;if A[i]+A[j]<xi?i+1elsej?j-1if A[i]+A[j]=xreturn trueelsereturn false时间复杂度为。
或者也可以先固定一个元素然后去二分查找x减去元素的差,复杂度为。
Chapter3 Growth of functions3.1Asymptotic notation3.1.2证明对于b时,对于,时,存在,当时,对于,3.1-4 判断与22n是否等于O(2n)3.1.6 证明如果算法的运行时间为,如果其最坏运行时间为O(g(n)),最佳运行时间为。
最坏时间O(g(n)),即;最佳时间,即3.1.7:证明定义3.2 Standard notation and common functions 3.2.2 证明证明当n>4时,,是否多项式有界~与设lgn=m,则?lgn~不是多项式有界的。
mememmmm2设,,是多项式有界的3.2.5比较lg(lg*n)与lg*(lgn)lg*(lgn)= lg*n-1设lg*n=x,lgx<x-1较大。
算法导论附录a习题答案
![算法导论附录a习题答案](https://img.taocdn.com/s3/m/7cd417846037ee06eff9aef8941ea76e59fa4a4c.png)
算法导论附录a习题答案算法导论附录A习题答案算法导论是一本经典的计算机科学教材,被广泛应用于计算机科学和工程的教育和研究领域。
附录A是该书中的一个重要部分,提供了一系列习题,用于帮助读者巩固和应用书中所讲述的算法概念和理论。
本文将回答附录A中的一些习题,旨在帮助读者更好地理解和运用算法导论中的知识。
习题1:给定一个由n个整数构成的数组A,设计一个算法,找到数组中的两个元素,使得它们的和等于给定的值x。
解答:可以使用哈希表来解决这个问题。
首先,遍历一遍数组A,将每个元素插入哈希表中。
然后,再次遍历数组A,对于每个元素a,计算目标值x与a的差值diff。
检查哈希表中是否存在diff,如果存在,则找到了满足条件的两个元素。
习题2:给定一个由n个整数构成的数组A,设计一个算法,找到数组中的一个元素,使得它出现的次数超过数组长度的一半。
解答:可以使用摩尔投票算法来解决这个问题。
首先,假设数组中的第一个元素为候选元素,初始化计数器count为1。
然后,遍历数组,对于每个元素a,如果a与候选元素相同,则计数器加1;否则,计数器减1。
如果计数器减到0,则将当前元素设为候选元素,并将计数器重置为1。
最后,返回候选元素即可。
习题3:给定一个由n个整数构成的数组A,设计一个算法,找到数组中的一个元素,使得它出现的次数严格大于n/3。
解答:可以使用摩尔投票算法的变种来解决这个问题。
首先,假设数组中的前两个元素为候选元素1和候选元素2,初始化计数器count1和count2为0。
然后,遍历数组,对于每个元素a,如果a与候选元素1相同,则计数器count1加1;如果a与候选元素2相同,则计数器count2加1;如果count1为0,则将当前元素设为候选元素1,并将计数器count1重置为1;如果count2为0,则将当前元素设为候选元素2,并将计数器count2重置为1。
最后,再次遍历数组,统计候选元素1和候选元素2的出现次数,如果其中一个元素的出现次数严格大于n/3,则返回该元素。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
CSCI 303Homework 1
Problem 1(2.1-1):
Using Figure 2.2as a model,illustrate the operation of Insertion-Sort on the array A = 31,41,59,26,41,58 .
Solution 1:
265841594131Problem 2(2.2-1):
Express the function n 3/1000−100n 2−100n +3in terms of Θ-notation.
Solution 2:
n 3/1000−100n 2−100n +3=Θ(n 3)
Problem 3(Derived from 2.2-2):
Consider sorting n numbers stored in array A by first finding the smallest element of A and exchanging it with the element in A [1].Then find the second smallest element of A ,and exchange it with A [2].Continue in this manner for the first n −1elements of A .Write pseudocode for this algorithm,which is known as Selection-Sort .Give the worst-case running times of selection sort in Θ-notation.
Solution 3:
Selection-Sort (A )
for i ←1to length [A ]
do min-value ←A [i ]
min-index =i
for j =i +1to length [A ]
do if A [j ]≤min-value
min-value =A [j ]
min-index =j
A [i ]↔A [min-index ]
The worst-case running time of Selection-Sort is Θ(n 2).
Using Figure2.4as a model,illustrate the operation of merge sort on the array A= 3,41,52,26,38,57,9,49 . Solution4:
Sorted Sequence
Initial Sequence
Problem5(Derived from1.2-2):
Suppose we are comparing two sorting algorithms.Suppose that for all inputs of size n,thefirst algorithm runs in8n2seconds,while the second algorithm runs in64n lg n seconds.For which
values of n does thefirst algorithm beat the second algorithm?
Solution5:
Thefirst algorithm beats the second algorithm if8n2<64n lg n.For this to happen,n<8lg n.
This is true for2≤n≤43.
Problem6(1.2-3):
What is the smallest value of n such that an algorithm whose running time is100n2runs faster
than an algorithm whose running time is2n?
Solution6:
n=15
Assume that a new Intel processor can execute1015operations per second.You have two algorithms that test whether a number is prime or not.Thefirst algorithm uses100n2operations for a number with n decimal digits.The second uses2n operations for a number with n decimal ing thefirst algorithm,how many seconds would the Intel processor take to determine whether a1000 decimal digit number is prime?Using the second algorithm,how many seconds would the Intel processor take to determine whether a1000decimal digit number is prime?
Solution7:
Thefirst algorithm would take10−7seconds(100nanoseconds).The second algorithm would take 10286seconds.For comparison,the universe is about4.33×1017seconds old,so it would take approximately2.5×10268times the age of the universe to solve the problem using the second algorithm.
Problem8(1-1Comparison of running times):
For each function f(n)and time t in the following table,determine the largest size n of a prob-lem that can be solved in time t,assuming that the algorithm to solve the problem takes f(n) microseconds.
1second1minute1hour1day1month1year1century
lg n
√
n
n
n lg n
n2
n3
2n
n!
Solution8:
1second1minute1hour1day1month1year1century
lg n210626×10723.6×10928.64×101022.63×101223.16×101323.16×1015√
n10123.6×10151.3×10197.46×10216.92×10249.96×10249.96×1030 n1066×1073.6×1098.64×10102.63×10123.16×10133.16×1015 n lg n6274628014171.33×1082.76×1097.29×10107.98×10116.87×1013 n210007745600002939381621643561753856175382 n3100391153244201380231600146677 2n19253136414451
n!9111213151617
Problem9(Derived from3.1-2):
Show that for all numbers a and b,(n+a)b=Θ(n b). Solution9:
(n+a)b=
b
k=0
b
k
n b−k a k(The binomial formula)
=n b+bn b−1k+···+bnk b−1+k b
=Θ(n b)
Problem10(3.1-4):
Is2n+1=O(2n)?Is22n=O(2n)?
Solution10:
2n+1=2×2n so2n+1=O(2n)
22n=2n×2n so22n=O(2n)
Problem11(Not in book):
In the table below,write O if f(n)=O(g(n)),Ωif f(n)=Ω(g(n)),andΘif f(n)=Θ(g(n)).
g(n)↓f(n)→5n+33.14×1088n2lg4n+n32n5n3+4n2lg n+3n12n+lg8n 5n+3
3.14×108
8n2lg4n+n3
2n
5n3+4n2lg n+3n
12n+lg8n
Solution11:
g(n)↓f(n)→5n+33.14×1088n2lg4n+n32n5n3+4n2lg n+3n12n+lg8n 5n+3ΘOΩΩΩΘ
3.14×108ΩΘΩΩΩΩ
8n2lg4n+n3O OΘΩΩO 2n O O OΘO O
5n3+4n2lg n+3n O O OΩΘO 12n+lg8nΘOΩΩΩΘ。