算法导论第三章答案

合集下载

算法第四版习题答案

算法第四版习题答案

算法第四版习题答案算法第四版,通常指的是《算法导论》(Introduction to Algorithms),这本书由Thomas H. Cormen、Charles E. Leiserson、Ronald L. Rivest和Clifford Stein共同撰写。

这本书是计算机科学领域内算法课程的标准教材之一,广受学术界和工业界的推崇。

然而,由于版权保护,我不能提供该书习题的官方答案。

但我可以提供一些解题思路和方法,帮助理解习题的解题过程。

# 开头在解答《算法导论》的习题时,首先要确保理解题目的要求和背景知识。

每个习题都旨在加深对特定算法概念的理解,因此,复习相关的理论知识是解答习题的第一步。

# 理解算法概念- 排序算法:如快速排序、归并排序等,需要理解它们的工作原理、时间复杂度和空间复杂度。

- 图算法:如深度优先搜索(DFS)、广度优先搜索(BFS)等,需要掌握它们的应用场景和实现方式。

- 动态规划:理解如何将问题分解为子问题,并利用子问题的解来构建原问题的解。

- 贪心算法:学习如何选择合适的局部最优解以达成全局最优。

# 解题步骤1. 问题定义:明确题目要求解决的问题是什么,以及需要哪些输入和输出。

2. 算法选择:根据问题的性质选择合适的算法或数据结构。

3. 算法设计:设计算法的逻辑流程,可以使用伪代码或流程图来辅助说明。

4. 复杂度分析:分析算法的时间复杂度和空间复杂度,确保算法的效率。

5. 代码实现:将算法逻辑转化为可执行的代码。

6. 测试验证:通过测试不同的输入来验证算法的正确性和效率。

# 常见问题类型- 理论证明题:要求证明某个算法的性质或定理的正确性。

- 算法设计题:要求设计一个新的算法来解决特定的问题。

- 算法分析题:要求分析给定算法的时间复杂度或空间复杂度。

- 编程实现题:要求编写代码来实现特定的算法。

# 结尾解答《算法导论》的习题是一个深化理解算法原理和提升编程技能的过程。

在解题过程中,如果遇到困难,可以查阅相关资料、参与讨论或寻求指导。

算法导论课程作业答案

算法导论课程作业答案

算法导论课程作业答案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)

数据结构与算法第3章课后答案

数据结构与算法第3章课后答案

第 3 章特殊线性表——栈、队列和串(2005-07-14) -第 3 章特殊线性表——栈、队列和串课后习题讲解1. 填空⑴设有一个空栈,栈顶指针为1000H,现有输入序列为1、2、3、4、5,经过push,push,pop,push,pop,push,push后,输出序列是(),栈顶指针为()。

【解答】23,1003H⑵栈通常采用的两种存储结构是();其判定栈空的条件分别是(),判定栈满的条件分别是()。

【解答】顺序存储结构和链接存储结构(或顺序栈和链栈),栈顶指针top= -1和top=NULL,栈顶指针top等于数组的长度和内存无可用空间⑶()可作为实现递归函数调用的一种数据结构。

【解答】栈【分析】递归函数的调用和返回正好符合后进先出性。

⑷表达式a*(b+c)-d的后缀表达式是()。

【解答】abc+*d-【分析】将中缀表达式变为后缀表达式有一个技巧:将操作数依次写下来,再将算符插在它的两个操作数的后面。

⑸栈和队列是两种特殊的线性表,栈的操作特性是(),队列的操作特性是(),栈和队列的主要区别在于()。

【解答】后进先出,先进先出,对插入和删除操作限定的位置不同⑹循环队列的引入是为了克服()。

【解答】假溢出⑺数组Q[n]用来表示一个循环队列,front为队头元素的前一个位置,rear为队尾元素的位置,计算队列中元素个数的公式为()。

page: 2The Home of jetmambo - 第 3 章特殊线性表——栈、队列和串【解答】(rear-front+n)% n【分析】也可以是(rear-front)% n,但rear-front的结果可能是负整数,而对一个负整数求模,其结果在不同的编译器环境下可能会有所不同。

⑻用循环链表表示的队列长度为n,若只设头指针,则出队和入队的时间复杂度分别是()和()。

【解答】O(1),O(n)【分析】在带头指针的循环链表中,出队即是删除开始结点,这只需修改相应指针;入队即是在终端结点的后面插入一个结点,这需要从头指针开始查找终端结点的地址。

中科大算法导论作业标准标准答案

中科大算法导论作业标准标准答案

第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第二章算法入门由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。

另,思考题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-112 31 41 59 26 41 584 while i ≥ 0 and A[i] > key5 do A[i+1]←A[i]6 i ← i − 17A[i+1]←key循环丌变式(Loop Invariant)是证明算法正确性的一个重要工具。

算法导论第三版答案

算法导论第三版答案
Solution to Exercise 2.3-5
Procedure BINARY-SEARCH takes a sorted array A, a value , and a range Œlow : : high of the array, in which we search for the value . The procedure compares to the array entry at the midpoint of the range and decides to eliminate half the range from further consideration. We give both iterative and recursive versions, each of which returns either an index i such that AŒi D , or NIL if no utions for Chapter 2: Getting Started
AŒlow : : high contains the value . The initial call to either version should have the parameters A; ; 1; n.
Selected Solutions for Chapter 2: Getting Started
2-3
d. We follow the hint and modify merge sort to count the number of inversions in ‚.n lg n/ time.
To start, let us define a merge-inversion as a situation within the execution of merge sort in which the MERGE procedure, after copying AŒp : : q to L and AŒq C 1 : : r to R, has values x in L and y in R such that x > y. Consider an inversion .i; j /, and let x D AŒi and y D AŒj , so that i < j and x > y. We claim that if we were to run merge sort, there would be exactly one mergeinversion involving x and y. To see why, observe that the only way in which array elements change their positions is within the MERGE procedure. Moreover, since MERGE keeps elements within L in the same relative order to each other, and correspondingly for R, the only way in which two elements can change their ordering relative to each other is for the greater one to appear in L and the lesser one to appear in R. Thus, there is at least one merge-inversion involving x and y. To see that there is exactly one such merge-inversion, observe that after any call of MERGE that involves both x and y, they are in the same sorted subarray and will therefore both appear in L or both appear in R in any given call thereafter. Thus, we have proven the claim.

算法导论作业3答案

算法导论作业3答案

Introduction to Algorithm s Day 14 Massachusetts Institute of Technology 6.046J/18.410J Singapore-MIT Alliance SMA5503 Professors Erik Demaine, Lee Wee Sun, and Charles E. Leiserson Handout 17Problem Set 3 SolutionsMIT students: This problem set is due in lecture on Day 11.Reading: Chapters 8 and 9Both exercises and problems should be solved, but only the problems should be turned in. Exercises are intended to help you master the course material. Even though you should not turn in the exercise solutions, you are responsible for material covered by the exercises.Mark the top of each sheet with your name, the course number, the problem number, your recitation instructor and time, the date, and the names of any students with whom you collaborated. MIT students: Each problem should be done on a separate sheet (or sheets) of three-hole punched paper.You will often be called upon to “give an algorithm” to solve a certain problem. Your write-up should take the form of a short essay. A topic paragraph should summarize the problem you are solving and what your results are. The body of your essay should provide the following:1. A description of the algorithm in English and, if helpful, pseudocode.2. At least one worked example or diagram to show more precisely how your algorithm works.3. A proof (or indication) of the correctness of the algorithm.4. An analysis of the running time of the algorithm.Remember, your goal is to communicate. Graders will be instructed to take off points for convo­luted and obtuse descriptions.Exercise 3-1. Do exercise 8.1-2 on page 167 of CLRS.Exercise 3-2. Do exercise 8.1-3 on page 168 of CLRS.Exercise 3-3. Do exercise 8.2-3 on page 170 of CLRS.Exercise 3-4. Do exercise 8.4-2 on page 177 of CLRS.Exercise 3-5. Do exercise 9.3-1 on page 192 of CLRS.Exercise 3-6. Show that the second smallest of n elements can be found with n+Θ(lg n)com­parisons in the worst case. (Hint: Also find the smallest element.)Problem 3-1. Largest i numbers in sorted orderGiven a set of n numbers, we wish to find the i largest in sorted order using a comparison-based algorithm. Find the algorithm that implements each of the following methods with the best asymp­totic worst-case running time, and analyze the running times of the algorithms in terms of n and i.(a) Sort the numbers, and list the i largest.Solution:Use any optimal sorting algorithm, such as MergeSort or HeapSort. Then this can bedone in Θ(n lg n).(b) Build a max-priority queue from the numbers, and call E XTRACT-M AX i times.Solution:Call Build-Heap, Θ(n). Then call Extract-Max, Θ(lg i), i times. So, total runningtime is Θ(n+i lg i).(c) Use an order-statistic algorithm to find the i th largest number, partition around thatnumber, and sort the i largest numbers.Solution:Select the i-th largest number using SELECT, Θ(n), call partition, Θ(n), and then sortthe i largest numbers, Θ(i lg i). So our algorithm takes Θ(n+i lg i).Problem 3-2. At the wading poolYou work at a summer camp which holds regular outings for the n children which attend. One of these outings is to a nearby wading pool which always turns out to be something of a nightmare at the end because there are n wet, cranky children and a pile of 2n shoes (n left shoes and n right shoes) and it is not at all clear which kids go with which shoes. Not being particularly picky, all you care about is getting kids into shoes that fit. The only way to determine if a shoe is a match for a child is to try the shoe on the child’s foot. After trying on the shoe, you will know that it either fits, is too big, or is too small. It is important to note that you cannot accurately compare children’s feet directly with each other, nor can you compare the shoes. You know that for every kid, there are at least two shoes (one left shoe and one right shoe) that will fit, and your task is to shoe all of the children efficiently so that you can go home. There are enough shoes that each child will find a pair which fits her. Assume that each comparison (trying a shoe on a foot) takes one time unit.(a) Describe a deterministic algorithm that uses Θ(n 2) comparisons to pair children withshoes.Solution:For each child, try on all the shoes until you find the two shoes that fit. T (n )= T (n − 2) + O (n ) = Θ(n 2).(b) Prove a lower bound of Ω(n lg n ) for the number of comparisons that must be madeby an algorithm solving this problem. (Hint: How many leaves does the decision tree have?)Solution:There are n ! ways that left shoes can be assigned to children and n ! ways that right shoes can be assigned to children. So the decision tree should have n !2 leaves. n !2 ≥ n ! h ≥ lg(n !)h ≥ lg ( ne )n by Stirling’s Approximation = n lg n − n lg e= Ω(n lg n )(c) How might you partition the children into those with a smaller shoe size than a “pivot”child, and those with a larger shoe size than the pivot child?Solution:Take the pivot child and try on all the shoes until you find one that fits. This should take Θ(n ) time as there are 2n shoes. Then try the shoe on all the children. If the shoe is too small, then they have larger feet than the pivot child. If the shoe is too big, then they have smaller feet than the pivot child. This should also take Θ(n ) time making our partition algorithm run in linear time.(d) Give a randomized algorithm whose expected number of comparisons is O (n lg n ),and prove that this bound is correct. What is the worst-case number of comparisons for your algorithm?Solution:This is similar to quicksort. Pick a random child. Partition the children around that child as in part (c). Then take the shoe you used to partition the children and partition the shoes around it. Take the two shoes and pivot child and put them in the group of paired children. Then recurse on the two groups of shoes and children. This should have the same analysis as randomized quicksort because we have only added an extra call to partition which will still make the work done at each level Θ(n ).。

算法导论答案Ch3

算法导论答案Ch3
n→∞
f (n) =∞ g (n)
Ω(g (n, m)) = {f (n, m) : there exist positive constants c, n0 , and m0 such that f (n, m) ≥ cg (n, m) for all n ≥ n0 or m ≥ m0 }
Θ(g (n, m)) = {f (n, m) : there exist positive constants c1 , c2 , n0 , and m0 such that c1 g (n, m) ≤ f (n, m) ≤ c2 g (n, m) for all n ≥ n0 or m ≥ m0 } Exercise 3.2-1 Let n1 < n2 be arbitrary. From f and g being monatonic increasing, we know f (n1 ) < f (n2 ) and g (n1 ) < g (n2 ). So f (n1 ) + g (n1 ) < f (n2 ) + g (n1 ) < f (n2 ) + g (n2 ) 2
n→∞
2e n
n
≤ lim
n→∞
2e n
n
1 =0 2n
nn 1 en n −.5 n √ = lim √ e = lim O ( n ) e ≥ lim 1 n→∞ n! n→∞ n→∞ c1 n n→∞ 2πn(1 + Θ( n )) lim ≥ lim en en = lim =∞ n→∞ c1 n n→∞ c1
n a/b n if and only if if and only if n − 21 /b ≥ −a if and only if n + a ≥ (1/2) (n + a)b ≥ cnb . Therefore (n + a)b = Ω(nb ). By Theorem 3.1, (n + a)b = Θ(nb ).

算法导论中文版答案

算法导论中文版答案

24.2-3
24.2-4
24.3-1 见图 24-6 24.3-2
24.3-3
24.3-4 24.3-5 24.3-6
24.3-7
24.3-8 这种情况下不会破坏已经更新的点的距离。 24.4**** 24.5****
25.1-1 见图 25-1 25.1-2 为了保证递归定义式 25.2 的正确性 25.1-3
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
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
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

MIT算法导论公开课 期末答案

MIT算法导论公开课 期末答案

leaves. Since leaf costs M , and the total cost is dominated by the leaves, the �each � ∈ �3 � � ∈ � solution is � M n/ M = � n3 / M .
Handout 36: Final Exam Solutions
Problem 1. Recurrences [15 points] (3 parts)
2
Give a tight asymptotic upper bound (O notation) on the solution to each of the following recur­ rences. You need not justify your answers. (a) T (n) = 2T (n/8) + Solution: ∈ 3 n.
Handout 36: Final Exam Solutions
Problem 4. True or False, and Justify [35 points] (7 parts)
5
Circle T or F for each of the following statements to indicate whether the statement is true or false, respectively. If the statement is correct, briefly state why. If the statement is wrong, explain why. The more content you provide in your justification, the higher your grade, but be brief. Your justification is worth more points than your true-or-false designation. T F Let A1 , A2 , and A3 be three sorted arrays of n real numbers (all distinct). In the comparison model, constructing a balanced binary search tree of the set A 1 � A2 � A3 requires Δ(n lg n) time. Solution: False. First, merge the three arrays, A1 , A2 , and A3 in O (n) time. Second, construct a balanced binary search tree from the merged array: the median of the array is the root; recursively build the left subtree from the first half of the array and the right subtree from the second half of the array. The resulting running time is T (n) = 2T (n/2)+ O (1) = O (n).

算法导论中文版答案

算法导论中文版答案
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.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

算法导论习题解答2.3-7

算法导论习题解答2.3-7

算法导论习题解答2.3-7
•2.3-7 请给出⼀个运⾏为Θ(nlgn)的算法(伪码),使之能在给定⼀个由n个整数构成的集合S和另⼀个整数x时,判断出S中是否存在有两个其和等于x的元素。

解:解题思路:先对集合S进⾏归并排序,然后新建⼀个数组S1,使得S1[i] = x – S[i],再将两个数组并起来。

如果在并的过程中发现有两个元素相等且两个元素⼀个来⾃S,⼀个来⾃S1,则可以确定S中存在有两个其和等于x的元素。

Find whether x exits
1、Sort(S)
2、for i <- 0 to Length(S) – 1
3、 do S1[i] <- x - S[i]
4、for i <- 0 to Length(S) – 1
5、 do Merge( S,S1 )
6、 if S[p] > S1[q]
7、 S0[k] <- S[p] p++ k++
8、 if S[p] < S1[q]
9、 S0[k] <- S[q] q++ k++
10、 if S[p] == S1[q]
11、 return true
12、return false
在第⼀⾏进⾏排序时,时间代价为Θ(nlgn),后来的合并过程时间代价为Θ(n),总的时间代价为Θ(nlgn)。

《算法导论》读书笔记(三)

《算法导论》读书笔记(三)

《算法导论》读书笔记(三) 本章介绍了快速排序及其算法分析,快速排序采⽤的是分治算法思想,对包含n个数的输⼊数组,最坏情况下运⾏时间为θ(n^2),但是平均性能相当好,期望的运⾏时间为θ(nlgn)。

另外快速排序能够就地排序(我理解是不需要引⼊额外的辅助空间,每次划分能确定⼀个元素的具体位置),在虚拟环境中能很好的⼯作。

1、快速排序的描述 快速排序算法采⽤的分治算法,因此对⼀个⼦数组A[p…r]进⾏快速排序的三个步骤为: (1)分解:数组A[p...r]被划分为两个(可能为空)⼦数组A[p...q-1]和A[q+1...r],给定⼀个枢轴,使得A[p...q-1]中的每个元素⼩于等于A[q],A[q+1...r]中的每个元素⼤于等于A[q],q下标是在划分过程中计算得出的。

(2)解决:通过递归调⽤快速排序,对⼦数组A[p...q-1]和A[q+1...r]进⾏排序。

(3)合并:因为两个⼦数组是就地排序,不需要合并操作,整个数组A[p…r]排序完成。

快速排序关键过程是对数组进⾏划分,划分过程需要选择⼀个主元素(pivot element)作为参照,围绕着这个主元素进划分⼦数组。

举个列说明如何划分数组,现有⼦数组A={24,15,27,5,43,87,34},以最后⼀个元素为主元素进⾏划分,划分过程如图所⽰:书中给出了划分过程的伪代码:1 PARTITION(A,p,r)2 x = A[r] //将最后⼀个元素作为主元素3 i = p-14 for j=p to r-1 //从第⼀个元素开始到倒数第⼆个元素结束,⽐较确定主元的位置5 do if A[j] <= x6 i = i+17 exchange A[i] <-> A[j]8 exchange A[i+1]<->A[r] //最终确定主元的位置9 return i+1 //返回主元的位置根据划分过程的为代码,书中⼜给出了快速排序的为代码:1 QUICKSORT(A,p,r)2 if p<r3 q = PARTITION(A,p,r) //确定划分位置4 QUICKSORT(A,p,q-1) //⼦数组A[p...q-1]5 QUICKSORT(Q,q+1,r) //⼦数组A[q+1...r]采⽤C元素实现⼀个完成的快速排序程序,程序如下:1 #include <stdio.h>2 #include <stdlib.h>34 size_t partition(int* datas,int beg,int last);5 void quick_sort(int* datas,int beg,int last);6 void swap(int *a,int *b);78 int main()9 {10 size_t i;11 int datas[10] = {78,13,9,23,45,14,35,65,56,79};12 printf("After quick sort,the datas is:\n");13 quick_sort(datas,0,9);14 for(i=0;i<10;++i)15 printf("%d ",datas[i]);16 exit(0);17 }1819 void swap(int *a,int *b)20 {21 int temp = *a;22 *a = *b;23 *b = temp;24 }2526 size_t partition(int* datas,int beg,int last)27 {28 int pivot = datas[last];29 int i,j;30 i = beg -1;31 for(j=beg;j<last;j++)32 {33 if(datas[j] < pivot)34 {35 i = i+1;36 swap(datas+i,datas+j);37 }38 }39 swap(datas+i+1,datas+last);40 return (i+1);41 }42 void quick_sort(int* datas,int beg,int last)43 {44 int pivot;45 if(beg < last)46 {47 pivot = partition(datas,beg,last);48 quick_sort(datas,beg,pivot-1);49 quick_sort(datas,pivot+1,last);50 }5152 }程序测试结果如下:可以将划分过程之间嵌⼊到快速排序过程中,C语⾔实现如下所⽰:1 void quicksort(int *datas,int length)2 {3 int pivot ,i,j;4 if(length > 1)5 {6 pivot = datas[length-1];7 for(i=0,j=0;j<length-1;j++)8 {9 if(datas[j] < pivot)10 {11 swap(datas+i,datas+j);12 i = i+1;13 }14 }15 swap(datas+i,datas+length-1);16 quicksort(datas,i);17 quicksort(datas+i,length-i);18 }19 }2、快速算法排序的性能 最快情况划分:当划分过程中产⽣的两个区域分别包含n-1个元素和1个元素的时候(即将待排序的数是逆序的),这样第个调⽤过程中每次划分都是不对称的。

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