无向图的连通性

边双连通分量

#include<bits/stdc++.h>
using namespace std;
const int M=2e6+10,N=5e5+10;
int n,m;
struct EDGE{int to,next;}ee[M];
int head[N],ne=1,nm;
inline void ae(int from,int to) {ee[++ne]={to,head[from]}, head[from]=ne;}
inline void fred() {ios::sync_with_stdio(); cin.tie(0), cout.tie(0);}
int dfn[N],low[N],st[N],g[N],top,ans;
inline void dfs(int from,int e) {
	dfn[from]=low[from]=++nm;
	st[++top]=from;
	for(int i=head[from];i;i=ee[i].next) {
		int to = ee[i].to;
		if(!dfn[to]) {
			dfs(to,i);
			low[from]=min(low[from],low[to]);
			if(low[to]>dfn[from]) {
				g[i]=g[i^1]=1;
			}
		}
		else if(i!=(e^1)) low[from]=min(low[from],dfn[to]);
	}
	if(low[from]==dfn[from]) {
		ans++;
		int p;
		do {
			p=st[top--];
		} while(p^from);
	}
}
int main() {
	fred();
	cin>>n>>m;
	for(int i=1,x,y;i<=m;i++) {
		cin>>x>>y;
		ae(x,y), ae(y,x);
	}
	dfs(1,-1);
	cout<<ans;
	return 0;
}

点双连通分量

#include<bits/stdc++.h>
using namespace std;
inline void fred() {ios::sync_with_stdio(); cin.tie(0), cout.tie(0);}
const int M=2e6+10,N=5e5+10;
int n,m,nm;
int dfn[N],low[N],st[N],id[M<<1],top,ans,root;
vector<int>as[N],ee[N];
inline void dfs(int from) {
	dfn[from]=low[from]=++nm; st[++top]=from;
    if(from==root&&ee[from].empty()) {
        as[++ans].push_back(from);
        return ;
    }
	for(int to:ee[from]) {
		if(!dfn[to]) {
			dfs(to);
			low[from]=min(low[from],low[to]);
			if(low[to]>=dfn[from]) {
                ++ans; int p;
                do
					as[ans].push_back(p=st[top--]);
                while(p!=to);
				as[ans].push_back(from);
			}
		}
		else low[from]=min(low[from],dfn[to]);
	}
}
inline void print() {
	cout<<ans<<"\n";
	for(int i=1;i<=ans;i++) {
		cout<<as[i].size()<<" ";
		for(int j:as[i])
			cout<<j<<" ";
		cout<<"\n";
	}
}
int main() {
	fred();
	cin>>n>>m;
	for(int i=1,x,y;i<=m;i++) {
		cin>>x>>y;
        if(x!=y) ee[x].push_back(y), ee[y].push_back(x);
	}
	for(int i=1;i<=n;i++) if(!dfn[i]) root=i,dfs(i);
	print();
	return 0;
}

本文作者:cjrqwq

本文链接:https://www.cnblogs.com/yfzqwq/p/18492788

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   cjrqwq  阅读(5)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
展开
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.