有向图及重边
dfs 判环及输出
dfs 判断有无自环, 即在深度优先遍历时访问到一个已经访问过的点,同时满足访问点与当前点通过返祖边相连, 则会出现环
注:dfs 过程中会出现两种特殊边, 横插边、返祖边, 当且仅当出现返祖边时会出现环。
// determine whether the connected has a ring
// print the length of the ring
void dfs(int u) // when undiredted dfs(int u, int fa)
{
if (vis[u]) return;
st[++top] = u; // push in stack
in[u] = true; // mark in stack
vis[u] = true; // there are multiple connected blocks
for (int i = 0; i < e[u].size(); i ++) {
int &v = e[u][i];
if (!in[v]) {
dfs(v);
} else { // back side
int k;
for (k = top; st[k] != v; k --);
ans = min(top - k + 1, ans);
}
}
top --;
in[u] = false;
}