有向图

Topological Sort

Topological sort. Redraw DAG so all edges point upwards (or to the same direction).

What it means by "Redraw"

拓扑序是这样一个序列:对 DAG 上的每一条有向边 u→vu \to v,拓扑序中 uu 都必定在 vv 之前出现。如果文明 6 中的科技树是一个 DAG,那么其拓扑序就是一种可能的点科技树的顺序。

Kahn's Algorithm

一个很经典的求拓扑序的算法是 Kahn 算法:

  • 初始将所有 indegree 为 0 的 vertices 加入队列。
  • 当队列非空时,弹出 vertice vv。
  • 在 DAG 中删除 vv 与以 vv 为起点的有向边。实现上我们仅需维护 indegree 数组:对于每一条有向边 v→wv \to w,删除 vv 意味着 ww 的 indegree 减一。若更新后 ww 的 indegree 为 0,则把 ww 加入队列。
  • 重复上述步骤直至队列为空。

从队列中弹出的 vertices 的顺序即为一种可能的拓扑序。

Kahn 算法的理解非常的 intuitive;其本身就是一个 trivial 的拓扑排序过程。

Depth-First Search Approach

Proposition. Reverse DFS postorder of a DAG is a topological order.

In postorder, a vertice is marked only when its subvertices are marked.

这个结论异常的简单且优美,仔细想一想也是很符合直觉的。证明如下:考虑任意有向边 v→wv \to w,当 dfs(v) 被调用时,分别有三种情况:

  • Case 1: dfs(w) has already been called and returned. Thus ww was done before vv.
  • Case 2: dfs(w) has not yet been called. Then dfs(w) will get called directly or indirecely by dfs(v) and will finish before dfs(v). Thus ww will be done before vv.
  • Case 3: dfs(w) has already been called but has not yet returned. This cannot happen in a DAG.

因此,在 DAG 的 postorder 中,一条有向边 v→wv \to w 能够保证 ww 在 vv 之前;因此在 reverse postorder 中 ww 一定在 vv 之后。这正好符合 topological order 的定义。

java
public class DepthFirstOrder {
    private boolean[] marked;
    private ArrayList<Integer> postorder;
    
    public DepthFirstOrder(Digraph G) {
        postorder = new ArrayList<Integer>();
        marked = new boolean[G.V()];
        for (int v = 0; v < G.V(); ++v)
            if (!marked[v])	dfs(G, v);
    }
    public void dfs(Digraph G, int v) {
        marked[v] = true;
        for (int w : G.adj(v))
            if (!marked[w])	dfs(G, w);
        postorder.add(v);
    }
    public Iterable<Integer> reversePost() {
        Collections.reverse(postorder);
        return postorder;
    }
}

Directed Cycle Detection

Proposition. A diagraph has a topological order iff no directed cycle.

很好理解,只有 DAG 有拓扑序;若使用 dfs 对有环图求拓扑序将进入死循环。

关于判环,有一个优美的算法:将每个节点染成白,灰,黑三种颜色。白色节点是还未入 dfs 栈的节点,灰色节点是当前 dfs 栈中的节点,黑色节点是已经弹出 dfs 栈的节点。

java
public DepthFirstOrder(Digraph G) {
    marked = new int[G.V()];	// 0 for white, 1 for grey, 2 for black
    hasCycle = false;
    ...
}
private void dfs(Digraph G, int v) {
    marked[v] = 1;
    for (int w : G.adj(v)) {
        if (marked[w] == 0)	dfs(G, w);
        if (marked[w] == 1)	hasCycle = true;
    }
    marked[v] = 2;
}

关于判环还有许多其他的应用:precedence scheduling,Java compiler 中的 cyclic inheritance 判断与 Excel 中的 spreadsheet recalculation。

Strong Components

Strongly Connected. Vertices vv and ww are strongly connected if there is both a directed path from vv to ww and a directed path from ww to vv.

强连通关系具有以下性质:

  • Reflexivity. vv is strongly connected to vv.
  • Symmetry. If vv is strongly connected to ww, then ww is strongly connected to vv.
  • Transitivity. If vv is strongly connected to ww and ww to xx, then vv is strongly connected to xx.

这三个性质决定了 strong component (强连通分量) 的定义。

Def. A strong component is a maximal subset of strongly-connected vertices.

接下来我们来介绍 Kosaraju-Sharir 算法:其通过对 DAG GG 的两次 DFS 求出其所有的 strong components。具体来说,该算法将计算出一个数组 id,属于同一个 strong components 的节点具有相同的 id。

  • Phase 1: run DFS on GRG^R to compute reverse postorder.
  • Phase 2: run DFS on GG, considering vertices in order given by first DFS.

GRG^R 是图 GG 的 reverse graph (反向图):其通过反转 GG 中的所有有向边生成。利用 Strong components in GG are the same as in GRG^R 这一性质,我们得到了对 kernal DAG of GG 的一种染色顺序。

Kernal DAG. Contract each strong component into a single vertex. (Tarjan 缩点)

如图,按照逆拓扑序对 kernal DAG of GG 进行染色能够保证 strong components 之间的颜色不会相互干扰;而 GG 的逆拓扑序就是 GRG^R 的拓扑序,即 GRG^R 的 reverse postorder。附上知乎上的这个回答,讲的很精辟。

java
public class KosarajuSharirSCC {
    private boolean marked[];
    private int[] id;
    private int count;
    
    public KosarajuSharirSCC(Digraph G) {
        marked = new boolean[G.V()];
        id = new int[G.V()];
        DepthFirstOrder dfs = new DepthFirstOrder(G.reverse());
        for (int v : dfs.reversePost()) {
            if (!marked[v]) {
                dfs(G, v);
                count++;
            }
        }
    }
    private void dfs(Digraph G, int v) {
        marked[v] = true;
        id[v] = count;
        for (int w : G.adj(v))
            if (!marked[w])	dfs(G, w);
    }
    
    public boolean stronglyConnected(int v, int w) { return id[v] == id[w]; }
}
CC BY-NC-SA 4.0
正在加载评论…