概念
-
强连通:若一张有向图的节点两两互相可达,则称这张图是强连通的
-
强连通分量(Strongly Connected Components, SCC):极大的强连通子图。如图中的1, 2, 3, 4, 9和5, 6, 8和7
-
对图深搜时,每一个节点只访问一次,被访问过的节点与边构成搜索树
-
有向边按访问情况分4类:
- 树边:访问节点走过的边(黑色边)
- 返祖边:指向祖先节点的边(红色边)
- 横叉边:右子树指向左子树的边(绿色边)
- 前向边:指向子树中节点的边(蓝色边)
-
返祖边和树边必定构成环,横叉边可能和树边构成环,前向边无用(必定存在一条等长或更长的路径代替前向边)。
-
如果节点x是某个强连通分量在搜索树中遇到的第一个节点,那么这个强连通分量的其余节点肯定是在搜索树中以x为根的子树中,节点x被称为这个强连通分量的根。
算法流程
-
时间戳dfn[x]:节点x第一次被访问的顺序
-
追溯值low[x]:从节点x出发,所能访问到的最早时间戳
-
入x时,盖戳,入栈
-
枚举x的邻点y
- 若y尚未访问:递归访问,回溯到x时,用low[y]更新low[x],因为x是y的父节点,y能访问到x也一定能访问到
- 若y已访问且在栈中:说明y是祖先节点或左子树节点,用dfn[y]更新low[x]
- 若y已访问且不在栈中:说明y已搜索完毕,其强连通分量已处理完毕
-
离x时,记录SCC,只有遍历完一个SCC才可以出栈,更新low[x]的意义:避免SCC节点提前出栈
![image-20220616132752297](https://zh-typora.oss-cn-guangzhou.aliyuncs.com/typora-img/image-20220616132752297.png)
![image-20220616134300232](https://zh-typora.oss-cn-guangzhou.aliyuncs.com/typora-img/image-20220616134300232.png)
例题 [USACO06JAN]The Cow Prom S
题目描述
有一个 n n n 个点, m m m 条边的有向图,请求出这个图点数大于 1 1 1 的强联通分量个数。
输入格式
第一行为两个整数 n n n 和 m m m。
第二行至 m + 1 m+1 m+1 行,每一行有两个整数 a a a 和 b b b,表示有一条从 a a a 到 b b b 的有向边。
输出格式
仅一行,表示点数大于 1 1 1 的强联通分量个数。
样例 #1
样例输入 #1
5 4
2 4
3 5
1 2
4 1
样例输出 #1
1
提示
数据规模与约定
对于全部的测试点,保证 2 ≤ n ≤ 1 0 4 2\le n \le 10^4 2≤n≤104, 2 ≤ m ≤ 5 × 1 0 4 2\le m\le 5\times 10^4 2≤m≤5×104, 1 ≤ a , b ≤ n 1 \leq a, b \leq n 1≤a,b≤n。
代码
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<algorithm>
#include<set>
#include<stack>
#include<map>
#include<cstring>
using namespace std;
const int N = 1e5 + 5, M = 1e5 + 5;
int head[N], e[M], edge[M], idx;
int scc[N], dfn[N], low[N], instk[N], siz[N], tot, cnt;
int ans;
stack<int> stk;
void add(int u, int v) {
e[idx] = v;
edge[idx] = head[u];
head[u] = idx++;
}
void tarjan(int x) {
dfn[x] = low[x] = tot++;
stk.push(x), instk[x] = 1;
for (int i = head[x]; i != -1; i = edge[i]) {
if (!dfn[e[i]]) {
tarjan(e[i]);
low[x] = min(low[x], low[e[i]]);
}
else if (instk[e[i]]) {
low[x] = min(low[x], dfn[e[i]]);
}
}
if (dfn[x] == low[x]) {
int t;
++cnt;
do {
t = stk.top(); stk.pop();
instk[t] = 0;
scc[t] = cnt;
++siz[cnt];
} while (t != x);
if (siz[cnt] > 1) ++ans;
}
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
memset(head, -1, sizeof(head));
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
add(u, v);
}
for (int i = 1; i <= n; i++) {
if (!dfn[i]) {
tarjan(i);
}
}
cout << ans;
return 0;
}