【模板】点双连通分量

题目跳转

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
uint8_t buf[1<<20],*p1,*p2;
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
ll rd(){
	ll x=0,f=1,ch=gc();
	while(ch<'0'||ch>'9'){
		if(ch=='-'){
            f=-1;
        }
        ch=gc();
	}
	while(ch>='0'&&ch<='9'){
		x=(x<<1)+(x<<3)+(ch-'0');
		ch=gc();
	}
	return x*f;
}
void write(ll x){
	if(x<0){
		x=-x;
		putchar('-');
	}
	if(x>9){
		write(x/10);
	}
	putchar(x%10+'0');
}
const ll maxn1=5e5+5,maxn2=2e6+5;
ll n,m,rt,cnt=1,num,tot,head[maxn1],dfn[maxn1],low[maxn1],fa[maxn1];
stack<ll> stk;
struct node{
	ll to,nxt;
}e[maxn2<<1];
void add(ll u,ll v){
	if(u!=v){
		e[++cnt].nxt=head[u];
		head[u]=cnt;
		e[cnt].to=v;
	}
}
vector<ll> scc[maxn1];
void dfs(ll x){
	low[x]=dfn[x]=++tot;
	stk.push(x);
	if(x==rt&&head[x]==0){
		scc[++num].push_back(x);
		return;
	}
	for(ll i=head[x];i;i=e[i].nxt){
		if(i!=(fa[x]^1)){
			ll y=e[i].to;
			if(!dfn[y]){
				fa[y]=i;
				dfs(y);
				low[x]=min(low[x],low[y]);
				if(dfn[x]<=low[y]){
					num++;
					ll j;
					do{
						j=stk.top();
						stk.pop();
						scc[num].push_back(j);
					}while(j!=y);
					scc[num].push_back(x);
				}
			}else{
				low[x]=min(low[x],dfn[y]);
			}
		}
	}
}
int main(){
	n=rd();
    m=rd();
	for(ll i=1;i<=m;i++){
		ll u=rd(),v=rd();
		add(u,v);
		add(v,u);
	}
	for(ll i=1;i<=n;i++){
		if(!dfn[i]){
			rt=i;
			dfs(i);
		}
	}
	write(num);
    putchar('\n');
	for(ll i=1;i<=num;i++){
		write(scc[i].size());
        putchar(' ');
		for(auto j:scc[i]){
			write(j);
            putchar(' ');
		}
		putchar('\n');
	}
	return 0;
}
posted @ 2026-11-09 11:14  beiciqi  阅读(6)  评论(0)    收藏  举报