无向图 Tarjan
定义
- 割点(割顶):在无向图中,若删除点
x 及其连边,使得连通块变多,那么x 为割点(割顶)。 - 割边(桥):在无向图中,若删除一条边
e 后,使得连通块变多,那么x 为割边(桥)。 - 点双连通:若无向图点对
x,y ,删除任意非x 和非y 节点后,x 和y 仍然联通,则称x,y 点双连通。 - 边双连通:若无向图点对
x,y ,删除任意一条边后,x 和y 仍然联通,则称x,y 边双连通。 - 点双连通子图:无向图中的一个子图
G ,G 中任意两点都是点双连通的,那么称G 为点双连通子图。 - 边双连通子图:无向图中的一个子图
G ,G 中任意两点都是边双连通的,那么称G 为边双连通子图。 - 点双连通分量(V-DCC):无向图的极大点双连通子图成为点双连通分量。
- 边双连通分量(E-DCC):无向图的极大边双连通子图成为边双连通分量。
性质
- 无向图至少有
3 个点,才有可能有割点。 - 点双连通不具有传递性,边双连通具有传递性。
- dfs 搜索树中的根结点有
2 个及以上的子结点时,才可能是割点。 - 一个割点可能出现在多个点连通分量。
- 割边一定不在环上,环上的边必然不是割边。
判定
割点
- 维护
dfn_x 表示在一次 dfs 中点x 被遍历到的次序,称为时间戳。 - 维护
low_x 表示点x 在一次 dfs 中能够到达的最小时间戳。 - 当 dfs 中从
x 走向y ,且low_y\ge dfn_x 时,x 是割点。 - 此时
x 不应是 dfs 的根结点,如果是,x 应只有y 这一个子结点。
割边
- 维护
dfn_x 表示在一次 dfs 中点x 被遍历到的次序,称为时间戳。 - 维护
low_x 表示点x 在一次 dfs 中能够到达的最小时间戳。 - 当 dfs 中从
x 走向y ,且low_y>dfn_x 时,x\rightarrow y 是割边。 - 递归时,不可以走成对的反向边。
代码
查找所有割点
#include<bits/stdc++.h>
using namespace std;
int n,m;
vector <int> ve[20005];
int dfn[20005],tot;
int low[20005];
int cut[20005];
int cnt,root;
void Tarjan(int x){
dfn[x] = low[x] = ++tot;
int flag = 0;
for(int it : ve[x]){
if(!dfn[it]){
Tarjan(it);
low[x] = min(low[x],low[it]);
if(low[it] >= dfn[x]){
flag++;
if(x != root || flag >= 2) cut[x] = 1;
}
}
else low[x] = min(low[x],dfn[it]);
}
return;
}
int main(){
cin >> n >> m;
for(int i = 1;i <= m;i++){
int x,y;
cin >> x >> y;
if(x == y) continue;
ve[x].push_back(y);
ve[y].push_back(x);
}
for(int i = 1;i <= n;i++){
if(!dfn[i]){
root = i;
Tarjan(i);
}
}
for(int i = 1;i <= n;i++){
if(cut[i]) cnt++;
}
cout << cnt << "\n";
for(int i = 1;i <= n;i++){
if(cut[i]) cout << i << " ";
}
return 0;
}
查找所有点双连通分量
#include<bits/stdc++.h>
using namespace std;
const int NR = 5e5 + 5;
const int MR = 2e6 + 5;
int head[MR],ver[MR * 2],Next[MR * 2];
int dfn[NR],low[NR];
stack <int> st;
vector <int> vdcc[NR];
int dcc;
int n,m;
int tot = 1,num;
int root;
bool cut[NR];
void add(int x,int y){
ver[++tot] = y;
Next[tot] = head[x];
head[x] = tot;
}
void Tarjan(int x){
dfn[x] = low[x] = ++num;
st.push(x);
if(x == root && head[x] == 0){
vdcc[++dcc].push_back(x);
return;
}
int flag = 0;
for(int i = head[x];i;i = Next[i]){
int y = ver[i];
if(!dfn[y]){
Tarjan(y);
low[x] = min(low[x],low[y]);
if(low[y] >= dfn[x]){
flag++;
if(x != root || flag > 1) cut[x] = 1;
dcc++;
int tmp = 0;
while(tmp != y){
tmp = st.top();
st.pop();
vdcc[dcc].push_back(tmp);
}
vdcc[dcc].push_back(x);
}
}
else low[x] = min(low[x],dfn[y]);
}
}
int main(){
cin >> n >> m;
for(int i = 1;i <= m;i++){
int x,y;
cin >> x >> y;
if(x == y) continue;
add(x,y);
add(y,x);
}
for(int i = 1;i <= n;i++){
if(!dfn[i]){
root = i;
Tarjan(i);
}
}
cout << dcc << "\n";
for(int i = 1;i <= dcc;i++){
cout << vdcc[i].size() << " ";
for(int it : vdcc[i]) cout << it << " ";
cout << "\n";
}
return 0;
}
总结
Tarjan 是一个功能强大的算法,在后续的算法也有许多应用。
练习
P8435 【模板】点双连通分量
P3388 【模板】割点(割顶)
P1656 炸铁路