连通性1 求无向图的low值

时间:2021-09-21 08:09:46

这是 DFS 系列的第一篇 。

首先给出一个重要的定理。该定理来自《算法导论》。

An undirected graph may entail some ambiguity in how we classify edges, since $(u,v)$ and $(v,u)$ are really the same edge. In such a case, we classify the edge according to whichever of $(u,v)$ or $(v,u)$ the search encounters first.

Introduction to Algorithm 3rd edition p.610

Theorem 22.10
In a depth-first search of an undirected graph $G$, every edge of $G$ is either a tree edge or a back edge.

Proof  Let $(u, v)$ be an arbitrary edge of $G$, and suppose without loss of generality that $u.d < v.d$. Then the search must discover and finish $v$ before it finishes $u$ (while $u$ is gray), since $v$ is on $u$’s adjacency list. If the first time that the search explores edge $(u, v)$, it is in the direction from $u$ to $v$, then $v$ is undiscovered (white) until that time, for otherwise the search would have explored this edge already in the direction from $v$ to $u$. Thus, $(u, v)$ becomes a tree edge. If the search explores $(u, v)$ first in the direction from $v$ to $u$, then $(u, v)$ is a back edge, since $u$ is still gray at the time the edge is first explored.

low 值大概是 Robert Tarjan 在论文 Depth-first search and linear graph algorithms  SIAM J. Comput. Vol. 1, No. 2, June 1972 给出的概念。

(p.150)"..., LOWPT(v) is the smallest vertex reachable from v by traversing zero or more tree arcs followed by at most one frond."

代码如下

 #define set0(a) memset(a, 0, sizeof(a))
typedef vector<int> vi;
vi G[MAX_N];
int ts; //time stamp
int dfn[MAX_N], low[MAX_N];
void dfs(int u, int f){
dfn[u]=low[u]=++ts;
for(int i=; i<G[u].size(); i++){
int &v=G[u][i];
if(!dfn[v]){ //tree edge
dfs(v, u);
low[u]=min(low[u], low[v]);
}
else if(dfn[v]<dfn[u]&&v!=f){ //back edge
low[u]=min(low[u], dfn[v]);
}
}
}
void solve(int N){
set0(dfn);
ts=;
for(int i=; i<=N; i++)
if(!dfn[i]) dfs(i, i);
}