算法导论作业6答案
算法分析第六章答案精选全文
13
P136 算法6.5
P(i) P(1)=1/20, P(2)=1/5, P(3)=1/10, P(4)=1/20
Q(i) Q(0)=1/5, Q(1)=1/10, Q(2)=1/5, Q(3)=1/20, Q(4)=1/20
化简为整数形式
P(i) P(1)=1, P(2)=4, P(3)=2, P(4)=1
Call CreateTree(m, r-1, root, w)
Call CreateTree(r, n, root, w)
endif
endif
End BuildTree
26
P151-6
设(w1,w2,w3,w4)=(10, 15, 6, 9), (p1,p2,p3,p4)=(2, 5, 8, 1)。
7
5
3
3
9 6
3
3
P151-1
Ak(i,j) = min{Ak-1(i,j), Ak-1(i,k)+Ak-1(k,j)} , k1 ①成立,不包含负长度环. P130 ②可以使结点间的长度任意小。
4
P151-2
修改过程ALL_PATHS,使其输出每对 结点(i,j)间的最短路径,这个新算法 的时间和空间复杂度是多少?
29
实现思想: 1:令(P,W)为最优解所对应的序偶,i=n-1 2:如果i>0,重复下列操作:
时间复杂性分析:T(n)=c+T(k)+T(n-k-1),此递推式保证算法
的时间复杂性为O(n),也可从递归的角度出发,递归的次数正
是结点的个数,而每次递归时间复杂性为常数,所以算法的时
间复杂度也为O(n)。
19
② Procedure BuildTree(m, n, R, Root) integer R(n,n), k TreeNode Root, LR, RR if (mn) then k←R(m,n) if k≠0 then data(Root)←k //内结点 BuildTree(m, k-1, R, LR) BuildTree(k, n, R, RR) left(Root)←LR right(Root)←RR else Root←null //外结点 endif endif
算法导论(第三版)-复习-第六部分图论22-26[转]
算法导论(第三版)-复习-第六部分图论22-26[转]22习题22.1-5 有向图G(V, E)的平⽅图。
链表表⽰时,对每结点u的Adj[u]中所有v加⼊队列,后边出队边将Adj[v]加⼊Adj[u]中。
矩阵表⽰时,若w[i, j]、w[j, k]同时为1则将w[i, k]置1.习题22.1-6 O(V)的时间寻找通⽤汇点。
汇点的特征是邻接矩阵的第j列除[j, j]外所有元素为1. 可将每⾏调整[j ,j]后作为⼀个整数,所有整数与运算,为1的位是汇点。
习题22.1-7 有向⽆环图的关联矩阵B,BB’每个元素C[i, j]=∑B[i, k]*B’[k, j]=∑B[i, k]*B[j, k],即同时进i, j两结点与同时出i, j的结点总数-⼀进⼀出i, j两结点的结点总数。
习题22.2-7 类似BFS,d mod2为0则标为B(娃娃脸),d mod2为1则标为H(⾼跟鞋)。
但若有边连接相同类的结点,则⽆法划分。
wrestler(G){for each u in G{(u,v)=Adj[u];if(v.mark==u.mark){throw error;}if(v.d==NIL) {v.d=u.d+1; v.mark=v.d mod 2;}}}习题22.2-8 任意点之间的最短路径。
重复的Dijktra算法或Floyd-Warshall算法习题22.2-9 ⽆向图扩展为有向图。
问题变成要遍历所有边⼀次。
访问结点u时,将u的⼦结点v的其他边都可视为⼦集v,问题等价于u到v,访问v的集合,v到u。
u标为visiting⼊列,然后访问v,v标为visiting⼊列,然后访问v的后继结点,访问过的边标为visited,返回到visiting的点时,如果该点所有连接的边都标为visited只剩⼀条返回上级的边,则返回上级结点并将点标为visited,v出列,访问u的其他⼦结点,最终u出列。
全部结点出列后达到遍历所有边⼀次。
算法导论课程作业答案
算法导论课程作业答案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。
《算法导论(第二版)》(中文版)课后答案
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)
算法导论参考问题详解
第二章算法入门由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。
另,思考题2-3 关于霍纳规则,有些部分没有完成,故没把解答写上去,我对其 c 问题有疑问,请有解答方法者提供个意见。
给出的代码目前也仅仅为解决问题,没有做优化,请见谅,等有时间了我再好好修改。
插入排序算法伪代码INSERTION-SORT(A)1 for j ←2 to length[A]2 do key ←A[j]3 Insert A[j] into the sorted sequence A[1..j-1]4 i ←j-15 while i > 0 and A[i] >6 do A[i+1]←A[i]7 i ←i − 18 A[i+1]←keyC#对揑入排序算法的实现:public static void InsertionSort<T>(T[] Input) where T:IComparable<T>{T key;int i;for (int j = 1; j < Input.Length; j++){key = Input[j];i = j - 1;for (; i >= 0 && Input[i].CompareTo(key)>0;i-- )Input[i + 1] = Input[i];Input[i+1]=key;}}揑入算法的设计使用的是增量(incremental)方法:在排好子数组A[1..j-1]后,将元素A[ j]揑入,形成排好序的子数组A[1..j]这里需要注意的是由于大部分编程语言的数组都是从0开始算起,这个不伪代码认为的数组的数是第1个有所丌同,一般要注意有几个关键值要比伪代码的小1.如果按照大部分计算机编程语言的思路,修改为:INSERTION-SORT(A)1 for j ← 1 to length[A]2 do key ←A[j]3 i ←j-14 while i ≥ 0 and A[i] >5 do A[i+1]←A[i]6 i ←i − 17 A[i+1]←key循环丌变式(Loop Invariant)是证明算法正确性的一个重要工具。
算法导论第三版第六章答案英
算法导论第三版第六章答案英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。
算法设计与分析习题答案6章
习题11. 图论诞生于七桥问题。
出生于瑞士的伟大数学家欧拉(Leonhard Euler ,1707 —1783) 提出并解决了该问题。
七桥问题是这样描述的:一个人是否能在一次步行中穿越哥尼斯堡(现在叫加里宁格勒,在波罗的海南岸)城中全部的七座桥后回到起点,且每座桥只经过一次,图是这条河以及河上的两个岛和七座桥的草图。
请将该问题的数据模型抽象出来,并判断此问题是否有解。
七桥问题属于一笔画问题。
输入:一个起点输出:相同的点1,一次步行2,经过七座桥,且每次只经历过一次3,回到起点该问题无解:能一笔画的图形只有两类:一类是所有的点都是偶点。
另一类是只有二个奇点的图形。
2 •在欧几里德提出的欧几里德算法中(即最初的欧几里德算法)用的不是除法而是减法。
请用伪代码描述这个版本的欧几里德算法=m-n2.循环直到r=0m=nn=rr=m-n3输出m3 •设计算法求数组中相差最小的两个元素(称为最接近数)的差。
要求分别给出伪代码和C++描述。
编写程序,求n至少为多大时,n个"1”组成的整数能被2013整除。
#in clude<iostream> using n amespace std;int mai n(){double value=0;for(int n=1;n<=10000 ;++n){ value=value*10+1;if(value%2013==0){cout<<"n 至少为:"<<n<<endl; break;}}计算n值的问题能精确求解吗编写程序,求解满足给定精度要求的n值#include <iostream> using namespace std;int main (){double a,b;double arctan(double x); 圣经上说:神6 天创造天地万有,第7 日安歇。
为什么是6 天呢任何一个自然数的因数中都有1 和它本身,所有小于它本身的因数称为这个数的真因数,如果一个自然数的真因数之和等于它本身,这个自然数称为完美数。
中科大算法导论作业标准标准答案
第8次作业答案16.1-116.1-2543316.3-416.2-5参考答案:16.4-1证明中要三点:1.有穷非空集合2.遗传性3.交换性第10次作业参考答案16.5-1题目表格:解法1:使用引理16.12性质(2),按wi单调递减顺序逐次将任务添加至Nt(A),每次添加一个元素后,进行计算,{计算方法:Nt(A)中有i个任务时计算N0 (A),…,Ni(A),其中如果存在Nj (A)>j,则表示最近添加地元素是需要放弃地,从集合中删除};最后将未放弃地元素按di递增排序,放弃地任务放在所有未放弃任务后面,放弃任务集合内部排序可随意.解法2:设所有n个时间空位都是空地.然后按罚款地单调递减顺序对各个子任务逐个作贪心选择.在考虑任务j时,如果有一个恰处于或前于dj地时间空位仍空着,则将任务j赋与最近地这样地空位,并填入; 如果不存在这样地空位,表示放弃.答案(a1,a2是放弃地):<a5, a4, a6, a3, a7,a1, a2>or <a5, a4, a6, a3, a7,a2, a1>划线部分按上表di递增地顺序排即可,答案不唯一16.5-2(直接给个计算例子说地不清不楚地请扣分)题目:本题地意思是在O(|A|)时间内确定性质2(性质2:对t=0,1,2,…,n,有Nt(A)<=t,Nt(A)表示A中期限不超过t地任务个数)是否成立.解答示例:思想:建立数组a[n],a[i]表示截至时间为i地任务个数,对0=<i<n,如果出现a[0]+a[1]+…+a[i]>i,则说明A不独立,否则A独立.伪代码:int temp=0;for(i=0;i<n;i++) a[i]=0; ******O(n)=O(|A|)for(i=0;i<n;i++) a[di]++; ******O(n)=O(|A|)for(i=0;i<n;i++) ******O(n)=O(|A|) {temp+=a[i];//temp就是a[0]+a[1]+…+a[i]if(temp>i)//Ni(A)>iA不独立;}17.1-1(这题有歧义,不扣分)a) 如果Stack Operations包括Push Pop MultiPush,答案是可以保持,解释和书上地Push Pop MultiPop差不多.b) 如果是Stack Operations包括Push Pop MultiPush MultiPop,答案就是不可以保持,因为MultiPush,MultiPop交替地话,平均就是O(K).17.1-2本题目只要证明可能性,只要说明一种情况下结论成立即可17.2-1第11次作业参考答案17.3-1题目:答案:备注:最后一句话展开:采用新地势函数后对i 个操作地平摊代价:)1()())1(())(()()(1''^'-Φ-Φ+=--Φ--Φ+=Φ-Φ+=-Di Di c k Di k Di c D D c c i i i i i i17.3-2题目:答案:第一步:此题关键是定义势能函数Φ,不管定义成什么首先要满足两个条件 对所有操作i ,)(Di Φ>=0且)(Di Φ>=)(0D Φ比如令k j+=2i ,j,k 均为整数且取尽可能大,设势能函数)(Di Φ=2k;第二步:求平摊代价,公式是)1()(^-Φ-Φ+=Di Di c c i i 按上面设置地势函数示例:当k=0,^i c =…=2当k !=0,^i c =…=3 显然,平摊代价为O(1)17.3-4题目:答案:结合课本p249,p250页对栈操作地分析很容易有下面结果17.4-3题目:答案:αα=(第i次循环之后地表中地entry 假设第i个操作是TABLE_DELETE, 考虑装载因子:inum size数)/(第i次循环后地表地大小)=/i i第12 次参考答案19.1.1题目:答案:如果x不是根,则degree[sibling[x]]=degree[child[x]]=degree[x]-1如果x是根,则sibling为二项堆中下一个二项树地根,因为二项堆中根链是按根地度数递增排序,因此degree[sibling[x]]>degree[x]19.1.2题目:答案:如果x是p[x]地最左子节点,则p[x]为根地子树由两个相同地二项树合并而成,以x为根地子树就是其中一个二项树,另一个以p[x]为根,所以degree[p[x]]=degree[x]+1;如果x不是p[x]地最左子节点,假设x是p[x]地子节点中自左至右地第i个孩子,则去掉p[x]前i-1个孩子,恰好转换成第一种情况,因而degree[p[x]]=degree[x]+1+(i-1)=degree[x]+i;综上,degree[p[x]]>degree[x]19.2.2题目:题目:19.2.519.2.6第13次作业参考答案20.2-1题目:解答:20.2-3 题目:解答:20.3-1 题目:答案:20.3-2 题目:答案:第14次作业参考答案这一次请大家自己看书处理版权申明本文部分内容,包括文字、图片、以及设计等在网上搜集整理.版权为个人所有This article includes some parts, including text, pictures, and design. Copyright is personal ownership.6ewMy。
算法导论参考答案
第二章算法入门由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。
另,思考题2-3 关于霍纳规则,有些部分没有完成,故没把解答写上去,我对其 c 问题有疑问,请有解答方法者提供个意见。
给出的代码目前也仅仅为解决问题,没有做优化,请见谅,等有时间了我再好好修改。
插入排序算法伪代码INSERTION-SORT(A)1 for j ←2 to length[A]2 do key ←A[j]3 Insert A[j] into the sorted sequence A[1..j-1]4 i ←j-15 while i > 0 and A[i] > key6 do A[i+1]←A[i]7 i ←i − 18 A[i+1]←keyC#对揑入排序算法的实现:public static void InsertionSort<T>(T[] Input) where T:IComparable<T>{T key;int i;for (int j = 1; j < Input.Length; j++){key = Input[j];i = j - 1;for (; i >= 0 && Input[i].CompareTo(key)>0;i-- )Input[i + 1] = Input[i];Input[i+1]=key;}}揑入算法的设计使用的是增量(incremental)方法:在排好子数组A[1..j-1]后,将元素A[ j]揑入,形成排好序的子数组A[1..j]这里需要注意的是由于大部分编程语言的数组都是从0开始算起,这个不伪代码认为的数组的数是第1个有所丌同,一般要注意有几个关键值要比伪代码的小1.如果按照大部分计算机编程语言的思路,修改为:INSERTION-SORT(A)1 for j ← 1 to length[A]2 do key ←A[j]3 i ←j-14 while i ≥ 0 and A[i] > key5 do A[i+1]←A[i]6 i ←i − 17 A[i+1]←key循环丌变式(Loop Invariant)是证明算法正确性的一个重要工具。
算法导论(第二版)课后习题解答
Θ
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
Solutions for Introduction to algorithms second edition
Philip Bille
The author of this document takes absolutely no responsibility for the contents. This is merely a vague suggestion to a solution to some of the exercises posed in the book Introduction to algorithms by Cormen, Leiserson and Rivest. It is very likely that there are many errors and that the solutions are wrong. If you have found an error, have a better solution or wish to contribute in some constructive way please send a message to beetle@it.dk. It is important that you try hard to solve the exercises on your own. Use this document only as a last resort or to check if your instructor got it all wrong. Please note that the document is under construction and is updated only sporadically. Have fun with your algorithms. Best regards, Philip Bille
算法导论答案(经典)
8.3-3 8.3-4
8.3-5(*) 8.4-1 见图 8-4 8.4-2
8.4-3 3/2,1/2 8.4-4(*) 8.4-5(*)
9.1-1
9.1-2 9.2-1 9.3-1
第九章
9.3-2 9.3-3
9.3-4 9.3-5
9.3-6 9.3-7
9.3-8
9.3-9
15.1-1
16.3-1 16.3-2Leabharlann 16.3-3 16.3-4
16.3-5
16.3-6 那就推广到树的结点有三个孩子结点,证明过程同引理 16.3 的证明。 16.3-7 16.3-8
第 24 章
24.1-1 同源顶点 s 的运行过程,见图 24-4 24.1-2
24.1-3
24.1-4 24.1-5* 24.1-6 修改 Bellman-Ford 算法,先找到负环上的一个节点,再依次找到负环上的一个节点,再依 次找到负环上的其他节点。 24.2-1 见图 24-5 24.2-2 最后一次不影响结果
len=j;//更新 len
} cout<<len<<endl; } return 0; } 15.5-1
15.5-2 15.5-3
15.5-4
16.1-1
第 16 章
16.1-2 16.1-3
16.1-4 16.2-1 16.2-2
16.2-3
16.2-4
16.2-5 16.2-6
16.2-7
第 25 章
25.1-4 25.1-5
25.1-6 25.1-7 25.1-8
25.1-9 25.1-10 25.2-1 见图 25-4 25.2-2 25.2-3 25.2-4
算法导论中文版答案
} cout<<len<<endl; } return 0; } 15.5-1
15.5-2 15.5-3
15.5-4
16.1-1
第 16 章
16.1-2 16.1-3
16.1-4 16.2-1 16.2-2
16.2-3
16.2-4
16.2-5 16.2-6
16.2-7
25.3-6
5.3-6
6.1-1 6.1-2 6.1-3 6.1-4 6.1-5 6.1-6
第6章
6.1-7
6.2-1 见图 6-2 6.2-2
6.2-3
6.2-4
6.2-5 对以 i 为根结点的子树上每个点用循环语句实现 6.2-6
6.3-1
见图 6-3 6.3-2
6.3-3
6.4-1 见图 6-4 6.4-2 HEAPSORT 仍然正确,因为每次循环的过程中还是会运行 MAX-HEAP 的过程。 6.4-3
6.4-4
6.4-5
6.5-1 据图 6-5 6.5-2
6.5-3 6.5-4 6.5-5
6.5-6 6.5-7
6.5-8
7.1-1 见图 7-1 7.1-2
7.1-3 7.1-4 7.2-1 7.2-2
7.2-3 7.2-4 7.2-5
第七章
7.2-6 7.3-1
7.3-2
7.4-1 7.4-2
16.3-1 16.3-2
16.3-3 16.3-4
16.3-5
16.3-6 那就推广到树的结点有三个孩子结点,证明过程同引理 16.3 的证明。 16.3-7 16.3-8
第 24 章
24.1-1 同源顶点 s 的运行过程,见图 24-4 24.1-2
算法导论习题答案
Chapter2 Getting Start2.1 Insertion sort2.1.2 将Insertion-Sort 重写为按非递减顺序排序2.1.3 计算两个n 位的二进制数组之和2.2 Analyzing algorithms2.2.1将函数32/10001001003n n n --+用符号Θ表示2.2.2写出选择排序算法selection-sort当前n-1个元素排好序后,第n 个元素已经是最大的元素了.最好时间和最坏时间均为2()n Θ2.3 Designing algorithms2.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 +=时,111111()(2)2(2)222(1)22lg(2)lg i i i i i i i i T n T T i i n n ++++++==+=⋅+=+== ()lg T n n n ∴ =2.3.4 给出insertion sort 的递归版本的递归式(1)1()(1)()1if n T n T n n if n Θ =⎧=⎨-+Θ >⎩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<jif A[i]+A[j]<xi←i+1elsej←j -1if A[i]+A[j]=xreturn trueelsereturn false时间复杂度为)(n Θ。
《计算机导论》第六章算法与数据结构课后习题
《计算机导论》第六章算法与数据结构课后习题1.编写一个程序,输入m、n,打印最小公倍数和最大公约数。
用五种方法写出其算法的描述。
2.试用递归的方法写一下计算菲波那契数列的通项f(n),已知f1=1,f2=1,以后每项都是前两项的和。
3.用折半查找1,2,3,4,5,6,7,8,9,10,11,12,13,14,15怎么找到10,请画图表示查找过程。
4.用三种方法对下列数字排序:12,3,4,5,8,7,15,9,10,1,11,14,6,13,2,请画出排序过程。
5.算法的灵魂是什么?6.用C语言写出选择排序、冒泡排序、插入排序、顺序查找和折半查找的程序(选做)。
附录:编程典型例题1.write a program that prompt the user to specify the sizeof a t-shirt: S for small,M for medium,L for large and X for extra large.The prices are $10,$20,$30 and $40,respectively.Display the price of a chosen size.Eg. PromptString.java2.write a program that displays even integer values from 1 to 20.Eg. DisplayEven.java3.输入一个华氏温度,要求输出摄氏温度。
公式为c=5(F-32)/9,输出要求有文字说明,取2位小数。
Eg. DisplayTemperature.java4.编写一个程序,输入a、b、c、d,输出其中最大者。
Eg. DisplayMax.java5.有一函数y= x (x<1)y= 2x-1 (1≤x<10)y= 3x-11 (x≥10)写一程序输入输出值。
6.打印出所有"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该本身。
算法部分作业答案
算法部分作业答案算法:是对特定问题求解步骤的⼀种描述,是指令的有限序列。
程序:当⼀个算法⽤某种程序设计语⾔来描述时,得到的就是程序,也就是说,程序是⽤某种程序设计语⾔对算法的具体实现.算法有输⼊、输出、确定性、能⾏性和有限性等特征,当不具备有穷性时,只能叫做计算过程,⽽不能称之为算法,算法可以终⽌,⽽程序没有此限制。
程序证明和程序测试的⽬的各是什么程序证明是确认⼀个算法能正确⽆误的⼯作.程序测试的⽬的是发现错误1-9解: n!的递归定义:11)!1(*{!=≥-=nnnnn求解n!的递归函数long Factorial (long n){if(n<0){cout<<”error!”;exit(0);}if(n==0)return 1;else return n *Factorial (n-1);}1-10使⽤归纳法,证明上题所设计的计算n!的递归函数的正确性证明(归纳法证明):(1)⾸先,如果n=0,那么程序执⾏if(n==0)return 1;返回1,算法显然正确;(2)假定函数Factorial对n1)能正确运⾏,那么,当n=k时,算法必定执⾏:else return k *Factorial (k-1);因为Factorial (k-1)正确,所以,当n=k时,程序运⾏正确综合以上两点,可得程序正确.证毕.2-1, 简述衡量⼀个算法的主要性能标准,说明算法的正确性与健壮性的关系答: 衡量⼀个算法的主要性能指标有:正确性,简单性,⾼效低存储,最优性算法的正确性与健壮性的关系:所谓算法的正确性:是指在合法的输⼊下,算法应实现预先规定的功能和计算精度要求;所谓算法的健壮性,是指当输⼊不合法时,算法应该能按某种预定的⽅式做出适当的处理;正确的算法不⼀定的是健壮的,健壮的算法也不⼀定是完全正确的.正确性和健壮性是相互补充的.⼀个可靠的算法,要求能在正常情况下正确的⼯作,⽽在异常情况下,亦能做出适当处理.2-9(1)设计⼀个C/C++程序,实现⼀个n*m 的矩阵转置,原矩阵与其转置矩阵保存在⼆维数组中.Void reverse(int **a,int **b,int n,int m){For(int i=0;iFor(int j=0;jb[j][i]=a[i][j];}(2)使⽤全局变量count,改写矩阵转置程序,并运⾏修改后的程序以确定此程序所需的程序步Void reverse(int **a,int **b,int n,int m,int &count){int i=0;count++;int j=0;count++;For(;iFor(;j{count++;b[j][i]=a[i][j];count++;}}2-10 试⽤定义证明下列等式的正确性(1) 5n 2-8n+2=O(n 2)证明: 因为当n 0=1,C=6时,当n>n 0时,有5n 2-8n+2<=6n 22-16 使⽤递推关系式计算求n!的递归函数的时间(即分析1-9题中的函数的时间复杂度),要求使⽤替换和迭代两种⽅法分别计算之.解: 分析1-9题中的函数的时间复杂度:⽤基本运算乘法的运算次数作为衡量时间复杂度的量当n=0时,程序执⾏if(n==0) return 1;,并没有做乘法,故T(0)=0;当n>=1时程序执⾏n *Factorial (n-1);此时T(n)= T(n-1)+1故: 0011)1({)(=≥+-=n n n T n T替换法: T(0)=0,T(1)=1,T(2)=2-----总结得到:T(n)=n;归纳法证明:(1),当n=0时,T(0)=0,结论成⽴;(2)假设当k所以,对所有n>=0有T(n)=n;成⽴.迭代法:T(n)=T(n-1)+1=(T(n-2)+1)+1=((T(n-3)+1)+1)+1=....=T(0)+1+1......+1(n 个1)=n 2-19 利⽤递归树计算递推⽅程2)2/(2)(n n T n T += 2)1(=T假设n=2k ,那么,总共有logn+1(即k+1)层,⾮递归部分之和为n 2+n 2/21+n 2/22+…+n 2/2k =(1+1/2+1/22+1/23+…+1/2logn )n 2=2n 2+2n=O(n 2)5-8三分搜索算法的做法是:它先将待查元素X 与n/3处的元素⽐较,然后将X 与2n/3处的元素⽐较,⽐较的结果或者找到X,或者将范围缩⼩到原来的n/3int Search3(int a[],int left,int right,int x) /*递归算法*/{int l,u;if(left<=right){l=left+(right-left)/3;u=left+(right-left)*2/3;if(x==a[u])return u;else if(x==a[l])return l;else if(x>a[u])return Search3(a, u+1, right,x);else if(x>a[l])return Search3(a, l+1, u-1,x);elsereturn Search3(a, left, l-1,x);}return -1;}void main(){int n,*a;int x,i;cout<<"Please input n:";cin>>n;(1) a=new int[n]; 假设当n< right-left+1(n>=2)时,算法正确,即对于所有元素个数⼩于n 的元素集,算法能正确排序.那么,当n= right-left+1时,算法执⾏程序段:int k=(right-left+1)/3;stoogesort(a,left,right-k);stoogesort(a,left+k,right);stoogesort(a,left,right-k);由假设可知:以上三条语句都能正确运⾏,所以,当n= right-left+1时,算法正确.由以上两点可知,算法正确.分析算法的时间复杂度:排序算法,基本运算仍然是元素之间的⽐较,所以,算法时间复杂度为:1,0121)3/2(3{)(=≥+=n n n T n T (⽤替换或迭代法计算之即可)6-1设有背包问题实例,n=7,(w0,w1,w2,w3,w4,w5,w6)=(2,3,5,7,1,4,1),(p0,p1,p2,p3,p4,p5,p6)=( 10,5,15,7,6,18,3),M=15。
算法设计第六章答案
2)程序流程 整个流程与队列式分支限界法的 01 背包问题一样,只是插入活结点的操作:由 insert()改为 push(),重新选择下一个扩展结点的操作:由 delete()改为 pop()。 算法主函数是: 一个 while(1)循环,循环结束条件是活结点列表为空,即当前扩展结点为空,表 示所有可行的结点都已经得到遍历;并且输出最优解。 每一次循环作用是:在当前的扩展结点下,将以当前扩展结点作为父结点的下一 层子结点都加入到活结点列表里,并且选择一个新的扩展结点,进入下一层循环; 其中,剪枝函数包括左结点的容量约束(约束函数)和右结点的最大价值判断(界 限函数);
是
将当前儿子结点加至 活结点列表
输出最优解 结束
将儿子结点加至活 结点列表
算法实现题 6-4: 最小重量机器设计问题 问题描述:设某一个机器由 n 个部件组成,每一种部件都可以从 m 个不同的供 应商处购得。设 wij 是从供应商 j 处购得的部件 i 的重量,cij 是相应的价格。 设计一个优先队列式分支限界法,给出总价格不超过 d 的最小重量机器设计。 编程任务: 对于给定的机器部件重量和机器部件价格,设计一个优先队列式分支限界法,计 算总价格不超过 d 的最小机器设计。
为 i+1; 2) 如果连接块 Nj 跨越 x[i+1]电路板,而且当前 high[j]小于 i+1,则将 high[j]更
新为 i+1; 3) 其余情况,则不需要更新 low[j]和 high[j]。
开始
根结点加入活结点列表, 并作为当前扩展结点
按照“先进先出”,选择下 一个扩展结点
计算各连接块的最小长度, 并且更新当前最优长度
算法流程: 主函数是一个 while 循环,结束条件是活结点列表为空,表示所有叶结点都已经 遍历完成;此时,应该输出整个问题的最优解。 每一次循环需要完成的工作包括:1)如果当前扩展结点的深度是 n-1,表示整个
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Problem 6-1. Overlapping rectangles VLSI databases commonly represent an integrated circuit as a collection of rectangles. Assume that each rectangle is rectilinearly oriented (sides parallel to the x- and y -axis), so that a representation of a rectangle consists of its minimum and maximum x- and y -coordinates.
2
Handout 24: Problem Set 6 Solutions (a) Give an O(n lg n)-time algorithm that decides whether a set of rectangles so repre sented contains two rectangles that overlap. Your algorithm need not report all inter secting pairs, but it must report that an overlap exists if one rectangle entirely covers another, even if the boundary lines do not intersect. (Hint: Move a “sweep” line across the set of rectangles by replacing one of the two spatial dimensions with time. At all times maintain the collection of rectangles pierced by the sweep line.) Solution: Idea: The main idea here is to move a sweep line from left to right, while maintain ing the set of rectangles intersected by the line in an interval tree. Details: First sort the x-coordinates of the rectangles. Scan the sorted x-coordinate list from lowest to highest. When an x-coordinate of a left edge is found, add the in terval corresponding to the y -coordinates of that edge into the interval tree and check for overlap. When an x-coordinate of a right edge is found, delete the interval cor responding to the y -coordinates of that edge from the interval tree. The interval tree always contains the set of “open” rectangles intersected by the sweep line. (b) Argue that your algorithm indeed runs in O(n lg n) time in the worst case. Solution: This implementation requires O(n lg n) time to sort the x-coordinates, and 2n · O(lg n) to maintain the interval tree, for a total running time of O(n lg n).
Problem 6-2. GPS map display After graduating from MIT, you decide to join GiPSy, a startup that hopes to make money by selling an affordable hand-held GPS (Global Positioning System) device. The device picks up time-stamped messages from 4 geostationary satellites and uses them to calculate its precise co ordinates on the globe by taking into account the orbital position of each satellite (included in the messages) and the time it took each message to reach the device. The device has a rectangular LCD screen which displays the user’s exact location on the map, as well as all the nearby streets; see Figure 1. The device must be able to update the map display in real time because the user may be moving and may zoom in or out. GiPSy’s first model will only work in cities whose streets are arranged in a grid (such as Manhattan). If the first model proves to be a success in those markets, GiPSy hopes to secure the necessary funding to develop a model that can work in all cities. Your task is to figure out how the city map should be preprocessed and stored on the device, in order to quickly answer queries about what streets are in the vicinity of the user. More precisely, the problem is defined as follows: • A road r = �(rx1 , ry1 ), (rx2 , ry2 )� is a line segment, either horizontal or vertical, spec ified by the coordinates of its endpoints, (rx1 , ry1 ) and (rx2 , ry2 ). Thus, for every road r = �(rx1 , ry1 ), (rx2 , ry2 )�, we have either rx1 = rx2 (vertical) or ry1 = ry2 (horizontal).
Day 23 6.046J/18.410J SMA5503 Handout 24
Problem Set 6 Solutions
Exercise 6-1. Do exercise 14.1-5 on page 307 of CLRS. Solution: First find the rank of x. Add i to this value, and find the element with this rank. This takes 2O(lg n) + 1 time. Exercise 6-2. Do exercise 14.2-2 on page 310 of CLRS. Solution: Yes, since the black height of a node can be computed from the information at the node and its two children. According to Theorem 14.1 (page 309 of CLRS) insertion and deletion can be still performed in O(lg n) time. Exercise 6-3. Do exercise 14.3-1 on page 316 of CLRS. Solution: Assume that before the rotation x has α as its left child and y as its right child, and y has β as its left child and γ as its right child. The rotation changes the pointers as in the L EFT-ROTATE procedure as shown on page 278 of CLRS. In addition, at the end it sets max[y ] ← max[x] and max[x] ← max(max[α], max[β ], high[int[x]]) in that order. This takes O(1) time. Exercise 6-4. Do exercise 33.1-4 on page 946 of CLRS. Solution: For each point, sort the others by their polar angle relative to that point, and check if any two adjacent points in the sorted order have the same angle. For each point, we need O(n) time to compute the polar angles of all the other points, O(n lg n) time to sort them and O(n) time to check whether any two adjacent points have the same angle. We repeat the process for O(n) points, which gives us a total running time of O(n2 lg n). Exercise 6-5. Do exercise 33.2-1 on page 946 of S. Solution: We can show this by construction: consider a regular polygon with n sides. If n is even, for each side of the polygon there is exactly one other side parallel to it (think of a square, or a hexagon). If n is odd, there are no parallel sides (think of a triangle or a pentagon). In any case, of all pairwise n(n − 1)/2 combinations of sides, there are at most n/2 pairs of sides which are parallel to each other. The remaining n(n − 1)/2 − n/2 are not parallel. So if we extend them sufficiently in both directions, at some point they will intersect (pairwise). Thus we will have n segments with n(n − 1)/2 − n/2 = Θ(n2 ) intersections.