Tarjan vDCC 缩点

概念

若一张无向连通图不存在割点,则称它为“点双连通图”。无向图的极大点双连通子图被称为“点双连通分量”。

tarjan算法求vDCC

用一个栈存点,若遍历回到x时,发现割点判定法则low[y]>=dfn[x]成立,则从栈中弹出节点,直到y被弹出。
刚才弹出的节点和x一起构成一个vDCC。

vDCC->缩点

将所有点双连通分量都缩成点,把缩点和对应的割点连边,构成一颗树(或森林),

code:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
vector<int> e[N],ne[N];
int dfn[N],low[N],tot,n,m;
stack<int> stk;
vector<int> dcc[N];
int cut[N],root,cnt,num,id[N];
void tarjan(int x){
    dfn[x]=low[x]=++tot;
    stk.push(x);
    if(!e[x].size()){//孤立点
        dcc[++cnt].push_back(x);
        return;
    }
    int child=0;
    for(int y:e[x]){
        if(!dfn[y]){//若y尚未访问
            tarjan(y);
            low[x]=min(low[x],low[y]);
            if(low[y]>=dfn[x]){
                child++;
                if(x!=root||child>1)
                    cut[x]=true;
                cnt++;
                int z;
                do{//记录vDCC
                    z=stk.top();stk.pop();
                    dcc[cnt].push_back(z);
                }while(z!=y);
                dcc[cnt].push_back(x);
            }
        }
        else{//若y已经访问
            low[x]=min(low[x],dfn[y]);
        }
    }
}
int main(){
    cin.tie(nullptr)->sync_with_stdio(false);
    cin>>n>>m;
    while(m--){
        int a,b;
        cin>>a>>b;
        e[a].push_back(b);
        e[b].push_back(a);
    }
    for(root=1;root<=n;root++){
        if(!dfn[root])
            tarjan(root);
    }
    //给每个割点一个新编号(cnt+1开始)
    num=cnt;
    for(int i=1;i<=n;i++){
        if(cut[i])
            id[i]=++num;
    }
    //建新图,从每个vDCC向对应割点连边
    for(int i=1;i<=cnt;i++){
        for(int j=0;j<dcc[i].size();j++){
            int x=dcc[i][j];
            if(cut[x]){
                ne[i].push_back(id[x]);
                ne[id[x]].push_back(i);
            }
        }
    }
    return 0;
}
posted @ 2025-09-12 20:35  xdhking  阅读(6)  评论(0)    收藏  举报