刚学双连通分量,求条
查看原帖
刚学双连通分量,求条
1065071
Atserckcn楼主2024/8/8 22:24
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+5,M=2e6+5;
int n,m,u,v;
int head[N],cnt_e,low[N],dfn[N],Index;
vector<vector<int> > ans;
stack<int> st;
struct E{
	int from,to,pre;
}e[M<<1];
void add(int from,int to)
{
	e[++cnt_e].from=from;
	e[cnt_e].to=to;
	e[cnt_e].pre=head[from];
	head[from]=cnt_e;
	return;
}
void dfs(int u,int fa)
{
	low[u]=dfn[u]=++Index;
	st.push(u);
	for(int i=head[u];i;i=e[i].pre)
	{
		int v=e[i].to;
		if(v==fa) continue;
		if(!dfn[v])
		{
			dfs(v,u);
			low[u]=min(low[u],low[v]);
		}
		else
			low[u]=min(low[u],dfn[v]);
	}
	if(low[u]==dfn[u])
	{
		int t;
		vector<int> ve;
		ve.clear();
		do{
			t=st.top();st.pop();
			ve.push_back(t);
		}while(t!=u);
		ans.push_back(ve);
	}
	return;
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++)
	{
		scanf("%d%d",&u,&v);
		add(u,v);
		add(v,u);
	}
	for(int i=1;i<=n;i++)
		if(!dfn[i])
			dfs(i,0);
	printf("%d\n",ans.size());
	for(auto i:ans)
	{
		printf("%d ",i.size());
		for(auto j:i)
			printf("%d ",j);
		putchar('\n');
	}
	return 0; 
}

https://www.luogu.com.cn/record/171486803

2024/8/8 22:24
加载中...