算法导论试卷

合集下载

中科大算法导论期末试卷及答案

中科大算法导论期末试卷及答案
2. (卷 1)已知 f1(n)=Θ(g1(n)),f2(n)=Θ(g2(n)),请问是否有 f1(n)+ f2(n)= Θ( max( g1(n),g2(n) ) )?
解:存在������1(n) + ������2(������) = ������(max(������1(������), ������2(������) 证明: ������1(������) = ������(������1(n)) 则存在 a1>0,a2>0, n1>0 使得 n>n1 时有 ������1 ∗ ������1(n) < ������1(������) < ������2 ∗ ������1(n) ������2(������) = ������(������2(n)) 则存在 b1>0,b2>0, n2>0 使得 n>n2 时有 ������1 ∗ ������2(n) < ������2(������) < ������2 ∗ ������2(n) 取 c1=min(a1,b1) >0, c2=2*max(a2,b2) >0, n0=max(n1,n2)>0 当 n>n0 时,有 ������1(n) + ������2(������) > ������1 ∗ ������1(n) + ������1 ∗ ������2(n)
= ������2(������������ − 5 ������������������������) − 2������ > 2������3 − 2������ > 2������0(������02 − 1) =12 即当 c=7, n0=2 时,对 n>n0, 5������2������������������������ + 2������ < ������������3恒成立, 5������2������������������������ + 2������ = ������(������3)

算法导论-9.红黑树习题

算法导论-9.红黑树习题

算法导论-9.红⿊树习题这⼀篇解决《算法导论》中红⿊树章节的部分习题,在上⼀篇⾃⼰亲⾃实现红⿊树后,解决这些题⽬就轻松多了。

练习13.1-6 在⼀棵⿊⾼度为 $k$ 的红⿊树中,内节点最多有多少个?最少有多少个?⿊⾼度为 $k$ 的⼆叉树,全⾼度最⼩为 $k+1$,最⼤为 $2k+2$ 。

内节点最多有 $2^{k+1}-1$ 个,这种情况下红⿊树中没有红节点,⿊节点全满(满⾜所有叶⼦节点⿊⾼度⼀致的条件);内节点最多有 $2^{2k+2}-1=4^{k+1}-1$ 个。

这种情况下红⿊树全满。

练习13.1-7 在 $n$ 个关键字上构造出来的⼆叉树,红节点与⿊节点个数的⽐值最⼤为多少?最⼩是多少?红节点最多时,⽐值为:$$\frac{n-2^{h-1}-2^{h-3}-...-(2)-1}{2^{h-1}+2^{h-3}+...+(2)+1},h=\lfloor\lg n\rfloor$$红节点最少时,⽐值时为:$$\frac{n-2^{\lfloor\lg n\rfloor}}{2^{\lfloor\lg n\rfloor}}$$练习13.2-2 证明,在⼀棵 $n$ 个节点的⼆叉查找树中,刚好有 $n-1$ 种可能的旋转。

思路:每⼀个可能的旋转对应于⼀条边,每⼀个条边也只能对应⼀个可能的旋转,因此可能的旋转数就是边的数⽬。

每⼀条边都对应⼀个⼉⼦节点,每⼀个节点(除了根节点)都对应⼀个边,所以边的数⽬为 $n-1$ ,也就是可能的旋转的数⽬。

练习13.2-4 证明任意⼀颗含有 $n$ 个节点的⼆叉查找树都能通过 $O(n)$ 次旋转,转变为另⼀颗含有同样节点(节点位置可以任意不⼀样,但仍然保持⼆叉查找树性质)的⼆叉查找树。

思路:考虑⼀颗⼆叉查找树的“右链”,即从根节点向具有最⼤节点值的节点的路径。

不断地右旋右链上具有左⼦树的节点,每⼀次旋转可以使右链上多⼀个节点,(⼜,右链上⾄少有⼀个节点,根节点),所以⾄多 $n-1$ 次右旋后,⼆叉树的右链上连接了所有的节点,这时⼆叉树实际上称了⼀个已排序(旋转保持⼆叉查找树的性质)的单链表。

算法导论习题答案

算法导论习题答案

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 Θ。

USC算法导论作业2

USC算法导论作业2
CSCI 303 Homework 2
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.

算法导论题目

算法导论题目

• A map M = {r1 , r2 , . . . , rn } is a set of n roads. • A view rectangle V = �(Vx1 , Vy1 ), (Vx2 , Vy2 )� specifies the rectangular region that should be displayed by giving the coordinates of the rectangle’s lower-left and upper-right corners, (Vx1 , Vy1 ) and (Vx2 , Vy2 ) respectively. • A road r is visible in the view rectangle V if it intersects the interior of the rectangle V . There are two types of visible roads r: Type 1: One or both endpoints of the road r are inside the view rectangle V .
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 convo­ luted and obtuse descriptions.

算法导论课程考试

算法导论课程考试

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.。

USC算法导论作业3

USC算法导论作业3

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 ).。

算法基础试题及答案

算法基础试题及答案

算法基础试题及答案一、单项选择题(每题2分,共10分)1. 以下哪个选项是算法的基本特征之一?A. 有穷性B. 可行性C. 确定性D. 以上都是答案:D2. 在算法设计中,以下哪个步骤是不必要的?A. 问题定义B. 算法描述C. 算法实现D. 算法测试答案:D3. 算法的时间复杂度通常用来描述什么?A. 算法的运行时间B. 算法的空间需求C. 算法的执行步骤数量D. 算法的输入数据大小答案:A4. 以下哪个不是算法设计的基本方法?A. 递归B. 排序C. 搜索D. 迭代答案:B5. 在算法分析中,大O符号表示什么?A. 算法执行的时间B. 算法执行的空间C. 算法执行的最坏情况D. 算法执行的平均情况答案:C二、填空题(每题2分,共10分)1. 算法的输入输出定义了算法的______,算法的步骤定义了算法的______。

答案:功能;实现2. 算法的时间复杂度和空间复杂度是衡量算法______的两个重要指标。

答案:效率3. 在算法设计中,______是一种通过重复执行代码块来实现的算法结构。

答案:循环4. 递归算法通常包括两个基本部分:______和______。

答案:基本情况;递归情况5. 在算法分析中,______复杂度描述了算法执行过程中所需的存储空间。

答案:空间三、简答题(每题5分,共20分)1. 请简述算法的五个基本特征。

答案:算法的五个基本特征包括有穷性、确定性、可行性、输入和输出。

有穷性指算法必须在执行有限步骤后结束;确定性指算法的每一步都必须有明确的定义;可行性指算法的每一步都必须足够基本,以至于可以精确地执行;输入指算法有0个或多个输入,以描述运算的对象和初始条件;输出指算法至少有一个输出,输出表示算法运行的结果。

2. 算法的时间复杂度和空间复杂度有什么区别?答案:时间复杂度主要关注算法执行所需的时间,它通常与算法中操作的数量有关,而空间复杂度则关注算法执行过程中所需的存储空间。

经典算法试题及答案

经典算法试题及答案

经典算法试题及答案题目一:找出旋转排序数组中的最小值题目描述:假设按照升序排序的数组在预先未知的某个点上进行了旋转。

例如,数组 `[0,1,2,4,5,6,7]` 可能变为`[4,5,6,7,0,1,2]`。

请找出并返回数组中的最小元素。

说明:- 原数组是一个升序排序的数组- 数组中可能包含重复的元素- 你的算法应该具有 O(log n) 的时间复杂度答案解析:这个问题可以通过二分查找的方法来解决。

以下是详细的解题步骤:1. 初始化两个指针 `left` 和 `right` 分别指向数组的开头和结尾。

2. 当 `left` 小于 `right` 时,执行以下步骤:- 找到中间位置 `mid`。

- 如果 `nums[mid]` 大于 `nums[right]`,则最小值在 `mid+1` 到 `right` 之间,更新 `left = mid + 1`。

- 如果 `nums[mid]` 小于 `nums[right]`,则最小值在 `left` 到 `mid` 之间,更新 `right = mid`。

- 如果 `nums[mid]` 等于 `nums[right]`,则无法判断最小值的位置,需要减少 `right`。

3. 当 `left` 等于 `right` 时,返回 `nums[left]`。

代码实现:```pythondef findMin(nums):left, right = 0, len(nums) - 1while left < right:mid = left + (right - left) // 2if nums[mid] > nums[right]:left = mid + 1elif nums[mid] < nums[right]:right = midelse:right -= 1return nums[left]```题目二:合并两个有序链表题目描述:将两个有序链表合并为一个新的有序链表。

算法导论答案 (4)

算法导论答案 (4)

算法导论答案第一章:算法概述啊算法的定义算法是一系列解决问题的明确指令。

它是一个有穷步骤集,其中每个步骤或操作由确定性和可行性特征。

算法是通过将预期的输入转换为输出来解决问题的工具。

第二章:插入排序插入排序的思想插入排序是一种简单直观的排序算法,其基本思想是将待排序的序列分为已排序和未排序两部分,每次从未排序的部分中取出一个元素,并将其插入到已排序部分的正确位置,直到所有元素都被排序。

插入排序的算法实现以下是插入排序的伪代码:INSERTION-SORT(A)for j = 2 to A.lengthkey = A[j]// Insert A[j] into the sorted sequence A[1.. j-1].i = j - 1while i > 0 and A[i] > keyA[i + 1] = A[i]i = i - 1A[i + 1] = key插入排序的时间复杂度插入排序的时间复杂度为O(n^2),其中n是排序的元素个数。

虽然插入排序的最坏情况下的复杂度很高,但是对于小规模的数据集,插入排序是一种较快的排序算法。

第三章:分治策略分治策略的基本思想分治策略是一种解决问题的思想,它将问题的规模不断缩小,直到问题足够小而可以直接解决。

然后将子问题的解合并起来,得到原问题的解。

分治策略的应用实例一种经典的应用分治策略的算法是归并排序。

归并排序将待排序的序列划分为两个子序列,分别排序后再将两个有序子序列合并为一个有序序列。

以下是归并排序的伪代码:MERGE-SORT(A, p, r)if p < rq = floor((p + r) / 2)MERGE-SORT(A, p, q)MERGE-SORT(A, q + 1, r)MERGE(A, p, q, r)MERGE(A, p, q, r)n1 = q - p + 1n2 = r - qlet L[1..n1+1] and R[1..n2+1] be new arraysfor i = 1 to n1L[i] = A[p + i - 1]for j = 1 to n2R[j] = A[q + j]L[n1 + 1] = infinityR[n2 + 1] = infinityi = 1j = 1for k = p to rif L[i] <= R[j]A[k] = L[i]i = i + 1elseA[k] = R[j]j = j + 1分治策略的时间复杂度归并排序的时间复杂度为O(nlogn),其中n是待排序序列的长度。

算法考试试题及答案

算法考试试题及答案

精品文档一、填空题(本题10 分,每空 1 分)1、算法的复杂性是的度量,是评价算法优劣的重要依据。

2、设 n 为正整数,利用大“O(·)”记号,将下列程序段的执行时间表示为n 的函数,则下面程序段的时间复杂度为。

i=1; k=0;while(i<n) { k=k+10*i;i++; }3、计算机的资源最重要的是和资源。

因而,算法的复杂性有和之分。

n24、 f(n)= 6 ×2+n,f(n) 的渐进性态 f(n)= O()5、递归是指函数或者通过一些语句调用自身。

6、分治法的基本思想是将一个规模为n 的问题分解为k 个规模较小的子问题,这些子问题互相且与原问题相同。

二、选择题(本题20 分,每小题2 分)1、分支限界法与回溯法都是在问题的解空间树T 上搜索问题的解 , 二者 () 。

A. 求解目标不同 , 搜索方式相同B.求解目标不同 , 搜索方式也不同C. 求解目标相同 , 搜索方式不同D.求解目标相同 , 搜索方式也相同2、回溯法在解空间树T 上的搜索方式是 ( )。

A. 深度优先B.广度优先C.最小耗费优先D.活结点优先3、在对问题的解空间树进行搜索的方法中, 一个活结点最多有一次机会成为活结点的是( ) 。

A. 回溯法B.分支限界法C.回溯法和分支限界法D. 回溯法求解子集树问题4、以下关于判定问题难易处理的叙述中正确的是( ) 。

A.可以由多项式时间算法求解的问题是难处理的B.需要超过多项式时间算法求解的问题是易处理的C.可以由多项式时间算法求解的问题是易处理的D.需要超过多项式时间算法求解的问题是不能处理的5、设 f(N),g(N) 是定义在正数集上的正函数, 如果存在正的常数 C 和自然数 N0,使得当 N≥N0时有 f(N) ≤Cg(N), 则称函数 f(N)当 N 充分大时有上界g(N), 记作 f(N)=O(g(N)),即 f(N) 的阶( )g(N) 的阶。

算法导论习题答案 (1)

算法导论习题答案 (1)

Introduction to Algorithms September 24, 2004Massachusetts Institute of Technology 6.046J/18.410J Professors Piotr Indyk and Charles E. Leiserson Handout 7Problem Set 1 SolutionsExercise 1-1. Do Exercise 2.3-7 on page 37 in CLRS.Solution:The following algorithm solves the problem:1.Sort the elements in S using mergesort.2.Remove the last element from S. Let y be the value of the removed element.3.If S is nonempty, look for z=x−y in S using binary search.4.If S contains such an element z, then STOP, since we have found y and z such that x=y+z.Otherwise, repeat Step 2.5.If S is empty, then no two elements in S sum to x.Notice that when we consider an element y i of S during i th iteration, we don’t need to look at the elements that have already been considered in previous iterations. Suppose there exists y j∗S, such that x=y i+y j. If j<i, i.e. if y j has been reached prior to y i, then we would have found y i when we were searching for x−y j during j th iteration and the algorithm would have terminated then.Step 1 takes �(n lg n)time. Step 2 takes O(1)time. Step 3 requires at most lg n time. Steps 2–4 are repeated at most n times. Thus, the total running time of this algorithm is �(n lg n). We can do a more precise analysis if we notice that Step 3 actually requires �(lg(n−i))time at i th iteration.However, if we evaluate �n−1lg(n−i), we get lg(n−1)!, which is �(n lg n). So the total runningi=1time is still �(n lg n).Exercise 1-2. Do Exercise 3.1-3 on page 50 in CLRS.Exercise 1-3. Do Exercise 3.2-6 on page 57 in CLRS.Exercise 1-4. Do Problem 3-2 on page 58 of CLRS.Problem 1-1. Properties of Asymptotic NotationProve or disprove each of the following properties related to asymptotic notation. In each of the following assume that f, g, and h are asymptotically nonnegative functions.� (a) f (n ) = O (g (n )) and g (n ) = O (f (n )) implies that f (n ) = �(g (n )).Solution:This Statement is True.Since f (n ) = O (g (n )), then there exists an n 0 and a c such that for all n √ n 0, f (n ) ←Similarly, since g (n )= O (f (n )), there exists an n � 0 and a c such that for allcg (n ). �f (n ). Therefore, for all n √ max(n 0,n Hence, f (n ) = �(g (n )).�()g n ,0← �),0c 1 � g (n ) ← f (n ) ← cg (n ).n √ n c � 0 (b) f (n ) + g (n ) = �(max(f (n ),g (n ))).Solution:This Statement is True.For all n √ 1, f (n ) ← max(f (n ),g (n )) and g (n ) ← max(f (n ),g (n )). Therefore:f (n ) +g (n ) ← max(f (n ),g (n )) + max(f (n ),g (n )) ← 2 max(f (n ),g (n ))and so f (n ) + g (n )= O (max(f (n ),g (n ))). Additionally, for each n , either f (n ) √max(f (n ),g (n )) or else g (n ) √ max(f (n ),g (n )). Therefore, for all n √ 1, f (n ) + g (n ) √ max(f (n ),g (n )) and so f (n ) + g (n ) = �(max(f (n ),g (n ))). Thus, f (n ) + g (n ) = �(max(f (n ),g (n ))).(c) Transitivity: f (n ) = O (g (n )) and g (n ) = O (h (n )) implies that f (n ) = O (h (n )).Solution:This Statement is True.Since f (n )= O (g (n )), then there exists an n 0 and a c such that for all n √ n 0, �)f ()n ,0← �()g n ,0← f (n ) ← cg (n ). Similarly, since g (n ) = O (h (n )), there exists an n �h (n ). Therefore, for all n √ max(n 0,n and a c � such thatfor all n √ n Hence, f (n ) = O (h (n )).cc�h (n ).c (d) f (n ) = O (g (n )) implies that h (f (n )) = O (h (g (n )).Solution:This Statement is False.We disprove this statement by giving a counter-example. Let f (n ) = n and g (n ) = 3n and h (n )=2n . Then h (f (n )) = 2n and h (g (n )) = 8n . Since 2n is not O (8n ), this choice of f , g and h is a counter-example which disproves the theorem.(e) f(n)+o(f(n))=�(f(n)).Solution:This Statement is True.Let h(n)=o(f(n)). We prove that f(n)+o(f(n))=�(f(n)). Since for all n√1, f(n)+h(n)√f(n), then f(n)+h(n)=�(f(n)).Since h(n)=o(f(n)), then there exists an n0such that for all n>n0, h(n)←f(n).Therefore, for all n>n0, f(n)+h(n)←2f(n)and so f(n)+h(n)=O(f(n)).Thus, f(n)+h(n)=�(f(n)).(f) f(n)=o(g(n))and g(n)=o(f(n))implies f(n)=�(g(n)).Solution:This Statement is False.We disprove this statement by giving a counter-example. Consider f(n)=1+cos(�≈n)and g(n)=1−cos(�≈n).For all even values of n, f(n)=2and g(n)=0, and there does not exist a c1for which f(n)←c1g(n). Thus, f(n)is not o(g(n)), because if there does not exist a c1 for which f(n)←c1g(n), then it cannot be the case that for any c1>0and sufficiently large n, f(n)<c1g(n).For all odd values of n, f(n)=0and g(n)=2, and there does not exist a c for which g(n)←cf(n). By the above reasoning, it follows that g(n)is not o(f(n)). Also, there cannot exist c2>0for which c2g(n)←f(n), because we could set c=1/c2if sucha c2existed.We have shown that there do not exist constants c1>0and c2>0such that c2g(n)←f(n)←c1g(n). Thus, f(n)is not �(g(n)).Problem 1-2. Computing Fibonacci NumbersThe Fibonacci numbers are defined on page 56 of CLRS asF0=0,F1=1,F n=F n−1+F n−2for n√2.In Exercise 1-3, of this problem set, you showed that the n th Fibonacci number isF n=�n−� n,�5where �is the golden ratio and �is its conjugate.A fellow 6.046 student comes to you with the following simple recursive algorithm for computing the n th Fibonacci number.F IB(n)1 if n=02 then return 03 elseif n=14 then return 15 return F IB(n−1)+F IB(n−2)This algorithm is correct, since it directly implements the definition of the Fibonacci numbers. Let’s analyze its running time. Let T(n)be the worst-case running time of F IB(n).1(a) Give a recurrence for T(n), and use the substitution method to show that T(n)=O(F n).Solution: The recurrence is: T(n)=T(n−1)+T(n−2)+1.We use the substitution method, inducting on n. Our Induction Hypothesis is: T(n)←cF n−b.To prove the inductive step:T(n)←cF n−1+cF n−2−b−b+1← cF n−2b+1Therefore, T(n)←cF n−b+1provided that b√1. We choose b=2and c=10.∗{For the base case consider n0,1}and note the running time is no more than10−2=8.(b) Similarly, show that T(n)=�(F n), and hence, that T(n)=�(F n).Solution: Again the recurrence is: T(n)=T(n−1)+T(n−2)+1.We use the substitution method, inducting on n. Our Induction Hypothesis is: T(n)√F n.To prove the inductive step:T(n)√F n−1+F n−2+1√F n+1Therefore, T(n)←F n. For the base case consider n∗{0,1}and note the runningtime is no less than 1.1In this problem, please assume that all operations take unit time. In reality, the time it takes to add two num­bers depends on the number of bits in the numbers being added (more precisely, on the number of memory words). However, for the purpose of this problem, the approximation of unit time addition will suffice.Professor Grigori Potemkin has recently published an improved algorithm for computing the n th Fibonacci number which uses a cleverly constructed loop to get rid of one of the recursive calls. Professor Potemkin has staked his reputation on this new algorithm, and his tenure committee has asked you to review his algorithm.F IB�(n)1 if n=02 then return 03 elseif n=14 then return 15 6 7 8 sum �1for k�1to n−2do sum �sum +F IB�(k) return sumSince it is not at all clear that this algorithm actually computes the n th Fibonacci number, let’s prove that the algorithm is correct. We’ll prove this by induction over n, using a loop invariant in the inductive step of the proof.(c) State the induction hypothesis and the base case of your correctness proof.Solution: To prove the algorithm is correct, we are inducting on n. Our inductionhypothesis is that for all n<m, Fib�(n)returns F n, the n th Fibonacci number.Our base case is m=2. We observe that the first four lines of Potemkin guaranteethat Fib�(n)returns the correct value when n<2.(d) State a loop invariant for the loop in lines 6-7. Prove, using induction over k, that your“invariant” is indeed invariant.Solution: Our loop invariant is that after the k=i iteration of the loop,sum=F i+2.We prove this induction using induction over k. We assume that after the k=(i−1)iteration of the loop, sum=F i+1. Our base case is i=1. We observe that after thefirst pass through the loop, sum=2which is the 3rd Fibonacci number.To complete the induction step we observe that if sum=F i+1after the k=(i−1)andif the call to F ib�(i)on Line 7 correctly returns F i(by the induction hypothesis of ourcorrectness proof in the previous part of the problem) then after the k=i iteration ofthe loop sum=F i+2. This follows immediately form the fact that F i+F i+1=F i+2.(e) Use your loop invariant to complete the inductive step of your correctness proof.Solution: To complete the inductive step of our correctness proof, we must show thatif F ib�(n)returns F n for all n<m then F ib�(m)returns m. From the previous partwe know that if F ib�(n)returns F n for all n<m, then at the end of the k=i iterationof the loop sum=F i+2. We can thus conclude that after the k=m−2iteration ofthe loop, sum=F m which completes our correctness proof.(f) What is the asymptotic running time, T�(n), of F IB�(n)? Would you recommendtenure for Professor Potemkin?Solution: We will argue that T�(n)=�(F n)and thus that Potemkin’s algorithm,F ib�does not improve upon the assymptotic performance of the simple recurrsivealgorithm, F ib. Therefore we would not recommend tenure for Professor Potemkin.One way to see that T�(n)=�(F n)is to observe that the only constant in the programis the 1 (in lines 5 and 4). That is, in order for the program to return F n lines 5 and 4must be executed a total of F n times.Another way to see that T�(n)=�(F n)is to use the substitution method with thehypothesis T�(n)√F n and the recurrence T�(n)=cn+�n−2T�(k).k=1Problem 1-3. Polynomial multiplicationOne can represent a polynomial, in a symbolic variable x, with degree-bound n as an array P[0..n] of coefficients. Consider two linear polynomials, A(x)=a1x+a0and B(x)=b1x+b0, where a1, a0, b1, and b0are numerical coefficients, which can be represented by the arrays [a0,a1]and [b0,b1], respectively. We can multiply A and B using the four coefficient multiplicationsm1=a1·b1,m2=a1·b0,m3=a0·b1,m4=a0·b0,as well as one numerical addition, to form the polynomialC(x)=m1x2+(m2+m3)x+m4,which can be represented by the array[c0,c1,c2]=[m4,m3+m2,m1].(a) Give a divide-and-conquer algorithm for multiplying two polynomials of degree-bound n,represented as coefficient arrays, based on this formula.Solution:We can use this idea to recursively multiply polynomials of degree n−1, where n isa power of 2, as follows:Let p(x)and q(x)be polynomials of degree n−1, and divide each into the upper n/2 and lower n/2terms:p(x)=a(x)x n/2+b(x),q(x)=c(x)x n/2+d(x),where a(x), b(x), c(x), and d(x)are polynomials of degree n/2−1. The polynomial product is thenp(x)q(x)=(a(x)x n/2+b(x))(c(x)x n/2+d(x))=a(x)c(x)x n+(a(x)d(x)+b(x)c(x))x n/2+b(x)d(x).The four polynomial products a(x)c(x), a(x)d(x), b(x)c(x), and b(x)d(x)are com­puted recursively.(b) Give and solve a recurrence for the worst-case running time of your algorithm.Solution:Since we can perform the dividing and combining of polynomials in time �(n), re­cursive polynomial multiplication gives us a running time ofT(n)=4T(n/2)+�(n)=�(n2).(c) Show how to multiply two linear polynomials A(x)=a1x+a0and B(x)=b1x+b0using only three coefficient multiplications.Solution:We can use the following 3 multiplications:m1=(a+b)(c+d)=ac+ad+bc+bd,m2=ac,m3=bd,so the polynomial product is(ax+b)(cx+d)=m2x2+(m1−m2−m3)x+m3.� (d) Give a divide-and-conquer algorithm for multiplying two polynomials of degree-bound nbased on your formula from part (c).Solution:The algorithm is the same as in part (a), except for the fact that we need only compute three products of polynomials of degree n/2 to get the polynomial product.(e) Give and solve a recurrence for the worst-case running time of your algorithm.Solution:Similar to part (b):T (n )=3T (n/2) + �(n )lg 3)= �(n �(n 1.585)Alternative solution Instead of breaking a polynomial p (x ) into two smaller poly­nomials a (x ) and b (x ) such that p (x )= a (x ) + x n/2b (x ), as we did above, we could do the following:Collect all the even powers of p (x ) and substitute y = x 2 to create the polynomial a (y ). Then collect all the odd powers of p (x ), factor out x and substitute y = x 2 to create the second polynomial b (y ). Then we can see thatp (x ) = a (y ) + x b (y )· Both a (y ) and b (y ) are polynomials of (roughly) half the original size and degree, and we can proceed with our multiplications in a way analogous to what was done above.Notice that, at each level k , we need to compute y k = y 2 (where y 0 = x ), whichk −1 takes time �(1) per level and does not affect the asymptotic running time.。

北京航空航天大学 《算法导论》期末参考题(有一部分考到了)

北京航空航天大学 《算法导论》期末参考题(有一部分考到了)

一、选择题1.算法分析中,记号O表示(B),记号Ω标售(A),记号Θ表示(D)A 渐进下界B 渐进上界C 非紧上界D 紧渐进界E 非紧下界2.以下关于渐进记号的性质是正确的有:(A)A f(n) =Θ(g(n)),g(n) =Θ(h(n))⇒f(n) =Θ(h(n))B f(n) =O(g(n)),g(n) =O(h(n)) ⇒h(n) =O(f(n))C O(f(n))+O(g(n)) = O(min{f(n),g(n)})D f(n) = O(g(n)) ⇔g(n) = O(f(n))3. 记号O的定义正确的是(A)。

A O(g(n)) = { f(n) | 存在正常数c和n0使得对所有n≥n0有:0≤ f(n) ≤ cg(n) };B O(g(n)) = { f(n) | 存在正常数c和n0使得对所有n≥n0有:0≤cg(n) ≤ f(n) };C O(g(n)) = { f(n) | 对于任何正常数c>0,存在正数和n0 >0使得对所有n≥n0有:0 ≤f(n)<cg(n) };D O(g(n)) = { f(n) | 对于任何正常数c>0,存在正数和n0 >0使得对所有n≥n0有:0 ≤cg(n) < f(n) };4. 记号Ω的定义正确的是(B)。

A O(g(n)) = { f(n) | 存在正常数c和n0使得对所有n≥n0有:0≤ f(n) ≤ cg(n) };B O(g(n)) = { f(n) | 存在正常数c和n0使得对所有n≥n0有:0≤ cg(n) ≤ f(n) };C (g(n)) = { f(n) | 对于任何正常数c>0,存在正数和n0 >0使得对所有n≥n0有:0 ≤f(n)<cg(n) };D (g(n)) = { f(n) | 对于任何正常数c>0,存在正数和n0 >0使得对所有n≥n0有:0 ≤cg(n) < f(n) };5. T(n)表示当输入规模为n时的算法效率,以下算法效率最优的是( C )A T(n)= T(n – 1)+1,T(1)=1B T(n)= 2n2C T(n)= T(n/2)+1,T(1)=1D T(n)= 3nlog2n6. 动态规划算法的基本要素为(C)A 最优子结构性质与贪心选择性质B 重叠子问题性质与贪心选择性质C 最优子结构性质与重叠子问题性质D 预排序与递归调用7.下列不是动态规划算法基本步骤的是( A )。

算法考卷参考答案

算法考卷参考答案

一、选择题(每题1分,共5分)A. Dijkstra算法B. Kruskal算法C. Huffman编码D. 动态规划算法2. 下列排序算法中,哪个算法的时间复杂度最稳定?A. 冒泡排序B. 快速排序C. 堆排序D. 插入排序A. 二分查找B. 深度优先搜索C. 广度优先搜索D. 动态规划A. 初始化状态B. 确定状态转移方程C. 计算最优值D. ABC都是A. Floyd算法B. Warshall算法C. Prim算法D. BellmanFord算法二、判断题(每题1分,共5分)1. 算法的空间复杂度与时间复杂度成正比。

(×)2. 贪心算法总能得到最优解。

(×)3. 快速排序的平均时间复杂度为O(nlogn)。

(√)4. 二分查找算法适用于顺序存储的有序表。

(√)5. 深度优先搜索和广度优先搜索在遍历图时,时间复杂度相同。

(×)三、填空题(每题1分,共5分)1. 算法的五个基本特性分别是:可行性、确定性、______、有穷性和输入输出。

2. 在排序算法中,堆排序的时间复杂度为______。

3. 求解背包问题通常采用______算法。

4. 图的遍历方法有深度优先搜索和______。

5. 在动态规划算法中,状态转移方程描述了______之间的关系。

四、简答题(每题2分,共10分)1. 简述冒泡排序的基本思想。

2. 什么是贪心算法?请举例说明。

3. 简述二分查找算法的基本步骤。

4. 什么是动态规划算法?它适用于哪些问题?5. 请列举三种常见的图遍历算法。

五、应用题(每题2分,共10分)1. 设有数组arr = [3, 5, 1, 4, 2],请用冒泡排序算法对数组进行排序。

2. 给定一个整数数组nums,请找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

3. 编写一个递归函数,实现求斐波那契数列的第n项。

A B| |C DA B (3)| |C D (4)六、分析题(每题5分,共10分)def func(n):sum = 0for i in range(n):for j in range(i):sum += 1return sum2. 给定一个字符串str,请设计一个算法,找出最长不重复子串的长度。

算法导论习题

算法导论习题

//在合并排序中对小数组采用插入排序#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]);/*对插入排序来说,当其输入已“几乎”排好序时,运行时间是很快的。

《算法导论》习题答案

《算法导论》习题答案

《算法导论》习题答案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]&lt;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&gt;4时,,是否多项式有界~与设lgn=m,则?lgn~不是多项式有界的。

mememmmm2设,,是多项式有界的3.2.5比较lg(lg*n)与lg*(lgn)lg*(lgn)= lg*n-1设lg*n=x,lgx&lt;x-1较大。

算法导论答案(经典)

算法导论答案(经典)

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
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

共 2页 第 1 页
5、(15 分)在 0/1 背包问题中,设 f(i , y)表示剩余容量为 y,剩余可选物品为: i,i+1,…,n 时的最优解的值。 1)给出 f(i , y)的递推表达式; 2)请设计计算 f(i , y)的算法; 3)设 W=[10,20,15,30],P=[6,10,15,18], m=48,请用你的算法求解,要求写 出计算过程。
4、(15 分)[节点覆盖问题] 假设 G=(V,E)为一个无向图,G 的节点覆盖为节点 集合 V 的一个子集 U,满足 E 中每一条边至少与 U 中的一个顶点相关联。 最小节点覆盖是具有最少节点数量的一个覆盖。先制定贪婪准则为:每次 从未被覆盖的顶点中选择一个顶点,使得它所覆盖的未被覆盖的顶点数目 最多。 1)这种法总能产生一个最优解吗?如果能,请证明之;如果不能,请举 出一个反例。 2)用伪代码描述这种贪心算法。
西安交通大学考试题
成绩
课程
系别 专业班号 姓名
算法导论
ቤተ መጻሕፍቲ ባይዱ
考试日期
年 月日
学号
期中
期末 √
1、(10 分)证明:若 f(n)= amnm+…+a1n+a0 那么 f(n)= (nm),f(n)= (nm)。
(am > 0),
2、(20 分)到商场购买商品需要找零钱。假设有四种面值分别为 14 角、5 角、 2 角和 1 角的硬币可以找零,售货员希望找零的硬币数目最少。也就是, 优化目标是找零的硬币数目最少,限制条件是所选择的硬币的总面值等于 要找的零钱数。
1)假设要找的零钱数分别是 13 角,21 角和 41 角;(贪婪策略:每一次选 择应该使硬币的面值最大), 给出相应的解。
2)假设要找的零钱数是 n 角,请用 C 语言或伪代码描述算法。
3、(10 分)有 n(=2 k)个硬币,其中 1 个是假币,且假币和真币的重量不同。 请用分而治之方法设计一个找出假币的算法,并用伪代码描述你的算法。
共 2页 第 2 页
6、(15 分)请分别说明分治策略、动态规划、贪心算法、回溯法和分支限界法 的基本思想。
7、(15 分)旅行商问题:给出一个 n 个顶点网络,要求找出一个包含所有 n 个 顶点的具有最小耗费的环路。任何一个包含所有 n 个顶点的环路被称作一 个旅行。在旅行商问题中,要求设法找到一条最小耗费的旅行。 1)若图的邻接矩阵如下,画出旅行商问题的解空间树; 2)对该树运用回溯算法求解,并写出依回溯算法遍历节点的序列; 3) 用 C 语言或伪代码描述求解旅行商问题的回溯算法。 ∞ 20 30 10 11 15 ∞ 16 4 2 35 ∞ 2 4 19 6 18 ∞ 3 16 4 7 16 ∞
相关文档
最新文档