算法导论课程作业
算法导论思考题7_2对区间的模糊排序

算法导论思考题7_2对区间的模糊排序这个学期在做算法设计课的助教,很多题以前做过就忘记了,重做特地记录下。
《算法导论》chapter7 problem7-6对区间的模糊排序考虑这样⼀种排序问题,即⽆法准确的知道等排序的各个数字到底是多⼤.对于其中的每个数字,我们只知道它落在实轴上的某个区间内.亦即,给定的 n 个形如[ai, bi ]的闭区间,其中ai,≤bi .算法的⽬标是对这些区间进⾏模糊排序(fuzzy-sort),亦即,产⽣各区间的⼀个排序<i1, i2, i3, i4,…in >,使得存在⼀个 cj ∈[ai, bi ],满⾜c1≤c2≤…≤cn .a)为n个区间的模糊排序设计⼀个算法,你的算法应该具有算法的⼀般结构,它可以快速排序左部端点(即各ai ),也要能充分利⽤重叠区间来改善运⾏时间.(随着各区间重叠得越来越多,对各区间的排序的问题会变得越来越容易,你的算法应该能充分利⽤这种重叠.)b)证明: 在⼀般情况下,你的算法的区望运⾏时间为 O(n*lgn),但当所有的区间都重叠时,期望的运⾏时间为O(n) (亦即,当存在⼀个值 x, 使得对所有的 i, 都有x∈[ai, bi ] ).你的算法不应显式的检查这种情况,⽽是应当随着重叠量的增加,性能⾃然地有所改善.解答a. 算法思想基本是仿快速排序对区间进⾏排序。
难点在于如何充分利⽤重叠区间来改善运⾏时间?其关键在于Partion()的设计。
对于如何充分利⽤重叠区间,解决思路是在调⽤Partion()划分时,区间如果重叠的部分,就把它们看做是相等的,并提取公共部分继续划分。
即对于区间[ai,bi],[aj,bj],它们⼤⼩分为三种情况。
if(bi<aj)那么[ai,bi]<[aj,bj]else if(bj<ai)那么[aj,bj]<[ai,bi]else [ai,bi]=[aj,bj]。
⽹上其它⼈的解答,思路都是类似的,不过看了⼏个版本,不少⼈在代码实现上多少有点bug。
算法导论课程设计

课程设计报告课程名称算法导论课题名称棋子移动问题专业班级学号姓名指导教师年月日湖南工程学院课程设计任务书课程名称算法导论课题棋子移动问题专业班级学生姓名学号指导老师审批任务书下达日期年月日任务完成日期年月日一、设计内容与设计要求1.设计内容:课本P220页 15-6 在棋盘上移动问题n 个方格的棋盘以及一个棋子。
必须根据以下的规则把棋子从假设有一张n棋盘的底边移动到棋盘的顶边。
在每一步你可以把棋子移动到三个方格中的一个:1)正上方的方格,2)左上方的方格(只能当这个棋子不在最左列的时候),3)右上方的方格(只能当这个棋子不在最右列的时候)。
每次从方格x移动到方格y,会得到p(x,y)块钱。
已知所有对(x,y)的p(x,y),只要从x到y的移动都是合法的。
不要假设p(x,y)的正值。
请给出一个计算移动方式集合的算法,把棋子从棋盘底边的某个地方移动到棋盘顶边的某个地方,同时收集尽可能多的钱。
你的算法可以自由选择底边的任意方格作为起始点,顶边上的任意方格作为目的点,来最大化一路上收集到的钱数。
你的算法执行时间是多少?2.设计要求:●课程设计报告正文内容(一)问题的描述;(二)算法设计与分析,内容包括1,算法设计,对问题的分析和算法的设计2,算法描述,以伪代码形式的算法3,算法分析,主要是算法的正确性和运行时间的分析(三)算法实现所有程序的原代码,要求用C或java语言程序实现,并对程序写出必要的注释。
●书写格式a.要求用A4纸打印成册b.正文格式:一级标题用3号黑体,二级标题用四号宋体加粗,正文用小四号宋体;行距为22。
c.正文的内容:正文总字数要求在3000字左右(不含程序原代码)。
d.封面格式如下页。
●考核方式指导老师负责验收程序的运行结果,并结合学生的工作态度、实际动手能力、创新精神和设计报告等进行综合考评,并按优秀、良好、中等、及格和不及格五个等级给出每位同学的课程设计成绩。
具体考核标准包含以下几个部分:a.平时出勤(占10%)b.系统需求分析、功能设计、数据结构设计及程序总体结构合理与否(占10%)c.程序能否完整、准确地运行,个人能否独立、熟练地调试程序(占40%)d.设计报告(占30%)e.独立完成情况(占10%)。
算法导论课程考试

Introduction to Algorithms December17,2001 Massachusetts Institute of Technology 6.046J/18.410J Singapore-MIT Alliance SMA5503 Professors Erik Demaine,Lee Wee Sun,and Charles E.Leiserson Final Exam ReviewFinal Exam ReviewTrue-false questions(1)T F The best case running time for I NSERTION S ORT to sort an n element array is O(n).(2)T F By the master theorem,the solution to the recurrence T(n)=3T(n/3)+log n isT(n)=Θ(n log n).(3)T F Given any binary tree,we can print its elements in sorted order in O(n)time by per-forming an inorder tree walk.(4)T F Computing the median of n elements takesΩ(n log n)time for any algorithm workingin the comparison-based model.(5)T F Every binary search tree on n nodes has height O(log n).(6)T F Given a graph G=(V,E)with cost on edges and a set S⊆V,let(u,v)be an edgesuch that(u,v)is the minimum cost edge between any vertex in S and any vertex in V−S.Then,the minimum spanning tree of G must include the edge(u,v).(You may assume the costs on all edges are distinct,if needed.)(7)T F Computing a b takes exponential time in n,for n-bit integers a and b.(8)T F There exists a data structure to maintain a dynamic set with operations Insert(x,S),Delete(x,S),and Member?(x,S)that has an expected running time of O(1)per operation. (9)T F The total amortized cost of a sequence of n operations(i.e.,the sum over all operations,of the amortized cost per operation)gives a lower bound on the total actual cost of the sequence.(10)T F Thefigure below describes aflow assignment in aflow network.The notation a/bdescribes a units offlow in an edge of capacity b.True or False:The followingflow is a maximalflow./- 36-Q Q Q Q Q Q Q Q Q s ?Q Q Q Q Q Q Q Q Q s 3t b a 3/36/63/70/21/44/44/65/52/4ds c (11)T F Let G =(V,E )be a weighted graph and let M be a minimum spanning tree of G .The path in M between any pair of vertices v 1and v 2must be a shortest path in G .(12)T F n lg n =O (n 2)(13)T F Let P be a shortest path from some vertex s to some other vertex t in a graph.If theweight of each edge in the graph is increased by one,P remains a shortest path from s to t .(14)T F Suppose we are given n intervals (l i ,u i )for i =1,···,n and we would like to find aset S of non-overlapping intervals maximizing i ∈S w i ,where w i represents the weight of interval (l i ,u i ).Consider the following greedy algorithm.Select (in the set S )the interval,say (l i ,u i )of maximum weight w i ,remove all intervals that overlap with (l i ,u i )and repeat.This algorithm always provides an optimum solution to this interval selection problem.(15)T F Given a set of n elements,one can output in sorted order the k elements followingthe median in sorted order in time O (n +k log k ).(16)T F Consider a graph G =(V,E )with a weight w e >0defined forevery edge e ∈E .If a spanning tree T minimizes e ∈T w e then it also minimizes e ∈E w 2e,and vice versa.(17)T F The breadth first search algorithm makes use of a stack.(18)T F In the worst case,merge sort runs in O (n 2)time.(19)T F A heap can be constructed from an unordered array of numbers in linear worst-casetime.(20)T F No adversary can elicit the Θ(n 2)worst-case running time of randomized quicksort.(21)T F Radix sort requires an “in place”auxiliary sort in order to work properly.(22)T F A longest path in a dag G =(V,E )can be found in O (V +E )time.(23)T F The Bellman-Ford algorithm is not suitable if the input graph has negative-weightedges.(24)T F Memoization is the basis for a top-down alternative to the usual bottom-up versionof dynamic programming.(25)T F Given a weighted,directed graph G=(V,E)with no negative-weight cycles,theshortest path between every pair of vertices u,v∈V can be determined in O(V3)worst-case time.(26)T F For hashing an item into a hash table in which collisions are resolved by chaining,the worst-case time is proportional to the load factor of the table.(27)T F A red-black tree on128keys must have at least1red node.(28)T F The move-to-front heuristic for self-organizing lists runs no more than a constantfactor slower than any other reorganization strategy.(29)T F Depth-first search of a graph is asymptotically faster than breadth-first search.(30)T F Dijkstra’s algorithm is an example of a greedy algorithm.(31)T F Fibonacci heaps can be used to make Dijkstra’s algorithm run in O(E+V lg V)timeon a graph G=(V,E).(32)T F The Floyd-Warshall algorithm solves the all-pairs shortest-paths problem using dy-namic programming.(33)T F A maximum matching in a bipartite graph can be found using a maximum-flow al-gorithm.(34)T F For any directed acyclic graph,there is only one topological ordering of the vertices.(35)T F If some of the edge weights in a graph are negative,the shortest path from s to t canbe obtained using Dijkstra’s algorithm byfirst adding a large constant C to each edge weight, where C is chosen large enough that every resulting edge weight will be nonnegative. (36)T F If all edge capacities in a graph are integer multiples of5then the maximumflowvalue is a multiple of5.(37)T F For any graph G with edge capacities and vertices s and t,there always exists anedge such that increasing the capacity on that edge will increase the maximumflow from s to t in G.(Assume that there is at least one path in the graph from s to t.)(38)T F Heapsort,quicksort,and mergesort are all asymmptotically optimal,stable comparison-based sort algorithms.(39)T F If each operation on a data structure runs in O(1)amortized time,then n consecutiveoperations run in O(n)time in the worst case.(40)T F A graph algorithm withΘ(E log V)running time is asymptotically better than analgorithm with aΘ(E log E)running time for a connected,undirected graph G(V,E). (41)T F In O(V+E)time a matching in a bipartite graph G=(V,E)can be tested todetermine if it is maximum.(42)T F n integers each of value less than n100can be sorted in linear time.(43)T F For any network and any maximalflow on this network there always exists an edgesuch that increasing the capacity on that edge will increase the network’s maximalflow.(44)T F If the depth-first search of a graph G yields no back edges,then the graph G is acyclic.(45)T F Insertion in a binary search tree is“commutative”.That is,inserting x and then yinto a binary search tree leaves the same tree as inserting y and then x.(46)T F A heap with n elements can be converted into a binary search tree in O(n)time.。
MIT麻省理工学院 算法导论公开课 Problem Set 4 solution

Introduction to Algorithms October 29, 2005 Massachusetts Institute of Technology 6.046J/18.410J Professors Erik D. Demaine and Charles E. Leiserson Handout 18Problem Set 4 SolutionsProblem 4-1. TreapsIf we insert a set of n items into a binary search tree using T REE-I NSERT, the resulting tree may be horribly unbalanced. As we saw in class, however, we expect randomly built binary search trees to be balanced. (Precisely, a randomly built binary search tree has expected height O(lg n).) Therefore, if we want to build an expected balanced tree for a fixed set of items, we could randomly permute the items and then insert them in that order into the tree.What if we do not have all the items at once? If we receive the items one at a time, can we still randomly build a binary search tree out of them?We will examine a data structure that answers this question in the affirmative. A treap is a binary search tree with a modified way of ordering the nodes. Figure 1 shows an example of a treap. As usual, each item x in the tree has a key key[x]. In addition, we assign priority[x], which is a random number chosen independently for each x. We assume that all priorities are distinct and also that all keys are distinct. The nodes of the treap are ordered so that (1) the keys obey the binary-search-tree property and (2) the priorities obey the min-heap order property. In other words,•if v is a left child of u, then key[v]<key[u];•if v is a right child of u, then key[v]>key[u]; and•if v is a child of u, then priority(v)>priority(u).(This combination of properties is why the tree is called a “treap”: it has features of both a binary search tree and a heap.)Figure 1: A treap. Each node x is labeled with key[x]:p riority[x]. For example, the root has key G and priority 4.It helps to think of treaps in the following way. Suppose that we insert nodes x1,x2,...,x n, each with an associated key, into a treap in arbitrary order. Then the resulting treap is the tree that wouldhave been formed if the nodes had been inserted into a normal binary search tree in the order given by their (randomly chosen) priorities. In other words, priority[x i]<priority[x j]means that x i is effectively inserted before x j.(a) Given a set of nodes x1,x2,...,x n with keys and priorities all distinct, show that thereis a unique treap with these nodes.Solution:Prove by induction on the number of nodes in the tree. The base case is a tree withzero nodes, which is trivially unique. Assume for induction that treaps with k−1orfewer nodes are unique. We prove that a treap with k nodes is unique. In this treap, theitem x with minimum priority must be at the root. The left subtree has items with keys<key[x]and the right subtree has items with keys >key[x]. This uniquely defines theroot and both subtrees of the root. Each subtree is a treap of size ≤k−1, so they areunique by induction.Alternatively, one can also prove this by considering a treap in which nodes are inserted in order of their priority. Assume for induction that the treap with the k−1nodes with smallest priority is unique. For k=0t his is trivially true. Now considerthe treap with the k nodes with smallest priority. Since we know that the structureof a treap is the same as the structure of a binary search tree in which the keys areinserted in increasing priority order, the treap with the k nodes with smallest priorityis the same as the treap with the k−1nodes with smallest priority after inserting thek-th node. Since BST insert is a deterministic algorithm, there is only one place thek-th node could be inserted. Therefore the treap with k nodes is also unique, provingthe inductive hypothesis.(b) Show that the expected height of a treap is O(lg n), and hence the expected time tosearch for a value in the treap is O(lg n).Solution: The idea is to realize that a treap on n nodes is equivalent to a randomlybuilt binary search tree on n nodes. Recall that assigning priorities to nodes as theyare inserted into the treap is the same as inserting the n nodes in the increasing orderdefined by their priorities. So if we assign the priorities randomly, we get a randomorder of n priorities, which is the same as a random permutation of the n inputs, sowe can view this as inserting the n items in random order.The time to search for an item is O(h)where h is the height of the tree. As we saw inlecture, E[h]=O(lg n). (The expectation is taken over permutations of the n nodes,i.e., the random choices of the priorities.)Let us see how to insert a new node x into an existing treap. The first thing we do is assign x a random priority priority[x]. Then we call the insertion algorithm, which we call T REAP-I NSERT, whose operation is illustrated in Figure 2.(e) (f)Figure 2: Operation of T REAP-I NSERT. As in Figure 1, each node x is labeled with key[x]: priority[x]. (a) Original treap prior to insertion. (b) The treap after inserting a node with key C and priority 25. (c)–(d) Intermediate stages when inserting a node with key D and priority 9.(e) The treap after insertion of parts (c) and (d) is done. (f) The treap after inserting a node with key F and priority 2.(c) Explain how T REAP-I NSERT works. Explain the idea in English and give pseudocode.(Hint: Execute the usual binary search tree insert and then perform rotations to restorethe min-heap order property.)Solution: The hint gives the idea: do the usual binary search tree insert and thenperform rotations to restore the min-heap order property.T REAP-I NSERT (T,x)inserts x into the treap T(by modifying T). It requires that xhas defined key and priority values. We have used the subroutines T REE-I NSERT,R IGHT-R OTATE, and R IGHT-R OTATE as defined in CLRS.T REAP-I NSERT (T,x)1T REE-I NSERT (T,x)2 while x =root[T]and priority[x]<priority[p[x]]3 do if x=left[p[x]]4 then R IGHT-R OTATE (T,p[x])5 else L EFT-R OTATE (T,p[x])Note that parent pointers simplify the code but are not necessary. Since we only needto know the parent of each node on the path from the root to x(after the call toT REE-I NSERT), we can keep track of these ourselves.(d) Show that the expected running time of T REAP-I NSERT is O(lg n). Solution:T REAP-I NSERT first inserts an item in the tree using the normal binary search treeinsert and then performs a number of rotations to restore the min-heap property.The normal binary-search-tree insertion algorithm T REE-I NSERT always places thenew item at a new leaf of tree. Therefore the time to insert an item into a treap isproportional to the height of a randomly built binary search tree, which as we saw inlecture is O(lg n)in expectation.The maximum number of rotations occurs when the new item receives a priority lessthan all priorities in the tree. In this case it needs to be rotated from a leaf to the root.An upper bound on the number of rotations is therefore the height of a randomly builtbinary search tree, which is O(lg n)in expectation. (We will see that this is a fairlyloose bound.) Because each rotation take constant time, the expected time to rotate isO(lg n).Thus the expected running time of T REAP-I NSERT is O(lg n+lg n)=O(lg n).T REAP-I NSERT performs a search and then a sequence of rotations. Although searching and rotating have the same asymptotic running time, they have different costs in practice. A search reads information from the treap without modifying it, while a rotation changes parent and child pointers within the treap. On most computers, read operations are much faster than write operations. Thus we would like T REAP-I NSERT to perform few rotations. We will show that the expected number of rotations performed is bounded by a constant (in fact, less than 2)!(a) (b)Figure 3: Spines of a binary search tree. The left spine is shaded in (a), and the right spine is shaded in (b).In order to show this property, we need some definitions, illustrated in Figure 3. The left spine of a binary search tree T is the path which runs from the root to the item with the smallest key. In other words, the left spine is the maximal path from the root that consists only of left edges. Symmetrically, the right spine of T is the maximal path from the root consisting only of right edges. The length of a spine is the number of nodes it contains.(e) Consider the treap T immediately after x is inserted using T REAP-I NSERT. Let Cbe the length of the right spine of the left subtree of x. Let D be the length of theleft spine of the right subtree of x. Prove that the total number of rotations that wereperformed during the insertion of x is equal to C+D.Solution: Prove the claim by induction on the number of rotations performed. Thebase case is when x is the parent of y. Performing the rotation so that y is the new rootgives y exactly one child, so C+D=1.Assume for induction that the number of rotations k performed during the insertionof x equals C+D. The base case is when 0 rotations are necessary and x is insertedas a leaf. Then C+D=0. To prove the inductive step, we show that if after k−1rotations C+D=k−1, then after k rotations C+D=k. Draw a picture of aleft and right rotation and observe that C+D increases by 1 in each case. Let y bethe parent of x, and suppose x is a left child of y. After performing a right rotation, ybecomes the right child of x, and the previous right child of x becomes the left childof y. That is, the left spine of the right subtree of x before the rotation is tacked onto y, so the length of that spine increases by one. The left subtree of x is unaffectedby a right rotation. The case of a left rotation is symmetric. Therefore after one morerotation C+D increases by one and k=C+D, proving the inductive hypothesis.We will now calculate the expected values of C and D. For simplicity, we assume that the keys are 1,2,...,n. This assumption is without loss of generality because we only compare keys.�For two distinct nodes x and y , let k = key [x ]and i = key [y ], and define the indicator random variableX 1 if y is a node on the right spine of the left subtree of x (in T ),i,k =0 otherwise .(f) Show that X i,k =1if and only if (1) priority [y ]> priority [x ], (2) key [y ]< key [x ], and(3) for every z such that key [y ]< key [z ]< key [x ],we have p riority [y ]< priority [z ].Solution:To prove this statement, we must prove both directions of the “if and only if”. Firstwe prove the “if” direction. We prove that if (1) priority [y ]> priority [x ], (2) key [y ]<key [x ], and (3) for every z such that key [y ]< key [z ]< key [x ]are true, priority [y ]< priority [z ], then X i,k =1. We prove this by contradiction. Assume that X i,k =0. That is, assume that y is not on the right spine of the left subtree of x . We show thatthis leads to a contradiction. If y is not on the right spine of the left subtree of x ,it could be in one of three places:1. Suppose y is in the right subtree of x . This contradicts condition (2) becausekey [y ]< key [x ].2. Suppose y is not in one of the subtrees of x . Then x and y must share somecommon ancestor z . Since key [y ]< key [x ], we know that y is in the left subtreeof z and x is in the right subtree of z and key [y ]< key [z ] < key [x ]. Since y isbelow z in the tree, priority [z ]< priority [x ]and priority [z ]< priority [y ]. Thiscontradicts condition (3).3. Suppose that y is in the left subtree of x but not on the right spine of the leftsubtree of x . This implies that there exists some ancestor z of y in the left subtreeof x such that y is in the left subtree of z . Hence key [y ]< key [z ]< key [x ]. Sincez is an ancestor of y , priority [z ]< priority [y ], which contradicts condition (3).All possible cases lead to contradictions, and so X i,k =1.Now for the “only if” part. We prove that if X i,k =1, then statements (1), (2), and (3) are true. If X i,k =1, then y is in the right spine of the left subtree of x . Since y is ina subtree of x , y must have been inserted after x ,so p riority [y ]> priority [x ], proving(1). Since y is in the left subtree of x , key [y ]< key [x ], proving (2). We prove (3) by contradiction: suppose that X i,k =1and there exists a z such that key [y ]< key [z ]< key [x ]and priority [z ]< priority [y ]. In other words, z was inserted before y . There arethree possible cases that satisfy the condition key [z ]< key [x ]:1. Suppose z is in the right spine of the left subtree of x .For y to be inserted into theright spine of the left subtree of x , it will have to be inserted into the right subtreeof z . Since key [y ]< key [z ], this leads to a contradiction.2. Suppose z is in the left subtree of x but not in the right spine. This implies thatz is in the left subtree of some node z in the right spine of x . Therefore for y tobe inserted into the right spine of the left subtree of x , it must be inserted into theright subtree of z . This leads to a contradiction by reasoning similar to case 1.3. Suppose that z is not in one of the subtrees of x . Then z and x have a commonancestor z such that z is in the left subtree of z and x is in the right subtree of x .This implies key [z ] < key [z ] < key [x ]. Since key [y ]< key [z ]< key [z ], y cannotbe inserted into the right subtree of z . Therefore it cannot be inserted in a subtreeof x , which is a contradiction.Therefore there can be no z such that key [y ] < key [z ] < key [x ] and priority [z ] < priority [y ]. This proves statement (3). We have proven both the “if” and “only if” directions, proving the claim.(g) Show that(k − i − 1)! 1 Pr {X i,k =1} == . (k − i +1)! (k − i +1)(k − i )Solution: We showed in the previous part that X i,k =1if and only if the priorities of the items between y and x are ordered in a certain way. Since all orderings are equally likely, to calculate the probability we count the number of permutations of priorities that obey this order and divide by the number of total number of priority permutations. We proved in (e) that whether or not X i,k =1depends only on the relative ordering of the priorities of y , x , and all z such that key [y ] < key [z ] < key [x ]. Since we assumed that the keys of the items come from {1,...,n }, the keys of the items in question are i,i +1,i +2,...,k − 1,k . There are (k − i +1)!permutations of the priorities of these items. Of these permutations, the ones for which X i,k =1are those where i has minimum priority, k has the second smallest priority, and the priorities of the remaining k − i − 1 items follow in any order. There are (k − i − 1)! of these permutations. Thus the probability that we get a “bad” order is (k −i −1)!/(k −i +1)!= 1/(k − i )(k − i +1).(h) Show thatk −1 � 1 1 E [C ]= =1− . j (j +1)k j =1 Solution:X For a node x with key k , E [C ]is the expected number of nodes in the right spine of the left subtree of x . This equals the sum of the expected value of the random variables i,k for all i in the tree. Since X i,k =0for all nodes i ≥ k , we only need to consider i <k .� � � k −1 �k −1 � E [C ]=E [X i,k ]=E X i,k i =1 i =1 k −1 =Pr {X i,k =1}i =1 k −1 � 1 =(k − i )(k − i +1) i =1 k −1 � 1= j (j +1)j =1 1To simplify this sum, observe that j (j 1+1) = j +1−j = − 1 . Therefore the sumj (j +1) j j +1 telescopes and we have 1 E [C ]=1− . kIf you didn’t see this, you could have proven that the equationk −1 � 1 1 =1− j (j +1)k j =1 holds by induction on k . In the proving the inductive hypothesis you might have 11discovered 1 − = .j j +1 j (j +1)(i) Use a symmetry argument to show that1 E [D ]=1− . n − k +1Solution: The idea is to consider the treap produced if the ordering relationship amongthe keys is reversed. That is, for all items x , leave priority [x ]unchanged but replacekey [x ]with n − key [x ]+1.Let T be the binary tree we get when inserting the items (in increasing order of priority) using the original keys. Once we remap the keys and insert them into a newbinary search tree, we get a tree T whose shape is the mirror image of the shape ofT . (reflected left to right). Consider the item x with key k in T and therefore has key n − k +1 i n T . The length of the left spine of x ’s right subtree in T has becomethe length of the right spine of x ’s left subtree in T . We know by part (g) that the expected length of the right spine of a left subtree of a node y is 1− 1/idkey [y ],so the expected length of the right spine of the left subtree of x in T is 1− 1/(n − k +1), which means that 1 E [D ]=1− . n − k +1(j) Conclude that the expected number of rotations performed when inserting a node into a treap is less than 2.Solution:11 E [number of rotations ]= E [C +D ]=E [C ]+E [D ]=1− +1− k n − k +1 ≤ 1+1=2. Problem 4-2. Being balancedCall a family of trees balanced if every tree in the family has height O (lg n ), where n is the number of nodes in the tree. (Recall that the height of a tree is the maximum number of edges along any path from the root of the tree to a leaf of the tree. In particular, the height of a tree with just one node is 0.)For each property below, determine whether the family of binary trees satisfying that property is balanced. If you answer is “no”, provide a counterexample. If your answer is “yes”, give a proof (hint: it should be a proof by induction). Remember that being balanced is an asymptotic property, so your counterexamples must specify an infinite set of trees in the family, not just one tree. (a) Every node of the tree is either a leaf or it has two children.Solution: No. Counterexample is a right chain, with each node having a leaf hanging off to the left(b) The size of each subtree can be written as 2k − 1, where k is an integer (k is not the same for each subtree).Solution: Yes.Consider any subtree with root r . We know from the condition that the size of this subtree is 2k 1 − 1. We also know that the size of the subtree rooted at the left child of r is 2k 2 − 1, and the size of the subtree rooted at the right child of r is 2k 3 − 1. But the size of the subtree at r is simply the node r together with the nodes in the left and right subtrees. This leads to the equation 2k 1 − 1=1+(2k 2 − 1)+(2k 3 − 1),or 2k 1 =2k 2 +2k 3. Now we show that k 2 =k 3. This is easy to see if you consider the binary representations of k 1, k 2, and k 3.Otherwise, if we assume WLOG that k 2 ≤ k 3, then we have 2k 1−k 2 =1+2k 3−k 2. 2Now, the only pair of integer powers of 2 that could satisfy this equation are 21 and 0 . Thus k 3 − k 2 =0,or k 2 =k 3, and the left and right subtrees of r have an equal number of nodes. It follows that the tree is perfectly balanced.(c) There is a constant c>0such that, for each node of the tree, the size of the smallerchild subtree of this node is at least c times the size of the larger child subtree.Solution:Yes1. The proof is by induction. Assume that the two subtrees of x with n nodes in itssubtree has two children y and z with subtree sizes n1 and n2. By inductive hypothesis,the height of y’s subtree is at most d lg n1 and the height of z’s subtree is at most d lg n2for some constant d. We now prove that the height of x’s subtree is at most d lg n.Assume wlog that n1 ≥n2. Therefore, by the problem statement, we have n2 ≥cn1.Therefore, we have n=n1 +n2 +1≥(1+c)n1 +1≥(1+c)n1 and the height hof x’s subtree is d lg n1 +1≤d lg(n/(c+1))+1≤d lg n−d lg(1+c)+1≤d lg nif d lg(1+c)≥1. Therefore, for sufficiently large d, the height of a tree with n nodesis at most d lg n.(d) There is a constant c such that, for each node of the tree, the heights of its childrensubtrees differ by at most c.Solution: Yes1. Let n(h)be the minimum number of nodes that a tree of height h thatsatisfies the stated property can have. We show by induction that n(h)≥(1+α)h−1,for some constant 0<α≤1. We can then conclude that for a tree with n nodes,h≤log1+α(n+1)=O(lg n).For the base case, a subtree of height 0has a single node, and 1≥(1+α)0 −1forany constant α≤1.In the inductive step, assume for all trees of height k<h, that the n(k)≥(1+α)k−1.Now consider a tree of height h, and look at its two subtrees. We know one subtreemust have height h−1, and the other must have height at least h−1−c. Therefore,we known(h)≥n(h−1)+n(h−1−c)+1.Using the inductive hypothesis, we getn(h) ≥(1+α)h−1 −1+(1+α)h−1−c−1+1≥2(1+α)h−1−c−1.Suppose we picked αsmall enough so that (1+α)<21/(c+1). Then (1+α)c+1 <2.Therefore, we getn(h)≥2(1+α)h−1−c−1≥(1+α)h−1.1Note that in this problem we assume that a nil pointer is a subtree of size 0, and so a node with only one child has two subtrees, one of which has size 0. If you assume that a node with only one child has only one subtree, then the answer to this problem part is “no”.�11Handout18: Problem Set4SolutionsTherefore, we satisfy the inductive hypothesis.Note that if we plug this value for αback into h≤log1+α(n+1),we getlg(n+1)h≤≤(c+1)l g(n+1).lg(1+2c+1)(e) The average depth of a node is O(lg n). (Recall that the depth of a node x is thenumber of edges along the path from the root of the tree to x.)Solution: No.√Consider a tree with n−n nodes organized as a complete binary tree, and the other √ √n nodes sticking out as a chain of length n from the balanced tree. The height of√√√the tree is lg(n−n)+n=Ω(n), while the average depth of a node is at most�√√ √(1/n)n·(n+lg n)+(n−n)·lg n√√=(1/n)(n+n lg n+n lg n−nlgn)=(1/n)(n+n lg n)=O(lg n)√Thus, we have a tree with average node depth O(lg n), but height Ω(n).。
算法设计与分析(王多强)作业参考答案.docx

第二章递归习题导论4.1-17(/?) = 27(b / 2)+ 1=> M = 2T5 /2) + 1%)习题导论4.1-6Tin) = 2T(0) + 1做代换:m=log2n另 S(m)=T(2m )则有: S(/z?) = 2S(zz? / 2) + 1 化简有:S(m)=O(m) 所以 T(n)=O(logn)习题4.2-27(/7)= T(n / 3) + 7(2/7 / 3) + 劲 注意最长分支 2n/3-*(2n/3)2 -*(2n/3)3...-*(2n^)log3/2n 习题4.3-1a) T(n) = 4T(n/2) + nb) T(n) = 4T(n/2) + n 2c 取大于1/2小于1的数即可,如珈习题4.3-4f(n )/nlogba = n 2log n/n'°g"二 log nvn所以不满足规则3直接化简即可,T(n)=O(n 2log 2n)c) T(n) = 4T(n/2) + n 3情况 3, ◎ (r?). 验证 4f(n/2)=4(n/2)3=n 3/2^cn 3,这里7X2")27(2"/彳)+情况4 0(n 2)情况 2, © (n 2logn)第三章习题4.5注意三分Z—和三分Z二分割点的计算ml = (2low+high)^m2 = (low+2high)/3习题4.20主要是验证T(n/r) + T(0)>|« n/r+O的数量级是否小于n的1次方(线性) 利用关系式:\n / r」n (/7 - r - 1) / /进行化简r=3:\r / 2~|~|_/2 / /_] / 2~| > 2 z? / r / 2 = n / r」> (/? 一2) / 3则,刀一卜/2北刀 / 厂」/ 2] < /? - (/? - 2) / 3 = 2/7 / 3 + 2 / 3 则,n〃 +羊n +厉超线性了r=7:\r / 2]\n / r\/ 2〕>/ 7」/2 = 2山 / 7」> 2(刀一6) / 7则,n - \r / i\\n / /」/ 2〕v 刀一2(刀一6) / 7 = 5刀 / 7 + 12 / 7可证,当n>48的时候,上式小于3伙则,n/7+3nA = 25n/28 <n 成立r=9:\r / 2][n / 厂」/ 2〕> 5[刀 / 9」/ 2 = (5 / 2)^/9」> 5(刀-8)/18n一\r / 2\[n / /」/ 2〕< 13/?/18 + 40/18可证,当n>20的时候,上式小于7n/8 则,n/9+7n/8 = 71n/72 <n 成立r=ll习题4.25肓接带入验证即可棋盘覆盖问题角上用一个骨牌覆盖,认为构造有特殊方格的区域,然后在四个区域上递归求解即可第四章中位数中位数习题导论9-2A)比较明显。
算法导论参考答案

算法导论参考答案算法导论参考答案算法导论是计算机科学领域中一本经典的教材,被广泛应用于计算机科学和工程的教学和研究中。
它涵盖了算法设计和分析的基本概念,以及各种常见算法的实现和应用。
本文将为读者提供一些算法导论中常见问题的参考答案,以帮助读者更好地理解和掌握这门课程。
1. 什么是算法?算法是一系列解决问题的步骤和规则。
它描述了如何将输入转换为输出,并在有限的时间内完成。
算法应具备正确性、可读性、健壮性和高效性等特点。
2. 如何分析算法的效率?算法的效率可以通过时间复杂度和空间复杂度来衡量。
时间复杂度表示算法执行所需的时间量级,常用的时间复杂度有O(1)、O(n)、O(logn)、O(nlogn)和O(n^2)等。
空间复杂度表示算法执行所需的额外空间量级,通常以字节为单位。
3. 什么是渐进符号?渐进符号用于表示算法的时间复杂度或空间复杂度的增长趋势。
常见的渐进符号有大O符号、Ω符号和Θ符号。
大O符号表示算法的上界,Ω符号表示算法的下界,Θ符号表示算法的平均情况。
4. 什么是分治法?分治法是一种算法设计策略,将问题分解为若干个子问题,并对子问题进行独立求解,最后将子问题的解合并得到原问题的解。
典型的分治算法有归并排序和快速排序。
5. 什么是动态规划?动态规划是一种通过将问题分解为相互重叠的子问题来求解的方法。
它通常用于求解具有重叠子问题和最优子结构性质的问题。
典型的动态规划算法有背包问题和最短路径问题。
6. 什么是贪心算法?贪心算法是一种通过每一步选择局部最优解来求解整体最优解的方法。
贪心算法通常不能保证得到全局最优解,但在某些问题上能够得到近似最优解。
典型的贪心算法有霍夫曼编码和最小生成树算法。
7. 什么是图算法?图算法是一类用于解决图结构相关问题的算法。
图由节点和边组成,节点表示对象,边表示对象之间的关系。
图算法包括图的遍历、最短路径、最小生成树和网络流等问题的求解。
8. 什么是NP完全问题?NP完全问题是一类在多项式时间内无法求解的问题。
[1]算法导论
实例:求最大公约数
算法1.1 Euclid(m,n)
输入:非负整数 m, n,其中m与n不全为0 输出:m 与 n 的最大公约数 1. while m>0 do 2. r n mod m 3. n m 4. m r 5. return n
实例:改进的顺序检索
算法1.2 Search(L,x)
课程主要内容
近似 算法
随机 算法
处理难解问 题的策略
问题处理策略 计算复杂性理论 算法分析方法 算法设计技术 基础知识
NP 完全理论 算法分析与问题的计算复杂性 分治 动态 贪心 回溯与 策略 规划 算法 分支限界 数学基础、数据结构
算法的基本概念
1. 2. 3. 4. 5. 为什么要研究算法? 什么是算法? 算法化求解问题的过程 重要的问题类型 算法设计策略
Decrease and conquer Transform and conquer
20
Backtracking and Branch and bound Space and time tradeoffs
求:总等待时间最少的调度方案,即求S的排列i1, i2, …, in使得
min{k 1 ( n k 1)t ik }
n
求解方法 • 贪心策略:加工时间短的先做 • 如何描述这个方法?这个方法是否对所有的实例都能得到 最优解?如何证明?这个方法的效率如何?
例2 排序算法的评价 已有的排序算法:考察元素比较次数
2-1. 计算判别式d 2-2. 根据d的值进行不同处理 2-2-1:if d>0 x1=… x2=… 2-2-2:if d=0 x1=x2=… 2-2-3:if d<0 ….
4 算法的伪码描述
算法分析与设计作业(一)及参考答案
《算法分析与设计》作业(一)本课程作业由两部分组成。
第一部分为“客观题部分”,由15个选择题组成,每题1分,共15分。
第二部分为“主观题部分”,由简答题和论述题组成,共15分。
作业总分30分,将作为平时成绩记入课程总成绩。
客观题部分:一、选择题(每题1分,共15题)1、递归算法:(C )A、直接调用自身B、间接调用自身C、直接或间接调用自身D、不调用自身2、分治法的基本思想是将一个规模为n的问题分解为k个规模较小的字问题,这些子问题:(D )A、相互独立B、与原问题相同C、相互依赖D、相互独立且与原问题相同3、备忘录方法的递归方式是:(C )A、自顶向下B、自底向上C、和动态规划算法相同D、非递归的4、回溯法的求解目标是找出解空间中满足约束条件的:(A )A、所有解B、一些解C、极大解D、极小解5、贪心算法和动态规划算法共有特点是:( A )A、最优子结构B、重叠子问题C、贪心选择D、形函数6、哈夫曼编码是:(B)A、定长编码B、变长编码C、随机编码D、定长或变长编码7、多机调度的贪心策略是:(A)A、最长处理时间作业优先B、最短处理时间作业优先C、随机调度D、最优调度8、程序可以不满足如下性质:(D )A、零个或多个外部输入B、至少一个输出C、指令的确定性D、指令的有限性9、用分治法设计出的程序一般是:(A )A、递归算法B、动态规划算法C、贪心算法D、回溯法10、采用动态规划算法分解得到的子问题:( C )A、相互独立B、与原问题相同C、相互依赖D、相互独立且与原问题相同11、回溯法搜索解空间的方法是:(A )A、深度优先B、广度优先C、最小耗费优先D、随机搜索12、拉斯维加斯算法的一个显著特征是它所做的随机选性决策有可能导致算法:( C )A、所需时间变化B、一定找到解C、找不到所需的解D、性能变差13、贪心算法能得到:(C )A、全局最优解B、0-1背包问题的解C、背包问题的解D、无解14、能求解单源最短路径问题的算法是:(A )A、分支限界法B、动态规划C、线形规划D、蒙特卡罗算法15、快速排序算法和线性时间选择算法的随机化版本是:( A )A、舍伍德算法B、蒙特卡罗算法C、拉斯维加斯算法D、数值随机化算法主观题部分:二、写出下列程序的答案(每题2.5分,共2题)1、请写出批处理作业调度的回溯算法。
背包问题算法导论课程设计
背包问题算法导论课程设计一、课程目标知识目标:1. 理解背包问题的基础概念,掌握其定义和数学模型。
2. 学习并掌握贪心算法、动态规划算法解决0-1背包问题的基本原理和步骤。
3. 能够运用所学算法解决实际的背包问题,并对不同算法进行比较和分析。
技能目标:1. 培养学生的逻辑思维能力,使其能够运用算法思想解决实际问题。
2. 提高学生的编程能力,使其能够独立编写解决背包问题的程序代码。
3. 培养学生的团队协作能力,通过分组讨论和分享,共同解决复杂问题。
情感态度价值观目标:1. 培养学生对算法学习的兴趣,激发其探索精神和创新意识。
2. 引导学生树立正确的价值观,认识到算法在解决实际问题中的重要性。
3. 培养学生面对困难时的坚持和毅力,鼓励他们勇于挑战自我,克服困难。
本课程针对高中年级学生,结合背包问题算法的学科特点,旨在提高学生的逻辑思维和编程能力。
课程要求学生在掌握基本概念和算法原理的基础上,能够将所学知识应用于实际问题的解决。
通过本课程的学习,学生将能够具备解决类似问题的能力,并为后续学习更复杂的算法打下坚实基础。
二、教学内容1. 背包问题基本概念:介绍背包问题的定义、分类以及数学模型。
- 0-1背包问题- 完全背包问题- 多重背包问题2. 贪心算法:讲解贪心算法的基本原理,分析贪心算法在解决背包问题中的应用。
- 贪心策略的选择- 贪心算法的步骤及实现3. 动态规划算法:介绍动态规划的基本思想,分析动态规划在解决背包问题中的应用。
- 动态规划原理- 0-1背包问题的动态规划解法- 完全背包问题的动态规划解法4. 算法分析与比较:对不同算法进行时间复杂度和空间复杂度分析,比较各自的优缺点。
5. 实践环节:通过编程实践,让学生独立解决背包问题,并分组讨论、分享经验。
6. 拓展与提高:介绍其他解决背包问题的算法,如分支限界法等,拓展学生的知识面。
教学内容依据课程目标,紧密结合教材,按照教学大纲进行安排。
课程进度分为基础理论、算法分析与实践、拓展与提高三个阶段,以确保学生能够系统、科学地掌握背包问题算法的相关知识。
算法导论第二次作业答案
Solution: First, let’s analyze the Activity Selection Problem again: This is a problem using greedy algorithm: Input: 1. n activities a1, a2, . . . , an; 2. for i = 1, 2, . . . , n, the activity ai has a start time si and a finish time fi: [si, fi) Output: Pick a maximum set of activities that are compatible in time.
Solution: First, let’s analyze the Huffman Code again:
This is a problem using greedy algorithm:
Input: 1. n symbols s1, s2, . . . , sn ; 2. every symbol si has a frequency fi
Assume the time period of each activity is shown as following table:
i
123
si
157
fi
469
duration 3 1 2
We will choose the a2 which has the least duration among all three activities. However, it is obvious that the best arrangement is to choose {a1, a3}. So the approach of selecting the activity of least duration from among those that are compatible with previously selected activities does not work.
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
IntroductiontoAlgorithms
MassachusettsInstituteofTechnology6.046J/18.410J
Singapore-MITAllianceSMA5503
ProfessorsErikDemaine,LeeWeeSun,andCharlesE.LeisersonHandout6
GradeGrade
18
29
310
411
512
613
714
SubtotalSubtotal
Total
Name:
2
Handout6:DiagnosticQuiz0
Problem1
Considerthefollowingpseudocode:
R
OUTINE
1if
2thenreturn
3elsereturnR
OUTINE
(a)Giveaone-sentencedescriptionofwhatROUTINEdoes.(Remember,don’tguess.)
(b)Giveapreconditionfortheroutinetoworkcorrectly.
(c)Giveaone-sentencedescriptionofafasterimplementationofthesameroutine.
Problem2
Giveashort(1–2-sentence)descriptionofeachofthefollowingdatastructures:
(a)FIFOqueue
(b)Priorityqueue
Handout6:DiagnosticQuiz0
3
(c)Hashtable
Problem3
Using
-notation,describetheworst-caserunningtimeofthebestalgorithmthatyouknowfor
eachofthefollowing:
(a)Findinganelementinasortedarray.
(b)Findinganelementinasortedlinked-list.
(c)Insertinganelementinasortedarray,oncethepositionisfound.
(d)Insertinganelementinasortedlinked-list,oncethepositionisfound.
4
Handout6:DiagnosticQuiz0
Problem4
Describeanalgorithmthatlocatesthefirstoccurrenceofthelargestelementinafinitelistof
integers,wheretheintegersarenotnecessarilydistinct.Whatistheworst-caserunningtimeof
youralgorithm?
Problem5
Howdoestheheightofabalancedbinarysearchtreerelatetothenumberofnodesinthetree?
Problem6
Doesanundirectedgraphwith
vertices,eachofdegree,exist?Ifso,drawsuchagraph.Ifnot,
explainwhynosuchgraphexists.
Handout6:DiagnosticQuiz0
5
Problem7
ItisknownthatifasolutiontoProblemAexists,thenasolutiontoProblemBexistsalso.
(a)ProfessorGoldbachhasjustproduceda1,000-pageproofthatProblemAisunsolvable.If
hisproofturnsouttobevalid,canweconcludethatProblemBisalsounsolvable?Answeryesor
no(ordon’tknow).
(b)ProfessorWileshasjustproduceda10,000-pageproofthatProblemBisunsolvable.Ifthe
proofturnsouttobevalid,canweconcludethatproblemAisunsolvableaswell?Answeryesor
no(ordon’tknow).
Problem8
Considerthefollowingstatement:
If
pointsareplacedanywhereonorinsideaunitsquare,thentheremustexisttwo
thatarenomorethan
unitsofoneoftheother
points,sincethefurthestfromthecornersitcanbeisthecenter,whichisexactly
units.Sincetherearepointsandonlysquares,atleasttwopointsmustfallon
orinsideoneofthesmallersquares,givingasetofpointsthatarenomorethan
6
Handout6:DiagnosticQuiz0
Problem9
Giveaninductiveproofofthefollowingstatement:
Foreverynaturalnumber
,wehave.
Problem10
Wewanttolineupoutofchildren.Whichofthefollowingexpressesthenumberofpossible
line-ups?(Circletherightanswer.)
(a)
(b)
(c)
(d)
(e)Noneoftheabove
(f)Don’tknow
Problem11
Adeckof
cardsisshuffledthoroughly.Whatistheprobabilitythattheacesareallnextto
eachother?(Circletherightanswer.)
(a)
(b)
(c)
(d)
(e)Noneoftheabove
(f)Don’tknow
Handout6:DiagnosticQuiz0
7
Problem12
TheweatherforecastersaysthattheprobabilityofrainonSaturdayis
andthattheprobability
ofrainonSundayis
.Considerthefollowingstatement:
Theprobabilityofrainduringtheweekendis
.
Whichofthefollowingbestdescribesthevalidityofthisstatement?
(a)Ifthetwoevents(rainonSat/rainonSun)areindependent,thenwecanaddupthetwo
probabilities,andthestatementistrue.Withoutindependence,wecan’ttell.
(b)True,whetherthetwoeventsareindependentornot.
(c)Iftheeventsareindependent,thestatementisfalse,becausethetheprobabilityofnorain
duringtheweekendis
.Iftheyarenotindependent,wecan’ttell.
(d)False,nomatterwhat.
(e)Noneoftheabove.
(f)Don’tknow.
Problem13
Aplayerthrowsdartsatatarget.Oneachtrial,independentlyoftheothertrials,hehitsthebull’s-
eyewithprobability
.Howmanytimesshouldhethrowsothathisprobabilityisofhitting
thebull’s-eyeatleastonce?
(a)3
(b)4
(c)5
(d)
can’tbeachieved.
(e)Don’tknow.
8
Handout6:DiagnosticQuiz0
Problem14
Let
beanindicatorrandomvariable.Whichofthefollowingstatementsaretrue?(Circleall
thatapply.)
(a)
(b)
(c)
(d)