algorithms-ch3-Decompositions of graphs

3.1 Graphs

Represent a graph by

  • Adjacency matrix -- sparse graph


    n = |V | vertices v1, . . . , vn, this is an n × n array whose (i, j)th entry is aij

    (For undirected graphs, the matrix is symmetric since an edge {u,v} can be taken in either direction.)

  • Adjacency list -- dense graph

3.2 DFS -- O(n)

3.2.1Pseudocode

Find all nodes reachable from a particular code

procedure explore(G,v)
Input: G = (V,E) is a graph, v ∈ V
Output: visited(u) is set to true for all nodes u reachable from v

visited(v) = true
previsit(v)    // first time we visit v
for each edge(u,v)∈E;
  if not visited(u): explore(u)
postvisit(v)    // last time we visit v, since all node reachable from v have been visted

procedure dfs(G)
for all  v ∈ V:
  visited(v) = false
for all  v ∈ V:
  if not visisited(v): explore(v)

procedure previsit(v)
pre[v] = clock
clock = clock + 1

procedure postvisit(v)
post[v] = clock
clock = clock + 1

又用了递归的方法,把图转成树更容易理解

Algorithm analysis: procedure explore explore each edge once(|E|), procedure dfs check each vertex once(|V|),so the time complexity: O(|V| + |E|)

3.2.3Connectivity in undirected graphs

可以在previsit()里加一个计数器,每遍历一次source,计数器加1,表示有几个cc

Property For any nodes u and v, the two intervals [pre(u), post(u)] and [pre(v), post(v)] are either disjoint or one is contained within the other.

pre/post

3.3 directed graph

For undirected graphs we distinguished between tree edges and nontree edges. In the directed case, there is a slightly more elaborate taxonomy:

  • Tree edges are actually part of the DFS forest.
  • Forward edges lead from a node to a nonchild descendant
    in the DFS tree.
  • Back edges lead to an ancestor in the DFS tree.
  • Cross edges lead to neither descendant nor ancestor; they therefore lead to a node that has already been completely explored (that is, already postvisited).
edges
3.3.2Directed acyclic graphs

A graph without cycles is acyclic
(类比tree:undirected connected graph without cycles)

Property A: directed graph has a cycle if and only if its depth-first search reveals a backedge.

All DAGs can be linearized.
两种方法线性化:

  1. DFS;: simply perform tasks in decreasing order of their postnumbers. After all, the only edges (u, v) in a graph for which post(u) <post(v) are backedges

Property: In a dag, every edge leads to a vertex with a lower post number.

  1. 找到source,输出并从图中删除; 直到图空
    the vertex with the smallest postnumber comes last in this linearization, and it must be a sink—no outgoing edges.
    Symmetrically, the one with the highest post is a source, a node with no incoming edges.

Property: Every dag has at least one source and at least one sink. ( remove a source or sink, still a DAG)

3.4 SCC(Strongly connected components)

  • Undirected graph
    DFS--trees in the forest = connected component
  • Directed graph:
    Two nodes u and v of a directed graph are connected if there is a path from u to v and a path from v to u.
    This relation partitions V into disjoint sets that we call **strongly connected components. **

Every directed graph is a dag of its strongly connected components. (acyclic graph can be linearized)

和DFS结合的相关性质

Property 1 : If the explore subroutine is started at node u, then it will terminate precisely when all nodes reachable from u have been visited.

Property 2 : The node that receives the highest post number in a depth-first search must liein a source strongly connected component.

Property 3 : If C and C′ are strongly connected components, and there is an edge from a node

The resulting algorithm is this.

  1. Run depth-first search on GR.
  2. Run the undirected connected components algorithm (from Section 3.2.3) on G, and during the depth-first search, process the vertices in decreasing order of their post numbers from step 1.

找出有向图的强连通分量:

  1. 在G reverse上dfs,
  2. 找到最大的postvisit()删除能够遍历到的点,这些点构成一个强连通分量
  3. 如果还有顶点没有被删除,回到3,否则结束

补充一个点,CLRS上的

拓扑排序算法:
topological sort(G)

  1. call DFS(G) to compute finishing time postvisit(v) for each vertex v
  2. as each vertex is finish, insert it onto the front of a linked list
  3. return the linked list of vertices

Time complexity:T(n) = Θ(V+E)
dfs复杂度为V+E ,插入链表 O(1)

exercise

这章exercise 1-13都值得看一下,28,31 是很重要的两个问题
画图的不写了,随便挑几道放上来供玩赏┑( ̄Д  ̄)┍

3.5 The reverse of a directed graph G = (V,E) is another directed graph GR = (V,ER) on the same vertex set, but with all edges reversed; that is, ER = {(v, u) : (u, v) ∈ E}.Give a linear-time algorithm for computing the reverse of a graph in adjacency list format.(GR,ER R为上标)
sol

function find-reverse(G)
Input: Graph G = (V,E) in adjacency list
Output G reverse


 for each edge (v, u) ∈ E
   do reverse (v, u) to get (u, v)

Algorithm analysis

  • (i) The algorithm terminates because it considers each edge once
  • (ii) The algorithm is correct because it reverses each edge. Thus, we have the new
    graph GR = (V, ER) where V is the original vertex set and E
    R is the set of
    reversed edges
  • (iii) The algorithm runs in time O (m) because it does a constant amount of work
    for each of the O (m) edges. We simply look at each element of the edge list in
    our adjacency list representation and swap the vertices.

3.6 In an undirected graph, the degree d(u) of a vertex u is the number of neighbors u has, or equivalently, the number of edges incident upon it. In a directed graph, we distinguish between the indegree din(u), which is the number of edges into u, and the outdegree dout(u), the number of edges leaving u.
a. Show that in an undirected graph,

Paste_Image.png

b. Use part (a) to show that in an undirected graph, there must be an even number of vertices whose degree is odd.
c. Does a similar statement hold for the number of vertices with odd indegree in a directed graph?
sol

(a)this formula states that for an undirected graph if we sum all the degrees of each vertex, then this will equal 2 times the number of edges.
Since each edge must start at a vertex and end at a vertex, we see that for each edge that we add to the graph we are increasing the total sum of degrees by 2 for an undirected graph, thus the formula is correct

(b) This also makes sense since the total sum of degrees in an undirected graph must be an even number, if there were an odd number of vertices whose degree were odd, then the total degrees for the graph would be odd which violates the equality stated above

(c) No, the indegree and outdegree both can not be determined in directed graph

3.7 A bipartite graph is a graph G = (V,E) whose vertices can be partitioned into two sets (V = V1 U V2) and V1 int V2 = 0 such that there are no edges between vertices in the same set (for instance, if u, v is an element of V1, then there is no edge between u and v).

(a) Give a linear-time algorithm to determine whether an undirected graph is bipartite.

(b) There are many other ways to formulate this property. For instance, an undirected graph is bipartite if and only if it can be colored with just two colors.Prove the following formulation: an undirected graph is bipartite if and only if it contains no cycles of odd length.

(c) At most how many colors are needed to color in an undirected graph with exactly one odd-length cycle?
sol

(a) Perform a DFS on the undirected graph. The root node will belong to the set V1, once we visit a node we will mark it set V2, if its parent is V1, or set V1 if its parent is V2. When we visit a node we will look at its neighbors to determine if any of the sets are equal to the current node, if they are then this is not a bipartite graph, otherwise, if the graph is strongly connected then it is a bipartite graph
用b中的coloring角度来看

function graph-coloring(g)
Input: Graph G
Output: if the graph is bipartite, return true, otherwise, return false

//initialize
for all v∈V
  visited(v) = false
  color(v) = GREY

while ∃s ∈ V && visit(s) = false
  visited(s) = true
  color(s) = WHITE
  S = [s] //Stack S contains vertices
  while S is not empty
    u = pop(S)
    for all edges (u,v) ∈ E:
      if visited(v) = false:
        visited[v] = true
        push(S,v)

      if color(v) = GREY
//it has not been visited, set color
        if color(u) = BLACK:
          color(v) = WHITE
        if color(u) = WHITE:
          color(v) = BLACK
      else if color(v) = WHITE:
//if has been visited, compare color
        if color(u) != BLACK:
          return false
       else if color(v) = BLACK:
         if color(u) != WHITE:
            return false
return true

(b)An undirected graph is bipartite if and only if it contains no cyles of
odd length
Proof: (这个过程写出来及其麻烦,其实只要画个图简要说明一下应该就可以:根据上面的算法可以知道,一个图为二分的一个充要条件是对于每条 non-treeedge (u,v),有顶点u,v的颜色不相同,也即是在DFS树上顶点u,v要间隔奇数层。而环的长度为间隔层数加 1,为偶数。于是得证)

⇒Consider a path P whose start vertex is s, end vertex is t and it passes
through vertices u1, u2, ..., un and the associated edges are (s, u1),(u1, u2), ...,(un, t).
Now if P is a cycle, then s and t are the same vertices. Without loss of generality
assume s is in V1. Each edge (ui
, ui+1) goes from one vertex set to other.
Therefore a path must have 2·i edges to come back into the same vertex set
where i ∈ N. Since s and t are in same vertex set, so the length of the cycle
formed must be 2·i which is even.
⇐Suppose the graph has a cycle of odd length. Let the cycle be C and it passes through vertices u1, u2, ..., un where u1 = un. The associated edges are
(u1, u2), ...,(un−1, un). We start coloring edges of using two colors WHITE and
BLACK. Without any loss of generality u1 is colored WHITE while un−1 is
colored BLACK since n is odd and therefore n − 1 is even. Choosing color of
un as WHITE conflicts with the color of un−1 while choosing color as BLACK
conflicts with the color of u1. Therefore it is not possible to color an odd cycle
with 2 colors which implies that the graph is not bipartite

(c)3

3.13. Undirected vs. directed connectivity.
(a) Prove that in any connected undirected graph G = (V,E) there is a vertex v ∈ V whose
removal leaves G connected. (Hint: Consider the DFS search tree for G.)
sol

Consider the DFS tree at any vertex, if we remove a leaf(v) from this tree, we still get a tree which is a subgraph of the graph obtained by remaining v. Hence the graph remain connected.
(虽然这个证明确实很简单, 注意是conected undirect graph就可以了,但是个人觉得这个证明答案跟没说一样,其实大部分证明都这画风的)
加一个详细的解释

Paste_Image.png

CLRS上配套exercise
22.3-7 Rewrite the procedure DFS, using a stack to eliminate recursion.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,393评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,790评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,391评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,703评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,613评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,003评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,507评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,158评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,300评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,256评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,274评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,984评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,569评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,662评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,899评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,268评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,840评论 2 339

推荐阅读更多精彩内容

  • 怎么才能提高自己看待事物、看待问题的层次,从一群人里脱颖而出? 答案是升级认知。前段时期的学习过程中,几位前辈、师...
    李赫先生的昵称阅读 373评论 0 0
  • 喜欢行走,喜欢漫无目的地走在路上的那种感觉。 无边旷野,阡陌纵横。斜斜的山坡上开满了粉红浅紫的小花。有风吹来,卷起...
    对花情味阅读 553评论 2 5
  • 小马哥某天看到他爹的爹拿养老金回来,不禁自问,我老了能拿多少呢? 掐指一算,小马哥现在每月5000元,那么退休后,...
    谁谁谁漫画阅读 1,159评论 2 6
  • #C姑娘在高中的时候谈了个对象,后来毕业就分了。大一有个舍友热情得很,开学没几天就说要给C姑娘牵红线。C姑娘二话不...
    陈陈陈姑娘阅读 233评论 0 0
  • 我来到你的脚下, 你却沉默不语 我就安静地等候, 像黑夜在星空下无眠。 当黎明到来,夜晚隐匿, 你的声音划破天际如...
    王泽然思想星空阅读 197评论 2 1