点—双连通分量:图中任意两个点之间至少存在两条点不重复的路径,则该图是双连通的;无向图的极大点—双连通子图称为双连通分量;
求解点双连通分量的过程其实就是找割点的过程:
建一个栈,储存当前的双连通分支,在搜索的过程中,每找到一条树边,就把边加入栈中。如果遇到某边的树枝边满足pre[u] <= low[v],说明u是一个割点。此时把边从栈顶中取出,直到遇到(u,v)边,取出的这些边与其相连的顶点组成一个点双连通分量。
注意:割点可以属于多个点双连通分量,其余点只能属于一个点双连通分量;每条边恰好属于一个点双连通分量;
点双连通分量算法:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<climits>
#include<cctype>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<stack>
#define ll long long
#define MAX 1010
#define MAXN 5000010
#define INF INT_MAX
#define eps 1e-6
#define REP(i,n) for (int i=0; i<(n); i++)
#define FOR(i,s,t) for (int i=(s); i<=(t); i++)
using namespace std;
struct Edge{
int u,v;
};
int pre[MAX],bccno[MAX],dfs_clock,bcc_cnt,iscut[MAX],n; //bccno记录节点属于哪个 点—双连通分支
vector<int>G[MAX],bcc[MAXN]; //bcc记录各个点双连通分支包含哪些点
stack<Edge>S;
vector<Edge>edges[MAX]; //记录各个连通分量包含那些边
void init(){
for (int i=0; i<=n; i++){
G[i].clear();
bcc[i].clear();
edges[i].clear();
}
while (!S.empty()) S.pop();
memset(pre,0,sizeof(pre));
memset(iscut,0,sizeof(iscut));
memset(bccno,0,sizeof(bccno));
dfs_clock = bcc_cnt = 0;
}
int dfs(int u,int fa){
int lowu = pre[u] = ++dfs_clock;
int child = 0;
for (int i=0; i<G[u].size(); i++){
int v = G[u][i];
Edge e = (Edge){u,v};
if (!pre[v]){
S.push(e);
child++;
int lowv = dfs(v,u);
lowu = min(lowv,lowu);
if (lowv >= pre[u]){
iscut[u] = true;
bcc_cnt++;
bcc[bcc_cnt].clear();
while (1){
Edge x = S.top();
edges[bcc_cnt].push_back(x);
S.pop();
if (bccno[x.u] != bcc_cnt) {
bccno[x.u] = bcc_cnt;
bcc[bcc_cnt].push_back(x.u);
}
if (bccno[x.v] != bcc_cnt) {
bccno[x.v] = bcc_cnt;
bcc[bcc_cnt].push_back(x.v);
}
if (x.u == u && x.v == v) break;
}
}
}
else if (pre[v] < pre[u] && v != fa){
S.push(e);
lowu = min(lowu,pre[v]);
}
}
if (fa<0 && child == 1) iscut[u] = 0;
return lowu;
}
void find_bcc(){
for (int i = 1; i<=n; i++){
if (!pre[i]) dfs(i,-1);
}
}
int main(){
int m;
while (scanf("%d%d",&n,&m) != EOF){
init();
int x,y;
for (int i=0; i<m; i++){
scanf("%d%d",&x,&y);
G[x].push_back(y);
G[y].push_back(x);
}
find_bcc();
for (int i=1; i<=bcc_cnt; i++){
for (int j = 0; j<bcc[i].size(); j++) printf("%d ",bcc[i][j]);
printf("\n");
for (int j=0; j<edges[i].size(); j++) printf("(%d , %d)\n",edges[i][j].u,edges[i][j].v);
}
}
return 0;
}