算法导论ch10.ppt

合集下载

Ch10 ALGORITHM DESIGN TECHNIQUES(数据结构外文版)

Ch10 ALGORITHM DESIGN TECHNIQUES(数据结构外文版)

3. Approximate Bin Packing The Knapsack Problem
§1 Greedy Algorithms
A knapsack with a capacity M is to be packed. Given N items. Each item i has a weight wi and a profit pi . If xi is the percentage of the item i being packed, then the packed profit will be pi xi . An optimal packing is a feasible one with maximum profit. That is, we are supposed to find the values of xi such that i1 maximum under the constrains
Representation of the optimal Now, with in a binary tree code The answer is u = 110, x = 10, z = 111 a = 0, aaaxuaxz (with Cost ( aaaxuaxz 0, uThe trick=is: z ) 111). aand 00010110010111 = = the string 00010110010111, = 110, x 10, 1 = 14 + 31 + code+ 31 =decoding method No 22 is this 14 of another. either are leaves a prefix What makes All nodes can you decode it? children. 1 work? Any sequence of bits can alwaysor have two 0 be 0 decoded unambiguously if the characters 0 1 are placed only at the leaves of a full tree – a x u z such kind of code is called prefix code. Find the full binary tree of minimum total cost where all characters are contained in the leaves.

C入门经典(第4版)ch10简明教程PPT课件

C入门经典(第4版)ch10简明教程PPT课件

C入门经典(第4版) 10.3 计算机绘图系统的硬件组成
前面介绍过,stdin上的键盘输入有两种形式:一种是格式化输入,主要 由scanf()函数提供;另一种是非格式化输入,通过getchar()等函数接收原始的 字符数据。这两种形式都很常见,下面详细介绍它们。 格式化键盘输入 输入格式控制字符串 输入格式字符串中的字符 输入浮点数的各种变化 读取十六进制和八进制值 用scanf()读取字符 scanf()的陷阱 从键盘上输入字符串 键盘的非格式化输入
C入门经典(第4版) 10.3.8 从键盘上输入字符串
<stdio.h>头文件中的gets()函数可以将一整行的文本作为字符串读入。它 的函数原型如下: char *gets(char *str); 这个函数会将连续的字符读入指针str所指的内存中,直到按下回车键为 止。它会用终止字符'\0'取代按下回车键时读入的换行符。其返回值与变元相 同,即存储字符串的地址
C入门经典(第4版) 10.3.2 输入格式控制字符串
在scanf()或wscanf()函数中使用的格式控制字符串不完全类似于printf()中 的格式控制字符串。在格式控制字符串中添加一个或多个空白字符,如空格‘ ’、 制表符‘\t’或换行符‘n’,scanf()会忽略空白字符,直接读入输入中的下一个非空 白字符。在格式控制字符串中只要出现一个空白字符,就会造成无数个连续的 空白字符被忽略。因此,可以在格式字符串内加入任意多个的空白字符,使输 入易于理解。注意,scanf()默认忽略空白字符,但使用%c、%[]或%n指定符 读取数据时除外 。
第一个例子尝试过读入字符串,读入字符串还有其他方法。有3个格式指 定符用于读取一个或多个单字节字符。使用格式指定符%c可以读取一个字符, 并将它存储为char类型,如果使用的是%lc,就存储为wchar_t类型。对于字符 串,可以使用指定符%s或%[],如果要将输入存储为宽字符,就使用%ls或 %l[],其中转换指定符的前缀是L的小写。此时要给存储的字符串追加终止字 符‘\0’,作为最后一个字符。使用格式符%[]或%l[]读入的字符串必须只包含方 括号内的字符,如果方括号中的第一个字符是^时,则读入的字符串不能包含 方括号内^字符后面的任何字符,例如%[aeiou]读入的字符串只能包含元音。 碰到不是元音的字符就停止输入。而%[^aeiou]读入的字符串不能包含元音。 碰到元音就停止输入 。

ch10

ch10
10-12
LO 2 Identify the costs to include in initial valuation of property, plant, and equipment.
Acquisition of PP&E
E10-1 (variation): The expenditures and receipts below are related to

cost method or fair value (revaluation) method.
10-8
LO 2 Identify the costs to include in initial valuation of property, plant, and equipment.
Acquisition of PP&E

―Used in operations‖ and not for resale.
Includes: Land,

Long-term in nature and usually depreciated.
Building structures
(offices, factories, warehouses), and
land, land improvements, and buildings acquired for use in a business enterprise. Determine how the following should be classified: Classification (g) Architect’s fee on building (h) Cost of real estate purchased as a plant site (land €200,000 and building €50,000) Building

notes_ch10

notes_ch10

Chlorine: DfHø(Cl-, aq) = -167.2 kJ mol-1 + DfGø(Ag+, aq) = -131.2 kJ mol-1
»
Determine ions by difference from reaction enthalpy /Gibbs energy
Silver: DrHø = DfHø(Ag+, aq) + DfHø (Cl-,aq) or =DfHø(Ag+, aq) = DrHø - DfHø (Cl-,aq) DfHø(Ag+, aq) =-61.58 kJ mol-1 - (-167.2 kJ mol-1 ) = 105.6 kJ mol-1
»

ideal + RTln(g ) The chemical potential, µi, becomes µ i=µ i +And G becomes G = p µ ++qµ Again non-ideality is shared
D solvG where z i charg e of ion ri radius of ion N A Avagodro' s number 1 8e 0 ri e G
e 0 vacuum permitivity

For water, Born equation becomes DsolGø = 6.86 x 104(zi2/ri) kJ mol-1
Some ions have positive DfSø and some negative relative to H+
»
Means that relative to water Mg2+ induces more order and Cl- less

电路课件-ch10

电路课件-ch10

2020/7/13
R u11iR (L 1i1LM 1 dd)tid dtiM
di dt
u2
R2iL2
di dt
M
di dt
R2i(L2M)d dti
18
18
1. 耦合电感的串联
I R1 jL1
++
U
_
U 1 jM
+
R2
U 2
Z_
jL2
_
U 1[R 1j(L 1M )I ] U 2 [R 2j(L 2M )I ]
2020/7/13
3
2020/7/13
3
变压器
2020/7/13
4
2020/7/13
4
变压器
2020/7/13
5
2020/7/13
5
有载调压变压器
2020/7/13
6
2020/7/13
6
小变压器
2020/7/13
7
2020/7/13
7
调压器 牵引电磁铁 2020/7/13
2020/7/13
2020/7/13
22
2020/7/13
22
2. 耦合电感的并联
I3
jM ①
+ I1
U jL1
去耦思想 U (R 1jL 1)I 1jM I 2
I 2 jL2
U jM I 1 (R 2 jL 2 )I 2
I3 I1 I2 U jM I 3 [R 1 ( j(L 1 M )I 1 ]
1' 1 I1 jM 2'I2 2
+
U 1 jL1
+
jL2 U 2

Ch10算法导论 第三版 第十章 答案 英

Ch10算法导论 第三版 第十章 答案 英

Chapter10Michelle Bodnar,Andrew LohrApril12,2016Exercise10.1-14414134141841Exercise10.1-2We will call the stacks T and R.Initially,set T.top=0and R.top=n+1. Essentially,stack T uses thefirst part of the array and stack R uses the last part of the array.In stack T,the top is the rightmost element of T.In stack R, the top is the leftmost element of R.Algorithm1PUSH(S,x)1:if S==T then2:if T.top+1==R.top then3:error“overflow”4:else5:T.top=T.top+16:T[T.top]=x7:end if8:end if9:if S==R then10:if R.top−1==T.top then11:error“overflow”12:else13:R.top=R.top−114:T[T.top]=x15:end if16:end if1Algorithm2POP(S)if S==T thenif T.top==0thenerror“underflow”elseT.top=T.top−1.return T[T.top+1]end ifend ifif S==R thenif R.top==n+1thenerror“underflow”elseR.top=R.top+1.return R[R.top−1]end ifend ifExercise10.1-34414131313838Exercise10.1-4Algorithm3ENQUEUEif Q.head==Q.tail+1,or Q.head==1and Q.tail==Q.length then error“overflow”end ifQ[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.head+1end ifExercise10.1-5As in the example code given in the section,we will neglect to check for overflow and underflow errors.2Algorithm4DEQUEUEerror“underflow”end ifx=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifreturn xAlgorithm5HEAD-ENQUEUE(Q,x) Q[Q.head]=xif Q.head==1thenQ.head=Q.lengthelseQ.head=Q.head−1end ifAlgorithm6TAIL-ENQUEUE(Q,x) Q[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.tail+1end ifAlgorithm7HEAD-DEQUEUE(Q,x) x=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifAlgorithm8TAIL-DEQUEUE(Q,x) x=Q[Q.tail]if Q.tail==1thenQ.tail=Q.lengthelseQ.tail=Q.tail−1end if3Exercise10.1-6The operation enqueue will be the same as pushing an element on to stack 1.This operation is O(1).To dequeue,we pop an element from stack2.If stack 2is empty,for each element in stack1we pop it off,then push it on to stack2. Finally,pop the top item from stack2.This operation is O(n)in the worst case.Exercise10.1-7The following is a way of implementing a stack using two queues,where pop takes linear time,and push takes constant time.Thefirst of these ways,consists of just enqueueing each element as you push it.Then,to do a pop,you dequque each element from one of the queues and place it in the other,but stopping just before the last element.Then,return the single element left in the original queue.Exercise10.2-1To insert an element in constant time,just add it to the head by making it point to the old head and have it be the head.To delete an element,it needs linear time because there is no way to get a pointer to the previous element in the list without starting at the head and scanning along.Exercise10.2-2The PUSH(L,x)operation is exactly the same as LIST-INSERT(L,x).The POP operation sets x equal to L.head,calls LIST-DELETE(L,L.head),then returns x.Exercise10.2-3In addition to the head,also keep a pointer to the last element in the linked list.To enqueue,insert the element after the last element of the list,and set it to be the new last element.To dequeue,delete thefirst element of the list and return it.Exercise10.2-4First let L.nil.key=k.Then run LIST-SEARCH’as usual,but remove the check that x=L.nil.Exercise10.2-5To insert,just do list insert before the current head,in constant time.To search,start at the head,check if the element is the current node being in-spected,check the next element,and so on until at the end of the list or you4found the element.This can take linear time in the worst case.To delete,again linear time is used because there is no way to get to the element immediately before the current element without starting at the head and going along the list.Exercise10.2-6Let L1be a doubly linked list containing the elements of S1and L2be a doubly linked list containing the elements of S2.We implement UNION as fol-lows:Set L1.nil.prev.next=L2.nil.next and L2.nil.next.prev=L1.nil.prev so that the last element of L1is followed by thefirst element of L2.Then set L1.nil.prev=L2.nil.prev and L2.nil.prev.next=L1.nil,so that L1.nil is the sentinel for the doubly linked list containing all the elements of L1and L2. Exercise10.2-7Algorithm9REVERSE(L)a=L.head.nextb=L.headwhile a=NIL dotmp=a.nexta.next=bb=aa=tmpend whileL.head=bExercise10.2-8We will store the pointer value for L.head separately,for convenience.In general,A XOR(A XOR C)=C,so once we know one pointer’s true value we can recover all the others(namely L.head)by applying this rule.Assuming there are at least two elements in the list,thefirst element will contain exactly the address of the second.Algorithm10LISTnp-SEARCH(L,k)p=NILx=L.headwhile x=NIL and x.key=k dotemp=xx=pXORx.npp=tempend whileTo reverse the list,we simply need to make the head be the“last”ele-5Algorithm11LISTnp-INSERT(L,x)x.np=L.headL.nil.np=xXOR(L.nil.npXORL.head)L.head=xAlgorithm12LISTnp-Delete(L,x)L.nil.np=L.nil.npXORL.headXORL.head.npL.head.np.np=L.head.np.npXORL.headment before L.nil instead of thefirst one after this.This is done by settingL.head=L.nil.npXORL.head.Exercise10.3-1A multiple array version could be L=2,/34567/124819511/23456A single array version could be L=4,127/410481371916105191311/16 Exercise10.3-2Algorithm13Allocate-Object()if free==NIL thenerror“out of space”elsex=freefree=A[x+1]end ifExercise10.3-3Allocate object just returns the index of some cells that it’s guaranteed tonot give out again until they’ve been freed.The prev attribute is not modified because only the next attribute is used by the memory manager,it’s up to the code that calls allocate to use the prev and key attributes as it seesfit.Exercise10.3-4For ALLOCATE-OBJECT,we will keep track of the next available spot inthe array,and it will always be one greater than the number of elements being stored.For FREE-OBJECT(x),when a space is freed,we will decrement the6Algorithm14Free-Object(x)A[x+1]=freefree=xposition of each element in a position greater than that of x by1and update pointers accordingly.This takes linear time.Exercise10.3-5See the algorithm COMP ACT IF Y−LIST(L,F)Exercise10.4-1181274510221Note that indices8and2in the array do not appear,and,in fact do not represent a valid tree.Exercise10.4-2See the algorithm PRINT-TREE.Exercise10.4-3Exercise10.4-4See the algorithm PRINT-TREE.Exercise10.4-5See the algorithm INORDER-PRINT’(T)Exercise10.4-6Our two pointers will be left and right.For a node x,x.left will point to the leftmost child of x and x.right will point to the sibling of x immediately to its right,if it has one,and the parent of x otherwise.Our boolean value b,stored at x,will be such that b=depth(x)mod2.To reach the parent of a node, simply keep following the“right”pointers until the parity of the boolean value changes.Tofind all the children of a node,start byfinding x.left,then follow7Algorithm15COMPACTIFY-LIST(L,F)if n=m thenreturnend ife=max{max i∈[m]{|key[i]|},max i∈L{|key[i]|}}increase every element of key[1..m]by2efor every element of L,if its key is greater than e,reduce it by2e f=1while key[f]<e dof++end whilea=L.headif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE−OBJECT(a)f++while key[f]<e dof++end whileend ifwhile a=L.head doif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE−OBJECT(a)f++while key[f]<e dof++end whileend ifend while8Algorithm16PRINT-TREE(T.root) if T.root==NIL thenreturnelsePrint T.root.keyPRINT-TREE(T.root.left)PRINT-TREE(T.root.right)end ifAlgorithm17INORDER-PRINT(T) let S be an empty stackpush(S,T)while S is not empty doU=pop(S)if U=NIL thenprint U.keypush(S,U.left)push(S,U.right)end ifend whileAlgorithm18PRINT-TREE(T.root) if T.root==NIL thenreturnelsePrint T.root.keyx=T.root.left−childwhile x=NIL doPRINT-TREE(x)x=x.right−siblingend whileend if9Algorithm19INORDER-PRINT’(T) a=T.leftprev=Twhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend whileprint T.keya=T.rightwhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend while10the“right”pointers until the parity of the boolean value changes,ignoring thislast node since it will be x.Problem10-1For each,we assume sorted means sorted in ascending orderunsorted,single sorted,single unsorted,double sorted,double SEARCH(L,k)n n n nINSERT(L,x)1111DELET E(L,x)n n11SUCCESSOR(L,x)n1n1P REDECESSOR(L,x)n n n1 MINIMUM(L,x)n1n1MAXIMUM(L,x)n n n1 Problem10-2In all three cases,MAKE-HEAP simply creates a new list L,sets L.head=NIL,and returns L in constant time.Assume lists are doubly linked.To realizea linked list as a heap,we imagine the usual array implementation of a binaryheap,where the children of the i th element are2i and2i+1.a.To insert,we perform a linear scan to see where to insert an element suchthat the list remains sorted.This takes linear time.Thefirst element in thelist is the minimum element,and we canfind it in constant time.Extract-minreturns thefirst element of the list,then deletes it.Union performs a mergeoperation between the two sorted lists,interleaving their entries such thatthe resulting list is sorted.This takes time linear in the sum of the lengthsof the two lists.b.To insert an element x into the heap,begin linearly scanning the list untilthefirst instance of an element y which is strictly larger than x.If no suchlarger element exists,simply insert x at the end of the list.If y does exist,replace y t by x.This maintains the min-heap property because x≤y andy was smaller than each of its children,so x must be as well.Moreover,xis larger than its parent because y was thefirst element in the list to exceedx.Now insert y,starting the scan at the node following x.Since we checkeach node at most once,the time is linear in the size of the list.To get theminimum element,return the key of the head of the list in constant time.To extract the minimum element,wefirst call MINIMUM.Next,we’ll replacethe key of the head of the list by the key of the second smallest element yin the list.We’ll take the key stored at the end of the list and use it toreplace the key of y.Finally,we’ll delete the last element of the list,and callMIN-HEAPIFY on the list.To implement this with linked lists,we need tostep through the list to get from element i to element2i.We omit this detailfrom the code,but we’ll consider it for runtime analysis.Since the value ofi on which MIN-HEAPIFY is called is always increasing and we never need11to step through elements multiple times,the runtime is linear in the length of the list.Algorithm20EXTRACT-MIN(L)min=MINIMUM(L)Linearly scan for the second smallest element,located in position i.L.head.key=L[i]L[i].key=L[L.length].keyDELETE(L,L[L.length])MIN-HEAPIFY(L[i],i)return minAlgorithm21MIN-HEAPIFY(L[i],i)1:l=L[2i].key2:r=L[2i+1].key3:p=L[i].key4:smallest=i5:if L[2i]=NIL and l<p then6:smallest=2i7:end if8:if L[2i+1]=NIL and r<L[smallest]then9:smallest=2i+110:end if11:if smallest=i then12:exchange L[i]with L[smallest]13:MIN-HEAPIFY(L[smallest],smallest)14:end ifUnion is implemented below,where we assume A and B are the two list representations of heaps to be merged.The runtime is again linear in the lengths of the lists to be merged.c.Since the algorithms in part b didn’t depend on the elements being distinct,we can use the same ones.Problem10-3a.If the original version of the algorithm takes only t iterations,then,we havethat it was only at most t random skips though the list to get to the desired value,since each iteration of the original while loop is a possible random jump followed by a normal step through the linked list.b.The for loop on lines2-7will get run exactly t times,each of which is constantruntime.After that,the while loop on lines8-9will be run exactly X t times.So,the total runtime is O(t+E[X t]).12Algorithm22UNION(A,B)1:if A.head=NIL then2:return B3:end if4:i=15:x=A.head6:while B.head=NIL do7:if B.head.key≤x.key then8:Insert a node at the end of list B with key x.key 9:x.key=B.head.key10:Delete(B,B.head)11:end if x=x.next12:end while13:return Aing equation C.25,we have that E[X t]= ∞i=1P r(X t≥i).So,we needto show that P r(X t≥i)≤(1−i/n)t.This can be seen because having X t being greater than i means that each random choice will result in an element that is either at least i steps before the desired element,or is after the desired element.There are n−i such elements,out of the total n elements that we were pricking from.So,for a single one of the choices to be from such a range, we have a probability of(n−i)/n=(1−i/n).Since each of the selections was independent,the total probability that all of them were is(1−i/n)t, as stly,we can note that since the linked list has length n,the probability that X t is greater than n is equal to zero.d.Since we have that t>0,we know that the function f(x)=x t is increasing,so,that means that x t≤f(x).So,n−1r=0r t=nr t dr≤nf(r)dr=n t+1e.E[X t]≤nr=1(1−r/n)t=nr=1ti=0ti(−r/n)i=ti=0nr=1ti(−r/n)i=ti=0ti(−1)in i−1+n−1r=0(r)t/n≤ti=0ti(−1)in i−1+n i+1/n ≤ti=0ti(−1)in ii+1=1t+1ti=0t+1i+1(−n)i≤(1−n)t+1t+1f.We just put together parts b and e to get that it runs in time O(t+n/(t+1)).But,this is the same as O(t+n/t).13g.Since we have that for any number of iterations t that the first algorithm takes to find its answer,the second algorithm will return it in time O (t +n/t ).In particular,if we just have that t =√n .The second algorithm takestime only O (√n ).This means that tihe first list search algorithm is O (√n )as well.h.If we don’t have distinct key values,then,we may randomly select an element that is further along than we had been before,but not jump to it because it has the same key as what we were currently at.The analysis will break when we try to bound the probability that X t ≥i .14。

ch10_计算思维与大学计算机基础_[共11页]

ch10_计算思维与大学计算机基础_[共11页]

246第10章程序设计基础程序设计作为一门技术,对程序员而言涉及程序设计方法与程序设计风格两方面内容。

将合理、高效的设计方法与良好的程序设计风格相结合,才能使开发出的程序结构清晰,便于维护。

本章首先介绍计算机求解问题的步骤和程序设计风格,然后分别介绍两种程序设计方法—— 结构化程序设计和面向对象程序设计。

10.1 计算机求解问题的步骤用计算机解决实际问题,就是在计算机中建立一个解决问题的模型。

在这个模型中,计算机内部的数据表示了需要被处理的实际对象(包括其内在的性质和关系),处理这些数据的程序则模拟对象领域中的求解过程。

通过解释计算机程序的运行结果,便得到了实际问题的解。

下面给出用计算机求解问题的一般步骤。

1.问题分析这个阶段的任务是弄清题目提供的已知信息和所要解决的问题是什么。

完整地理解和描述问题是解决问题的关键。

要做到这一点,必须注意以下一些问题:在未经加工的原始表达中,所用的术语是否都明白其准确定义?题目提供了哪些已知信息?还可以得到哪些潜在的信息?题目中做了哪些假定?题目要求得到什么结果?等等。

针对每个具体问题,必须认真审查问题的有关描述,深入分析,以加深对问题的准确理解。

2.数学模型建立用计算机解决实际问题必须建立合适的数学模型。

因为在现实问题面前,计算机是无能为力的。

对一个实际问题建立数学模型,可以考虑这样两个基本问题。

最适合于此问题的数学模型是什么?是否有已经解决了的类似问题可以借鉴?建立数学模型是最关键且较困难的一步,涉及四个世界和三级抽象。

四个世界分别是:现实世界(客观世界)、信息世界(概念世界)、数据世界、计算机世界。

三级抽象分别是:现实世界到信息世界的抽象,建立信息模型或概念模型;信息世界到数据世界的抽象,将信息数据转化建立数据模型;数据世界到计算机世界的抽象,建立存储模型在计算机中实现。

3.算法设计算法设计是指设计求解某一特定类型问题的一系列步骤,并且这些步骤是可以通过计算机的基本操作来实现的。

Ch10算法导论第三版第十章答案英

Ch10算法导论第三版第十章答案英

Ch10算法导论第三版第十章答案英Chapter10Michelle Bodnar,Andrew LohrApril12,2016Exercise10.1-14414134141841Exercise10.1-2We will call the stacks T and R.Initially,set T.top=0and R.top=n+1. Essentially,stack T uses the?rst part of the array and stack R uses the last part of the array.In stack T,the top is the rightmost element of T.In stack R, the top is the leftmost element of R.Algorithm1PUSH(S,x)1:if S==T then2:if T.top+1==R.top then3:error“over?ow”4:else5:T.top=T.top+16:T[T.top]=x7:end if8:end if9:if S==R then10:if R.top?1==T.top then11:error“over?ow”12:else13:R.top=R.top?1 14:T[T.top]=x 15:end if16:end if1Algorithm2POP(S) if S==T thenif T.top==0then error“under?ow”elseT.top=T.top?1. return T[T.top+1] end ifend ifif S==R thenif R.top==n+1then error“under?ow”elseR.top=R.top+1. return R[R.top?1] end ifend ifExercise10.1-34414131313838Exercise10.1-4Algorithm3ENQUEUEif Q.head==Q.tail+1,or Q.head==1and Q.tail==Q.length then error“over?ow”end ifQ[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.head+1end ifExercise10.1-5As in the example code given in the section,we will neglect to check for over?ow and under?ow errors.2Algorithm4DEQUEUEerror“under?ow”end ifx=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifreturn xAlgorithm5HEAD-ENQUEUE(Q,x) Q[Q.head]=xif Q.head==1thenQ.head=Q.lengthelseQ.head=Q.head?1end ifAlgorithm6TAIL-ENQUEUE(Q,x) Q[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.tail+1end ifAlgorithm7HEAD-DEQUEUE(Q,x) x=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifAlgorithm8TAIL-DEQUEUE(Q,x) x=Q[Q.tail]if Q.tail==1thenQ.tail=Q.lengthelseQ.tail=Q.tail?1end if3Exercise10.1-6The operation enqueue will be the same as pushing an element on to stack 1.This operation is O(1).To dequeue,we pop an element from stack2.If stack 2is empty,for each element in stack1we pop it o?,then push it on to stack2. Finally,pop the top item from stack2.This operation is O(n)in the worst case.Exercise10.1-7The following is a way of implementing a stack using two queues,where pop takes linear time,and push takes constant time.The?rst of these ways,consists of just enqueueing eachelement as you push it.Then,to do a pop,you dequque each element from one of the queues and place it in the other,but stopping just before the last element.Then,return the single element left in the original queue.Exercise10.2-1To insert an element in constant time,just add it to the head by making it point to the old head and have it be the head.To delete an element,it needs linear time because there is no way to get a pointer to the previous element in the list without starting at the head and scanning along.Exercise10.2-2The PUSH(L,x)operation is exactly the same as LIST-INSERT(L,x).The POP operation sets x equal to L.head,calls LIST-DELETE(L,L.head),then returns x.Exercise10.2-3In addition to the head,also keep a pointer to the last element in the linked list.To enqueue,insert the element after the last element of the list,and set it to be the new last element.T o dequeue,delete the?rst element of the list and return it.Exercise10.2-4First let L.nil.key=k.Then run LIST-SEARCH’as usual,but remove the check that x=L.nil.Exercise10.2-5To insert,just do list insert before the current head,in constant time.To search,start at the head,check if the element is the current node being in-spected,check the next element,and so on until at the end of the list or you4found the element.This can take linear time in the worst case.To delete,again linear time is used because there is no wayto get to the element immediately before the current element without starting at the head and going along the list.Exercise10.2-6Let L1be a doubly linked list containing the elements of S1and L2be a doubly linked list containing the elements of S2.We implement UNION as fol-lows:Set L1.nil.prev.next=L2.nil.next and L2.nil.next.prev=L1.nil.prev so that the last element of L1is followed by the?rst element of L2.Then set L1.nil.prev=L2.nil.prev and L2.nil.prev.next=L1.nil,so that L1.nil is the sentinel for the doubly linked list containing all the elements of L1and L2. Exercise10.2-7Algorithm9REVERSE(L)a=L.head.nextb=L.headwhile a=NIL dotmp=a.nexta.next=bb=aa=tmpend whileL.head=bExercise10.2-8We will store the pointer value for L.head separately,for convenience.In general,A XOR(A XOR C)=C,so once we know one pointer’s true value we can recover all the others(namely L.head)by applying this rule.Assuming there are at least two elements in the list,the?rst element will contain exactly the address of the second.Algorithm10LISTnp-SEARCH(L,k)p=NILx=L.headwhile x=NIL and x.key=k dotemp=xx=pXORx.npp=tempend whileTo reverse the list,we simply need to make the head be the“last”ele-5Algorithm11LISTnp-INSERT(L,x)x.np=L.headL.nil.np=xXOR(L.nil.npXORL.head)L.head=xAlgorithm12LISTnp-Delete(L,x)L.nil.np=L.nil.npXORL.headXORL.head.npL.head.np.np=L.head.np.npXORL.headment before L.nil instead of the?rst one after this.This is done by settingL.head=L.nil.npXORL.head.Exercise10.3-1A multiple array version could be L=2,/34567/124819511/23456A single array version could be L=4,127/410481371916105191311/16 Exercise10.3-2Algorithm13Allocate-Object()if free==NIL thenerror“out of space”elsex=freefree=A[x+1]end ifExercise10.3-3Allocate object just returns the index of some cells that it’s guaranteed tonot give out again until they’ve been freed.The prev attribute is not modi?ed because only the next attribute is used by the memory manager,it’s up to the code that calls allocate to use the prev and key attributes as it sees?t.Exercise10.3-4For ALLOCATE-OBJECT,we will keep track of the next available spot inthe array,and it will always be one greater than the number of elements being stored.For FREE-OBJECT(x),when a space is freed,we will decrement the6Algorithm14Free-Object(x)A[x+1]=freefree=xposition of each element in a position greater than that of x by1and update pointers accordingly.This takes linear time.Exercise10.3-5See the algorithm COMP ACT IF Y?LIST(L,F)Exercise10.4-1181274510221Note that indices8and2in the array do not appear,and,in fact do not represent a valid tree.Exercise10.4-2See the algorithm PRINT-TREE.Exercise10.4-3Exercise10.4-4See the algorithm PRINT-TREE.Exercise10.4-5See the algorithm INORDER-PRINT’(T)Exercise10.4-6Our two pointers will be left and right.For a node x,x.left will point to the leftmost child of x and x.right will point to the sibling of x immediately to its right,if it has one,and the parent of x otherwise.Our boolean value b,stored at x,will be such that b=depth(x)mod2.T o reach the parent of a node, simply keep following the“right”pointers until the parity of the boolean value changes.To?nd all the children of a node,start by?nding x.left,then follow7Algorithm15COMPACTIFY-LIST(L,F)if n=m thenreturnend ife=max{max i∈[m]{|key[i]|},max i∈L{|key[i]|}}increase every element of key[1..m]by2efor every element of L,if its key is greater than e,reduce it by2e f=1while key[f]<="" p="">f++end whilea=L.headif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE?OBJECT(a)f++while key[f]<="" p="">f++end whileend ifwhile a=L.head doif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE?OBJECT(a)f++while key[f]<="" p="">f++end whileend ifend while8Algorithm16PRINT-TREE(T.root) if T.root==NIL thenreturnelsePrint T.root.keyPRINT-TREE(T.root.left)PRINT-TREE(T.root.right)end ifAlgorithm17INORDER-PRINT(T) let S be an empty stack push(S,T)while S is not empty doU=pop(S)if U=NIL thenprint U.keypush(S,U.left)push(S,U.right)end ifend whileAlgorithm18PRINT-TREE(T.root) if T.root==NIL then returnelsePrint T.root.keyx=T.root.left?childwhile x=NIL doPRINT-TREE(x)x=x.right?siblingend whileend if9Algorithm19INORDER-PRINT’(T) a=T.leftprev=Twhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend whileprint T.keya=T.rightwhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend while10the“right”pointers until the parity of the boolean value changes,ignoring thislast node since it will be x.Problem10-1For each,we assume sorted means sorted in ascending order unsorted,single sorted,single unsorted,double sorted,double SEARCH(L,k)n n n nINSERT(L,x)1111DELET E(L,x)n n11SUCCESSOR(L,x)n1n1P REDECESSOR(L,x)n n n1 MINIMUM(L,x)n1n1MAXIMUM(L,x)n n n1 Problem10-2In all three cases,MAKE-HEAP simply creates a new list L,sets L.head=NIL,and returns L in constant time.Assume lists are doubly linked.T o realizea linked list as a heap,we imagine the usual array implementation of a binaryheap,where the children of the i th element are2i and2i+1.a.To insert,we perform a linear scan to see where to insert an element suchthat the list remains sorted.This takes linear time.The?rst element in thelist is the minimum element,and we can?nd it in constant time.Extract-minreturns the?rst element of the list,then deletes it.Union performs a mergeoperation between the two sorted lists,interleaving their entries such thatthe resulting list is sorted.This takes time linear in the sum of the lengthsof the two lists.b.To insert an element x into the heap,begin linearly scanning the list untilthe?rst instance of an element y which is strictly larger than x.If no suchlarger element exists,simply insert x at the end of the list.If y does exist,replace y t by x.This maintains the min-heap property because x≤y andy was smaller than each of its children,so x must be as well.Moreover,xis larger than its parent because y was the?rst element in the list to exceedx.Now insert y,starting the scan at the node following x.Since we checkeach node at most once,the time is linear in the size of the list.To get theminimum element,return the key of the head of the list in constant time.To extract the minimum element,we?rst call MINIM UM.Next,we’ll replacethe key of the head of the list by the key of the second smallest element yin the list.We’ll take the key stored at the end of the list and use it toreplace the key of y.Finally,we’ll delete the last element of the list,and callMIN-HEAPIFY on the list.T o implement this with linked lists,we need tostep through the list to get from element i to element2i.We omit this detailfrom the code,but we’ll consider it for runtime analysis.Since the value ofi on which MIN-HEAPIFY is called is always increasing and we never need11to step through elements multiple times,the runtime is linear in the length of the list.Algorithm20EXTRACT-MIN(L)min=MINIMUM(L)Linearly scan for the second smallest element,located in position i.L.head.key=L[i]L[i].key=L[L.length].keyDELETE(L,L[L.length])MIN-HEAPIFY(L[i],i)return minAlgorithm21MIN-HEAPIFY(L[i],i)1:l=L[2i].key2:r=L[2i+1].key3:p=L[i].key4:smallest=i5:if L[2i]=NIL and l6:smallest=2i7:end if8:if L[2i+1]=NIL and r<l[smallest]then< bdsfid="416" p=""></l[smallest]then<>9:smallest=2i+110:end if11:if smallest=i then12:exchange L[i]with L[smallest]13:MIN-HEAPIFY(L[smallest],smallest)14:end ifUnion is implemented below,where we assume A and B are the two list representations of heaps to be merged.The runtime is again linear in the lengths of the lists to be merged.c.Since the algorithms in part b didn’t depend on the elements being distinct,we can use the same ones.Problem10-3a.If the original version of the algorithm takes only t iterations,then,we havethat it was only at most t random skips though the list to get to the desired value,since each iteration of the original while loop is a possible random jump followed by a normal step through the linked list.b.The for loop on lines2-7will get run exactly t times,each of which is constantruntime.After that,the while loop on lines8-9will be run exactly X t times.So,the total runtime is O(t+E[X t]).12Algorithm22UNION(A,B)1:if A.head=NIL then2:return B3:end if4:i=15:x=A.head6:while B.head=NIL do7:if B.head.key≤x.key then8:Insert a node at the end of list B with key x.key9:x.key=B.head.key10:Delete(B,B.head)11:end if x=x.next12:end while13:return A/doc/8010751696.html,ing equation C.25,we have that E[X t]= ∞i=1P r(X t≥i).So,we needto show that P r(X t≥i)≤(1?i/n)t.This can be seen because having X t being greater than i means that each random choice will result in an element that is either at least i steps before the desired element,or is after the desired element.There are n?i such elements,out of the total n elements that we were pricking from.So,for a single one of the choices to be from such a range, we have a probability of(n?i)/n=(1?i/n).Since each of the selections was independent,the total probability that all of them were is(1?i/n)t, as /doc/8010751696.html,stly,we can note that since the linked list has length n,the probability that X t is greater than n is equal to zero.d.Since we have that t>0,we know that the function f(x)=x t is increasing,so,that means that x t≤f(x).So,n?1r=0r t=nr t dr≤nf(r)dr=e.E[X t]≤nr=1 (1?r/n)t= nr=1ti=0ti(?r/n)i= ti=0nr=1ti(?r/n)i =ti=0ti(?1)in i?1+ n?1r=0 (r)tti=0ti(?1)in i?1+n i+1/n ≤ti=0ti(?1)in ii+1=1t+1ti=0t+1i+1(?n)i≤(1?n)t+1t+1f.We just put together parts b and e to get that it runs in time O(t+n/(t+1)).But,this is the same as O(t+n/t).13g.Since we have that for any number of iterations t that the ?rst algorithm takes to ?nd its answer,the second algorithm will return it in time O (t +n/t ).In particular,if we just have that t =√n .The second algorithm takestime only O (√n ).This means that tihe ?rst list search algorithm is O (√n )as well.h.If we don’t have distinct key values,then,we may randomly select an element that is further along than we had been before,but not jump to it because it has the same key as what we were currently at.The analysis will break when we try to bound the probability that X t ≥i .14。

ch10图的基本概念

ch10图的基本概念

10.2 图与图模型
这样,一位教师如果给多个班级都授课,则在 讨论课时间安排方面则不能冲突,如教师1不能同 时参加班级c1与班级c2的讨论课。这种情况可以用 下图直观地表示。
c1 c2 c7 c6 c3 c4 c5
在上图中,共用了7个小圆圈来表示班级,圆 圈之间的线段表示存在同一个教师参加该二班级的 讨论课,这样就不能安排该二班级同时开展讨论课。 显然,这就给上述问题构建了一个直观的图的模型。
10.2 图与图模型
显然,子图或导出子图可以通过删除一
一个结点到第二个结点之间添加一条边。最后得到的图称为优先
图。下图就是一个优先图的例子。该图表明在执行语句S1、S2与 S4之前不能执行语句S5。
S1 S2 S3 S4 S5 S6 a=0 b=1 c=a+1 d=b+a e=d+1 e=c+d S1 S3 S2 S4
S6
S5
10.2 图与图模型
练习3 在晚会上有n个人,他们各自与自己相识的人 握一次手。已知每人与别人握手的次数都是奇数,
(3)指出与(v2,v3)邻接的边和与(v2,v3)关联的结点;
(4)该图是否有孤立结点和孤立边? ( 5 )求出各结点的度数,并判断是否是完全图和正 则图? (6)该(n,m)图中,n=?,m=?
10.2 图与图模型 图的边数与结点数的关系是图最为重要的属性, 结点的度数满足一个非常简单的关系,即图的每条
问n是奇数还是偶数。为什么?
解 n是偶数。用n个顶点表示n个人,顶点间的一条
边表示一次握手,可构成 一个无向图。若n是奇数,
那么该图的顶点度数之和为奇数个奇数的和,即为奇 数,与图性质矛盾,因此,n是偶数。
10.2 图与图模型 与集合论中研究子集,抽象代数中研究 子代数类似,图论中也研究一个图的子图。 一个图G的子图G′可以通过选取G中的部分 结点与边构成,但要求如果选择了G中的边,
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
相关文档
最新文档