C++#include <bits/stdc++.h>
using namespace std;
#define int long long
constexpr int maxn=1e4+10;
constexpr int maxm=1e5+10;
int n,m;
typedef struct edge
{
int to,next;
edge()=default;
edge(int a,int b):to(a),next(b){}
}edge;
edge edges[maxm];
int heads[maxn];
int enums;
void add_edge(int x,int y)
{
edges[++enums]={y,heads[x]};
heads[x]=enums;
}
int dfn[maxn],low[maxn];
int stk[maxn],instk[maxn];
int time_cnt;
int sc_heads[maxn],scct[maxn];
vector<int>scc[maxn];
void tarjan(int x)
{
++time_cnt;
stk[++stk[0]]=x;
instk[x]=1;
dfn[x]=low[x]=time_cnt;
for(int i=heads[x];i;i=edges[i].next)
{
int to=edges[i].to;
if(!dfn[to])
{
tarjan(to);
low[x]=min(low[x],low[to]);
}
else
{
if(instk[to])
{
low[x]=min(low[x],dfn[to]);
}
}
}//递归
if(dfn[x]==low[x])
{
sc_heads[++sc_heads[0]]=x;
while(stk[stk[0]]!=x)
{
scc[x].emplace_back(stk[stk[0]]);
instk[stk[stk[0]]]=0;
scct[stk[stk[0]]]=x;
--stk[0];
}
scc[x].emplace_back(x);
instk[x]=0;
scct[x]=x;
--stk[0];
}
}
signed main()
{
scanf("%lld%lld",&n,&m);
for(int i=1,u,v;i<=m;++i)
{
scanf("%lld%lld",&u,&v);
add_edge(u,v);
}
for(int i=1;i<=n;++i)
{
if(!dfn[i])
{
tarjan(i);
}
}
printf("%lld\n",sc_heads[0]);
for(int i=1;i<=n;++i)
{
if(dfn[i]==0)
{
continue;
}
sort(scc[scct[i]].begin(),scc[scct[i]].end());
for(int element:scc[scct[i]])
{
printf("%lld ",element);
dfn[element]=0;
}
printf("\n");
}
return 0;
}
https://www.luogu.com.cn/problem/B3609