yangjunhan1 @ 2023-09-03 17:09:18
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+10,M=2e6+10;
int n,m,lt[N],head[N],tot,dfn[N],hs[N],sz[N],T,z[N],top,cnt,prin[5000][5000],k[5000];
bool zg[N];
struct bian{
int to,ne;
}e[M<<1];
void add(int u,int v){
e[++tot]={v,head[u]};
head[u]=tot;
}
void dfs(int u,int a){
hs[u]=dfn[u]=++T;
z[++top]=u;
zg[u]=1;
for(int i=head[u];~i;i=e[i].ne){
int v=e[i].to;
if(!dfn[v]){
dfs(v,i);
hs[u]=min(hs[u],hs[v]);
}
else if(i!=(a^1)) hs[u]=min(hs[u],dfn[v]);
}
if(hs[u]==dfn[u]){
cnt++;
while(z[top]!=u){
zg[z[top]]=0;
sz[cnt]++;
lt[z[top]]=cnt;
prin[cnt][k[cnt]++]=z[top--];
}
zg[u]=0;
sz[cnt]++;
lt[u]=cnt;
prin[cnt][k[cnt]++]=u;
top--;
}
}
int main(){
memset(head,-1,sizeof head);
cin>>n>>m;
while(m--){
int u,v;
cin>>u>>v;
if(u==v) continue;
add(u,v);
add(v,u);
}
for(int i=1;i<=n;i++)
if(!dfn[i]) dfs(i,-1);
cout<<cnt<<endl;
for(int i=1;i<=cnt;i++){
for(int j=0;j<k[cnt];j++)
cout<<prin[i][j]<<" ";
cout<<endl;
}
return 0;
}
by yangjunhan1 @ 2023-09-05 17:17:48
new
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+10,M=2e6+10;
int n,m,lt[N],head[N],tot,dfn[N],hs[N],sz[N],T,z[N],top,cnt,prin[5000][5000],k[5000];
bool zg[N];
struct bian{
int to,ne;
}e[M<<1];
void add(int u,int v){
e[++tot]={v,head[u]};
head[u]=tot;
}
void dfs(int u,int a){
hs[u]=dfn[u]=++T;
z[++top]=u;
zg[u]=1;
for(int i=head[u];~i;i=e[i].ne){
int v=e[i].to;
if(!dfn[v]){
dfs(v,i);
hs[u]=min(hs[u],hs[v]);
}
else if(i!=(a^1)) hs[u]=min(hs[u],dfn[v]);
}
if(hs[u]==dfn[u]){
cnt++;
while(z[top]!=u){
zg[z[top]]=0;
sz[cnt]++;
lt[z[top]]=cnt;
prin[cnt][k[cnt]++]=z[top--];
}
zg[u]=0;
sz[cnt]++;
lt[u]=cnt;
prin[cnt][k[cnt]++]=u;
top--;
}
}
int main(){
memset(head,-1,sizeof head);
cin>>n>>m;
while(m--){
int u,v;
cin>>u>>v;
if(u==v) continue;
add(u,v);
add(v,u);
}
for(int i=1;i<=n;i++)
if(!dfn[i]) dfs(i,0);
cout<<cnt<<endl;
for(int i=1;i<=cnt;i++){
cout<<k[cnt]<<" ";
for(int j=0;j<k[cnt];j++)
cout<<prin[i][j]<<" ";
cout<<endl;
}
return 0;
}