麻省理工公开课《算法导论》学习笔记_第一讲
《算法导论》读书笔记
哨兵(sentinel) 哨兵是一个哑对象,其作用是简化边界条件的处理。 类似于以前学习时讲到的头节点。加入哨兵将原来的双向链表转变成一个有哨兵的双向循环两表。L.nil代表哨兵。一图胜千言,如下:
如果有很多个很短的链表,慎用哨兵,因为哨兵所占用的额外存储空间会造成严重的存储浪费。哨兵并没有优化太多的渐进时间界,只是可 以使代码更紧凑简洁。 指针和对象的实现 对象的多数组表示: next和prev中的数字指的是对应数字的下标,有趣!
关于几个时间复杂度
通常情况下,当数据量足够大时,一般满足 θ(1)>θ(N)>θ(NlogN)>θ(N^2) (>代表优于)
1.算 法 基 础
1.1 插 入 排 序
时间复杂度:O(N^2) 思想:每次从右至左跟已排序数列进行对比,放入合适位置。两次遍历,一次相当于摸牌,另一次相当于具体的查找算法。
1.2 分 治 法
解决冲突的方法
链接法(chaining)
关于链接法采用双链的一些解释: 简单讲,删除就是从x对应的链表里删除x,双链表的删除加入哨兵只需两行,但是单链表的话只能指定x.next=null,但是在这之前需 要先将x.prev.next指向x.next,由于是单链,所以没有prev,只能一直next找下去,相比双链多了查找的时间耗费。
将问题分解为几个规模较小但类似于原问题的子问题,递归的求解这些子问题,然后再合并这些子问题的解来建立原问题的解。 (分解-解决-合并) 归并排序 时间复杂度O(NlogN)(O还是θ——theta,都差不多)
归并排序算法如下:
函数的增长
O渐进上界Ω渐进下界,o和ω 具体看数学定义最清楚。
分治策略
1. 维护堆的性质 通俗的讲,就是保持数组的最大堆性质。思路比较简单,比较parent节点和孩子节点,找到最大值,如果最大值是某个孩子节点,交 换,递归运行。对于树高为h的节点来说,该程序时间复杂度为O(h)
算法导论笔记
第一章算法在计算中的应用第九章中位数和顺序统计学9.1-11.将数组中的元素分组,每组两个元素,然后比较每组中的两个元素得到最小值,重新得到包含原来一半元素的数组,继续重复上述过程,那么最后一个元素必然为最小值。
如图所示,数组为{2, 1, 4, 3, 5}2.上述过程形成的是一个二叉树,其中叶子节点都为数组元素,非叶子节点刚好4个,这是二叉树的性质。
3.然后我们来找第二小元素,第二小元素必然跟着1,首先赋值为5,然后再赋值为3,然后赋值为2,即为所求。
【运行结果】:1.我们先将N个数配对,每两个数一对,每对之间进行互相比较得出小值。
2.对得出的N/2个元素重复第一步,直至得出最小值。
到这儿我们得出了最小值,实际上比较的次数为n-1次。
不难发现上面的过程实际上可以演示为一个二叉树。
例如在5,8,11,18四个数找出最小值,二叉树演示如下(每个节点相当于一次比较):观察二叉树,可以得出这样一个结论,所有与最小值比较过的数中的最小值纪即为第二小的的值。
二叉树的高度为lgn,因此与最小值比较的数的数目为lgn,在lgn个数中找出最小值要进行lgn-1次比较。
9.1-29.3节的方法可以在最坏情况下的线性复杂度的算法来求顺序统计量.其核心思想在于获得一个更好的中枢值来更好地划分数组.然而题中给了我们一个"黑盒子"来以线性复杂度获取一个真正好的中枢值,那么再好不过了。
在同时找到最大值和最小值时,每个元素都参与了与最大值和最小值的比较,比较了两次。
将数组成对处理。
两两互相比较,将大的与最大值比较,小的与最小值比较。
每两个元素需要的比较次数是,两两比较一次,大者与最大值比较一次,小者与最小值比较一次,共三次。
9.2-1长度为0的数组,RANDOMIZED-SELECT直接返回,当然不会递归调用。
9.2-29.2-3 写出RANDOMIZED-SELECT的一个迭代版本【算法思想】:递归:在函数中调用自身的程序过程。
认识算法听课笔记
认识算法听课笔记全文共四篇示例,供读者参考第一篇示例:认识算法听课笔记算法作为计算机科学的核心领域,是指解决问题的一系列步骤或规则。
在计算机科学中,算法的设计与分析是最重要的课程之一。
学生在大学期间都会学习算法课程,以提升自己的计算机科学能力。
我在大学期间有幸上了一门名为“算法设计与分析”的课程,这门课程由一位资深的计算机科学教授授课。
教授讲解清晰,深入浅出,让我对算法有了更深刻的理解。
在这门课程中,我认识了许多经典的算法,并学会了如何设计和分析算法。
在这里,我将分享一些我在听课过程中做的笔记,希望能够帮助到正在学习算法的同学们。
1. 算法的定义和分类算法是一种解决问题的有限步骤的有序序列。
算法可以用来解决各种问题,例如排序、查找、最短路径等。
根据算法解决问题的方式不同,算法可以分为以下几类:- 穷举法:穷举法是一种基本的解决问题方式,通过枚举所有可能的情况来解决问题。
但是穷举法通常会消耗大量的时间和空间。
- 分治法:分治法是一种将问题分解为更小的子问题来解决的算法。
分治法常用于解决递归性质的问题,例如归并排序、快速排序等。
- 动态规划:动态规划是一种通过将问题分解为更小的子问题来解决的算法。
动态规划通常用于解决最优化问题,例如最长公共子序列、背包问题等。
2. 算法设计的基本原则在设计算法时,我们需要遵循一些基本原则,以保证算法的正确性、效率和可读性。
以下是一些常用的算法设计原则:- 简单性:设计的算法应该尽可能简单易懂,避免过度复杂的实现。
- 效率:设计的算法应该具有较高的效率,能够在合理的时间内解决问题。
- 可读性:设计的算法应该具有较高的可读性,便于他人理解和修改。
- 鲁棒性:设计的算法应该具有较高的鲁棒性,能够处理各种异常情况。
3. 算法分析的方法在设计完算法之后,我们需要对算法进行分析,以评估算法的性能。
算法的性能通常通过时间复杂度和空间复杂度来衡量。
时间复杂度是指算法执行所需的时间量,而空间复杂度是指算法执行所需的空间量。
算法导论文档
第一课课程细节;绪论:算法分析,插入排序法(Insertion Sort),归并排序(Merge Sort) 阅读:1-2章发测验02 演示课1 算法的正确性发《作业1》3 第二课渐进记号(Asymptotic Notation)。
递归公式(Recurrences):置换法,迭代法,主方法阅读:3-4 章,除了§4.44 第三课分治法:Strassen 算法,费氏数列,多项式乘法。
阅读:28 章第2 节,30章第1节5 演示课2 递归公式,松散性阅读:Akra-Bazzi 的讲义6 第四课快速排序法,随机化算法阅读:5 章1 到 3 节,7 章收《作业1》发《作业2》7 演示课3 排序法:堆排序,动态集合,优先队列阅读:6 章8 第五课线性时间的排序法:时间下界,计数排序法,基数排序法阅读:8 章第1 到3 节收《作业2》发《作业3》9 第六课顺序统计学,中位数阅读:9 章10 演示课4 中位数的应用,桶排序阅读:8 章第 4 节11 第七课散列,全域散列阅读:11 章1 到3 节收《作业3》发《作业4》12 第八课散列函数,完美散列阅读:11 章第5 节13 演示课5 测验1 复习收《作业4》14 评分后的作业4可以在中午拿到15 测验116 演示课6 二叉搜索树,树的遍历阅读:12 章1 到 3 节17 第九课二叉搜索树和快速排序法之间的关系;随机二叉搜索树的分析阅读:12 章4 节发《作业5》18 第十课红黑树,旋转,插入,删除阅读:13 章19 演示课7 2-3树,B-树阅读:18 章1 到 2 节20 第十一课高级数据结构,动态顺序统计,线段树(区间树)阅读:14 章收《作业5》发《作业6》21 第十二课计算几何,区间查询阅读:33 章1 到 2 节22 演示课8 凸多边形阅读:33 章3 节23 第十三课van Emde Boas树,优先队列阅读:van Emde Boas 的讲义收《作业6》发《作业7》24 第十四课平摊分析,表的复制,可能法阅读:17 章25 演示课9 竞争分析,自我排序列26 第十五课动态规划,最长公共子序列,最优二叉搜索树阅读:15 章收《作业7》发《作业8》27 第十六课贪婪算法,最小生成树阅读:16 章1 到 3 节,23 章28 演示课10 贪婪算法和动态规划的范例29 第十七课最短路径1,Dijkstra算法,广度优先搜索阅读:22 章1, 2 节;第580 - 587 页,24章 3 节收《作业8》发《作业9》30 演示课11 深度优先搜索,拓扑排序阅读:22 章3 到 5 节31 第十八课最短路径2,Bellman-Ford算法,DAG最短路径,差分约束阅读:24 章1, 2, 4, 5 节32 第十九课所有点对最短路径,Floyd-Warshall,Johnson 的算法阅读:25 章收《作业9》33 第二十课不相交集合的数据结构阅读:21 章34 评分后的作业9可以在中午拿到35 第二十一课带回家发下测验2 ; 道德,解决问题(强制参加)发测验236 没有演示课- 解答测验2!37 没有课算法程序比赛开始(非强制参加)收测验238 第二十二课网络流,最大流最小割切定理阅读:26 章1 - 2 节发《作业10》(选答)39 演示课12 图的匹配算法(注:最大二分匹配)阅读:26 章3 节40 第二十三课网络流,Edmonds-Karp 算法参赛答案截止41 第二十四课随堂测验;比赛颁奖;后续课程的讨论《作业10》解答。
算法导论小笔记
算法导论小笔记算法导论(CLRS)笔记Note on CLRS(Outline & Draft, 2011)Jian Xiao1第2章Getting started1. Merge sort相关的扩展问题1)链表实现V.S.数组实现。
Divide阶段,如何快速找到链表的中点?另外,如何减少Divide/Combine的时间(相比数组实现)?2)In-place merge的方法。
3)归并树:把Merge sort的中间过程都记录下来,所形成的树。
(其实就是一棵线段树,每个节点存放该节点的区间内有序化后的数)4)逆序数的计算。
2. 两数和问题。
数的集合S,一个数x,判断S中是否存在两个数,二者的和为x。
这个问题扩展以后是一个subset problem,为NPC问题。
第3章Growth of Functions1. 全部5个渐进符号的确切含义第4章Recurrences1. Substitution方法,Recursion tree方法计算复杂度2. Master Theorem及其不能被三种case覆盖的其他情况Master Theorem的证明3. Chip testing problem4. Monge arrays,凸四边形不等式,最优二叉查找树DP算法的优化第5章Probabilistic Analysis and Randomized Algorithms1. 用Biased-Random产生Uniform-Random分布。
2. In-place、O(n)的uniform random permutationIn-place、O(n)的各个position等概的排列1iamxiaojian@/doc/d1*******.html,3. Coupon collector’s problem4. On-line hiring problem第6章Heapsort1. 两种建堆的方法:逐个插入的O(nlogn),以及自底向上调整的O(n)算法2. Heap sort可能存在效率的地方:每次删除堆顶,都是把某树叶放置于堆顶,然后调整;但是,树叶一般比较大,放于堆顶后,几乎总是要进行多次的比较才能恢复堆的结构。
MIT公开课-线性代数笔记
目录方程组的几何解释 (2)矩阵消元 (3)乘法和逆矩阵 (4)A的LU分解 (6)转置-置换-向量空间R (8)求解AX=0:主变量,特解 (9)求解AX=b:可解性和解的解构 (10)线性相关性、基、维数 (11)四个基本子空间 (12)矩阵空间、秩1矩阵和小世界图 (13)图和网络 (14)正交向量与子空间 (15)子空间投影 (18)投影矩阵与最小二乘 (20)正交矩阵和Gram-Schmidt正交化 (21)特征值与特征向量 (27)对角化和A的幂 (28)微分方程和exp(At)(待处理) (29)对称矩阵与正定性 (29)正定矩阵与最小值 (31)相似矩阵和若尔当型(未完成) (32)奇异值分解(SVD) (33)线性变换及对应矩阵 (34)基变换和图像压缩 (36)NOTATIONp:projection vectorP:projection matrixe:error vectorP:permutation matrixT:transport signC(A):column spaceN(A):null spaceU:upper triangularL:lower triangularE:elimination matrixQ:orthogonal matrix, which means the column vectors are orthogonalE:elementary/elimination matrix, which always appears in the elimination of matrix N:null space matrix, the “solution matrix” of AX=0R:reduced matrix, which always appears in the triangular matrix, “IF00”I:identity matrixS:eigenvector matrixΛ:eigenvalue matrixC:cofactor matrix关于LINER ALGEBA名垂青史的分析方法:由具象到抽象,由二维到高维。
算法导论读书笔记
算法导论读书笔记【篇一:《算法概论》读书笔记及读后感】《算法概论》读书笔记12计转1 12130907 李酉辰第0章本章较为简短,没有深入系统地涉及某些内容。
主要以fibonacci 数列的例子,让我体会了递归和递推思想的差别。
针对fibonacci数列例子直接递归解法中涉及的重复计算,优化出递推方式,展示了思考问题中自顶向下与自底向上的不同思考角度可能产生较大的算法效率差别,同时隐约体现记忆化搜索的思想。
另外本章较为详细介绍了大o复杂度度量标准。
第1章本章以rsa算法为例,细致深入讨论了rsa算法涉及的相关数论知识,诸如取模运算、模下的四则运算与逆元概念、取模幂运算、素性检测。
在素性检测部分有经典的欧几里德算法、扩展欧几里德算法,同时引入随机化算法概念,以极高的概率保证素性检测有效性。
通过本章的学习,我对过去不曾深入考虑或者说真正考虑的基础性运算有了更深的理解。
之前对乘除运算复杂度总是在以单元操作的概念下以o(1)带过,以后会更加细致地考虑乘除等基本运算的复杂度。
另外,本章以rsa为案例,系统地展示了针对某一问题,如何从基础性知识入手,一步一步学习案例所需基础知识,并将其整合从而解决案例。
素性检测与素因子分解,两个看似相去不远的问题,其复杂性天差地别的现实,从一般角度让人们想到的是类似问题的解决难度可能差别很大仅此而已,而rsa算法展示了如何深入的多想一步,利用这种情况设计出优雅的解决方案。
这思想很值得我借鉴与利用。
第2章本章介绍分治算法思想,提及分治,相信每一个学习算法的人都不会陌生,经典的《算法导论》中就已合并排序为例在开篇不久就引入分治概念。
本书介绍分治的角度与众不同,不似《导论》中总是介绍比较显而易见的可以分治的案例。
本书列举了矩阵相乘、快速傅立叶变换等数学领域分治的应用案例,在这些案例之中,分治的应用很多情况下隐藏的较为深,并非显而易见,加大了分析难度。
但是更能让我感受到分治应用之广泛,可能在学习本章之前,许多类型的题目我不会想到去向分治的角度思考,因为不易看出,但是本章给我的备忘录上加了一条:永远不要忽视分治,针对陌生题目,不要轻易就否决掉往分治角度思考的路线。
《算法导论》读书笔记 附录A习题解答
A.1-1求的简化公式。
利用等差级数求和公式和级数线性性质:
A.1-2利用调和级数性质证明。
利用调和级数性质:
A.1-3对,证明。
对无穷递减几何级数式两边求导,再乘以:
对该式再进行同上操作得到:
A.1-4 求。
A.1-5 求的值。
当时求得
当时:
计算得到:
A.1-6 利用求和公式的线性特征证明。
令,则下式显然成立:
再把函数代换回即可。
A.1-7 求的值。
A.1-8 求的值。
A.2-1 证明有常量上界。
A.2-2 求和的渐近上界。
故渐近上界是
A.2-3 通过分割求和证明第个调和数是。
故取得下界
A.2-4 通过积分求的近似值。
A.2-5 题略。
为了保证被积函数在积分域上都连续。
思考题
A-1 求和的界
求下列和式的渐近确界。
假设,都是常量。
a)
,得到确界为
b)
根据此式得到上界:
故得到下界:
故据此得到确界
c)
故得到上界:
故得到下界:
因此得到确界。
藏书阁-《算法导论》常见算法总结
常见算法总结分治法分治策略的思想:顾名思义,分治是将一个原始问题分解成多个子问题,而子问题的形式和原问题一样,只是规模更小而已,通过子问题的求解,原问题也就自然出来了。
总结一下,大致可以分为这样的三步:分解:将原问题划分成形式相同的子问题,规模可以不等,对半或2/3对1/3的划分。
解决:对于子问题的解决,很明显,采用的是递归求解的方式,如果子问题足够小了,就停止递归,直接求解。
合并:将子问题的解合并成原问题的解。
这里引出了一个如何求解子问题的问题,显然是采用递归调用栈的方式。
因此,递归式与分治法是紧密相连的,使用递归式可以很自然地刻画分治法的运行时间。
所以,如果你要问我分治与递归的关系,我会这样回答:分治依托于递归,分治是一种思想,而递归是一种手段,递归式可以刻画分治算法的时间复杂度。
所以就引入本章的重点:如何解递归式?分治法适用的情况分治法所能解决的问题一般具有以下几个特征:1. 该问题的规模缩小到一定的程度就可以容易地解决2. 该问题可以分解为若干个规模较小的相同问题,即该问题具有最优子结构性质。
3. 利用该问题分解出的子问题的解可以合并为该问题的解;4. 该问题所分解出的各个子问题是相互独立的,即子问题之间不包含公共的子子问题。
第一条特征是绝大多数问题都可以满足的,因为问题的计算复杂性一般是随着问题规模的增加而增加;第二条特征是应用分治法的前提它也是大多数问题可以满足的,此特征反映了递归思想的应用;、第三条特征是关键,能否利用分治法完全取决于问题是否具有第三条特征,如果具备了第一条和第二条特征,而不具备第三条特征,则可以考虑用贪心法或动态规划法。
第四条特征涉及到分治法的效率,如果各子问题是不独立的则分治法要做许多不必要的工作,重复地解公共的子问题,此时虽然可用分治法,但一般用动态规划法较好。
——————————————————————————————最大堆最小堆1、堆堆给人的感觉是一个二叉树,但是其本质是一种数组对象,因为对堆进行操作的时候将堆视为一颗完全二叉树,树种每个节点与数组中的存放该节点值的那个元素对应。
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).。
算法导论读书笔记
算法导论读书笔记算法导论读书笔记篇1《算法导论》是计算机科学中一门重要的课程,它是一本经典的算法教材,被广泛使用于各个领域。
这本书的作者是美国计算机科学家ChristopherD.H.Anderson,他是一位著名的计算机科学家和数学家,曾在斯坦福大学和卡内基梅隆大学任教。
这本书主要介绍了各种基本算法,包括排序、搜索、图论、动态规划、贪心算法、分治算法等。
它通过示例代码和问题解决的方式,向读者展示了如何使用这些算法来解决实际问题。
这本书的特点是简洁明了、易于理解、逻辑清晰、重点突出。
作者在书中使用了通俗易懂的语言和简单的例子,使得读者可以轻松地理解各种算法的原理和应用。
同时,作者还对各种算法进行了深入的分析和比较,使得读者可以更好地理解它们的优缺点和应用场景。
在阅读这本书的过程中,我深刻地感受到了算法的重要性和应用价值。
算法是一种解决问题的工具,它可以帮助我们快速地解决复杂的问题,提高工作效率。
同时,算法也是一种思维方式和解决问题的手段,它可以帮助我们更好地理解问题和现象,提高我们的逻辑思维能力和解决问题的能力。
在阅读这本书的过程中,我遇到了一些困难和挑战。
首先,书中的算法种类繁多,有些算法比较抽象,需要深入思考才能理解它们的原理和应用。
其次,书中的代码示例比较简单,需要自己动手实现才能更好地理解算法的原理和应用。
总的来说,《算法导论》是一本非常优秀的教材,它可以帮助我们更好地理解算法的原理和应用,提高我们的逻辑思维能力和解决问题的能力。
在未来的学习和工作中,我将继续深入学习和研究算法,不断提高自己的专业水平和实践能力。
算法导论读书笔记篇2《算法导论》是计算机科学中广泛使用的一种经典算法教材。
本书的目的是为学生提供一种系统而全面的算法学习体验,旨在帮助学生理解算法的基本原理,掌握常见算法的实现和应用,提高编程能力和解决问题的能力。
本书共有11个章节,涵盖了各种常见算法的介绍和实现,如排序、搜索、图论、动态规划、贪心算法等。
麻省理工学院-算法导论
麻省理工学院-算法导论关于课本的介绍如下:本书自第一版出版以来,已经成为世界范围内广泛使用的大学教材和专业人员的标准参考手册。
本书全面论述了算法的内容,从一定深度上涵盖了算法的诸多方面,同时其讲授和分析方法又兼顾了各个层次读者的接受能力。
各章内容自成体系,可作为独立单元学习。
所有算法都用英文和伪码描述,使具备初步编程经验的人也可读懂。
全书讲解通俗易懂,且不失深度和数学上的严谨性。
第二版增加了新的章节,如算法作用、概率分析与随机算法、线性编程等,几乎对第一版的各个部分都作了大量修订。
学过计算机的都知道,这本书是全世界最权威的算法课程的大学课本了,基本上全世界的名牌大学用的教材都是它。
这本书一共四位作者,Thomas H. Cormen,Charles E. Leiserson和Ronald L. Rivest是来自MIT的教授,Clifford Stein是MIT出来的博士,现在哥伦比亚大学做教授,四人姓氏的首字母联在一起即是此书的英文简称(CLRS 2e),其中的第三作者Ronald L. Rivest是RSA算法的老大(算法名字里面的R即是指他),四个超级大牛出的一本书,此书不看人生不能算完整。
再介绍一下课堂录像里面授课的两位MIT的老师,第一位,外表“绝顶聪明”的,是本书的第二作者Charles E. Leiserson,以逻辑严密,风趣幽默享誉MIT。
第二位,留着金黄色的络腮胡子和马尾发的酷哥是Erik Demaine,21岁即取得MIT教授资格的天才,1981出生,今年才25岁,业余爱好是俄罗斯方块、演戏、琉璃、折纸、杂耍、魔术和结绳游戏。
另外,附上该书的中文电子版,pdg转pdf格式,中文版翻译自该书的第一版,中文书名没有使用《算法导论》,而使用的是《现代计算机常用数据结构和算法》,1994年出版时没有得到国外的授权,属于“私自翻译出版”,译者是南京大学计算机系的潘金贵。
课程重点算法导论是麻省理工学院电机工程与计算机科学系“理论计算机科学”集中选修课程的先导科目。
算法导论学习总结
算法导论学习总结这本书给我这样的感觉:有时遇到一个算法,在网上找了很多相关资料,但是看完后还是有点迷茫,然后才想起《算法导论》,遇到翻开目录,发现有相关的章节,于是去认真阅读,顿时发现自己的很多问题都可以解决了。
它就是这么一本书,也许你会把它当一本圣经来供养,但是当你认真阅读后,你会发现你受益颇多。
于是,自从几次问题通过《算法导论》解决后,我开始意识到,这是一个多么大的宝库啊。
它容纳的目前常用的诸多算法,并且都给予了详细解释,图文并茂,易于理解。
到目前为止,中间零散的看过一些章节。
我有这么一个习惯,就是每学到一个算法,我都会把这个算法总结一下,我觉得虽然当时写这个总结时有点占用时间,但是当你再温故时,你只需要短短的5分钟,就可以再次记住这个算法,并且通过以前总结的,你也许还可以发现不足,并改正。
就像我之前有两次都中断了算法的学习,并且一断就是几个月,但是当我再次拾起算法时,我只需要看看我以前总结的笔记,就可以很快的拾起。
所以,这次我也准备把《算法导论》这本书好好总结一下,这样当我总结时,我就可以知道哪些我彻底掌握了,因为如果我只掌握其表面内容,我是没法用自己的话去总结。
二是这样大家通过各种搜索引擎搜到我的文章时,可以互相探讨,并且发现哪些地方我理解错了,因为我是非计科生,从大一到现在都是我自己一个人自学过来的`,中间肯定会走一些弯路,对一些知识产生曲解,所以这样也可以通过大家来改正我的错误,大家互相学习,互相探讨,交一个可以讨论学术的朋友,何乐而不为呢?网上有些朋友推荐再遇到算法问题时可以把《算法导论》当字典来查,但是个人觉得,这本书读多少遍都值得,所以完完整整的把这本书看一遍是必须的,以后再可以当一个工具书去查。
所以推荐大家一起好好把《算法导论》学习下。
另外,我推荐每学一个算法,就去各个OJ(Online Judge)找一些相关题目做做,有时理论让人很无语,分析代码也是一个不错的选择。
对于接下来要写的一些总结文章,我想做一些约定:1.写这个总结,我不能确定时间,也许一天总结一章,也许几天总结一章,但是我不会断的,鉴于书上有35章,我估计最快得两个月的时间,最慢应该会花3个月在暑期之前搞定。
《算法导论》学习总结——快速排序
《算法导论》学习总结——快速排序曾经在程序员杂志上看到快速排序的作者,Hoare,曾经的图灵奖获得者啊,牛光闪闪的。
不过当时,对快速排序什么的,印象不算深刻,毕竟没好好学。
记得当时杂志上说到的是,快速排序,应该是目前最快的内部排序算法(虽然独立到语言上,C++的sort会比调用快速排序快)。
现在就进入快速排序的美好复习吧。
与归并排序类似,快排也用分治模式。
主要是三个步骤:1)分解:将数组A[p....r]划分为2个子数组A[p....q-1]和A[q+1....r],使前一个每个元素都小于A[q],后一个数组,每个元素都大于A[q](q在划分过程中计算)2)解决:递归调用快速排序,对2个子数组进行排序3)合并:因为2个子数组是就地排序,所以合并不用操作,数组已排序看到这个合并,就想到啊,和归并比,一个从小到大,一个从大到小,差距就是这么大,快排么得合并开销,一下就省了很多啊,说明,方向很重要啊,如同那句,同样一个B,S与N 的差别,大家都懂的。
快速排序的实现代码如下:1//===============================================================2// Name : Qsort.cpp3// Author : xia4// Copyright : NUAA5// Description : 快速排序的实现6//===============================================================7#include <iostream>8#include <vector>9#include <fstream>10#include <algorithm>11#include <ctime>1213using namespace std;14const int MAX = 1000 ;1516void WriteToFile(vector<int> v)17{//将v写入文件,纯看排序结果是否正确,也可以写个test()18int i;19 ofstream result("Qsort.txt");20if (result.fail())21 {22 cout << " open data error " << endl;23 exit(EXIT_FAILURE);24 }25for (i=0 ; i<v.size() ; i++)26 {27 result << v[i] << " " ;28 }29 result.close();30}31int Partion(vector<int> &A,int p ,int r)32{//数组划分33int x=A[r];//x都感觉没用34int i=p-1;35for (int j=p ; j<r ;j++)36 {37if ( A[j] <= x )38 {39 i++;40 swap(A[i],A[j]);41 }42 }43 swap(A[i+1],A[r]);44return i+1;45}46void Qsort(vector<int> &A, int p ,int r)47{//递归快排48if (p < r)49 {50int q = Partion(A,p,r);51 Qsort(A,p,q-1);52 Qsort(A,q+1,r);53 }54}55int main(int argc, char **argv)56{57 vector<int> v;58int i;59for (i=0 ; i< MAX ;i++)60 v.push_back(i);61 random_shuffle(v.begin(),v.end());//打乱6263 Qsort(v,0,v.size()-1);64 WriteToFile(v);6566return 0;67}说到代码,很惭愧的,/chinazhangjie/archive/2010/12/09/1901491.html张杰同学的c++模板类实现,(这里也得感谢Tanky Woo,看了他的总结,得以看很多的链接),果然我写的只是C的扩充啊,像用vector只是防止溢出,也就是数组来使用,一些操作也只是作为一个扩充。
超详细MIT线性代数公开课笔记 完整版
第三行: 0 0
1 2 关键第二行: -3 1 0 3 8 0 4
1 0 3 0 1 1 3 0 1 1 1
2 1 8 1 1 2 1 4 1 2 1 8 1 0 4 1 4 1 -3 [1 2 1] 1 [3 8 1] 0 2 2 0 [0 4 1] 1 2 1 1 0 2 0 4 1 E21A 1 2 1
* * * 例如消成这样 0 * * 0 0 0
回代 Back-Substitution
8
做方程的高斯消元时,需要对等式右侧的 b 做同样的乘法和加减法。手工计算 时比较有效率的方法是应用“增广矩阵” (augmented matrix) ,将 b 插入矩阵 A 之后形成最后一列,在消元过程中带着 b 一起操作。 (Matlab 是算完系数矩阵再处 理 b 的。 )
在列图像中,我们将系数矩阵写成列向量的形式,则求解原方程变为寻找列向 量的线性组合(linear combination)来构成向量 b。
4
x
2 1 0 y 1 2 3
向量线性组合是贯穿本课程的重要概念。对于给定的向量 c 和 d 以及标量 x 和 y,我们将 xc+yd 称之为 c 和 d 的一个线性组合。 从几何上讲, 我们是寻找满足如下要求的 x 和 y, 使得两者分别数乘对应的列向
1 2 1 1 2 1 2 1 2 1 2 2 6 3 8 1 12 0 2 - 2 6 0 2 - 2 0 0 5 - 10 0 4 1 2 0 4 1 2 2 此时我们将原方程 Ax=b 转化为了新的方程 Ux=c,其中 c= 6 。 - 10
算法导论复习笔记
《算法导论》复习笔记Chapter 22 基本图算法22、1-1 有向图邻接链表,计算节点出度与入度的时间复杂度?O(V+E)开一个degree[]数组,大小为结点个数,复杂度O(V);遍历邻接链表,经过边uv时,计算出度degree[u]+=1,计算入度degree[v]+=1,复杂度O(E) 22、1-4 将一个多图变成等价无向图,用邻接链表表示,时间复杂度O(V+E)多图就是允许重复边与自循环边的图。
开一个bool数组mark[],大小为节点个数,初始化为false。
复杂度O(V)。
对每个顶点u的邻接链表,遍历,令v为u的边所指向的顶点;如果mark[v]=false,将uv加入新图,并将mark[v]设置为true;否则就跳过。
复杂度O(E)再次遍历u的连边,将mark[v]初始化整体复杂度O(V+E)伪代码:SOLVE(G,G’)1 for each vetex u∈G2 for each v∈ G、Adj[u]3 if mark[v]==false4 mark[v]==true5 Addedge(G’,u,v)6 for each v∈G、Adj[u]7 mark[v]=false22、1-6 图G的邻接矩阵表示,给出一个O(V)的算法来判断有向图G中就是否存在一个通用汇点。
通用汇点指的就是入度|V|-1,但出度为0。
等价问题:给定有向图G的V×V邻接矩阵G,在O(V)时间内判断就是否存在一个数k,使得对所有的i有A[i][k]=1,对所有的j有A[k][j]=0,(i≠k,j≠k)令i与j初值为1,若G[i][j]=0,说明i到j无边,j不可能就是通用汇点,令j=j+1;若G[i][j]=1,说明i到j有边,i不可能就是通用汇点,令i=i+1,循环直到i>|V|或者j>|V|;若i>|V|,则不存在通用汇点,若j>|V|,则检查顶点i就是否满足要求。
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).
算法导论-复习笔记
《算法导论》复习笔记Chapter 22 基本图算法22.1—1 有向图邻接链表,计算节点出度和入度的时间复杂度?O(V+E)开一个degree[]数组,大小为结点个数,复杂度O(V);遍历邻接链表,经过边uv时,计算出度degree[u]+=1,计算入度degree[v]+=1,复杂度O(E)22。
1—4 将一个多图变成等价无向图,用邻接链表表示,时间复杂度O(V+E)多图是允许重复边和自循环边的图。
开一个bool数组mark[],大小为节点个数,初始化为false.复杂度O(V)。
对每个顶点u的邻接链表,遍历,令v为u的边所指向的顶点;如果mark[v]=false,将uv加入新图,并将mark[v]设置为true;否则就跳过。
复杂度O(E)再次遍历u的连边,将mark[v]初始化整体复杂度O(V+E)伪代码:SOLVE(G,G’)1 for each vetex u∈G2 for each v∈ G。
Adj[u]3 if mark[v]==false4 mark[v]==true5 Addedge(G’,u,v)6 for each v∈G。
Adj[u]7 mark[v]=false22.1—6 图G的邻接矩阵表示,给出一个O(V)的算法来判断有向图G中是否存在一个通用汇点。
通用汇点指的是入度|V|-1,但出度为0。
等价问题:给定有向图G的V×V邻接矩阵G,在O(V)时间内判断是否存在一个数k,使得对所有的i有A[i][k]=1,对所有的j有A[k][j]=0,(i≠k,j≠k)令i和j初值为1,若G[i][j]=0,说明i到j无边,j不可能是通用汇点,令j=j+1;若G[i][j]=1,说明i到j有边,i不可能是通用汇点,令i=i+1,循环直到i〉|V|或者j>|V|;若i>|V|,则不存在通用汇点,若j>|V|,则检查顶点i是否满足要求。
伪代码:判断是否存在通用汇点 O(V)HAS_UNIVERSL_SINK(G)1 i=j=12 while i≤V and j≤V3 if G[i][j]==14 i=i+15 else j=j+16 if i>V7 return false8 else return CHECK(G,i)CHECK(G,u)1 for each vertex v∈G.V2 if G[u][v]=13 return false4 for each vertex v ∈ G.V5 if G[v][u]==0& u!=v6 return false7 return true检查点u是否是通用汇点【宽度优先搜索】22。