模板——Tarjan

时间:2022-10-30 13:45:53
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
const int maxn=;
vector<int>tu[maxn];
vector<int>lt[maxn];
int n,m,lts=;
int js=;
int dfn[maxn],low[maxn];
int zhan[maxn],top=;
bool isins[maxn];
void tarjan(int i)
{
int j;
dfn[i]=low[i]=++js;
isins[i]=;
zhan[top++]=i;
for(int j=;j<tu[i].size();j++)
{
int tp=tu[i][j];
if(dfn[tp]==-)
tarjan(tp),
low[i]=min(low[i],low[tp]);
else if(isins[tp])
low[i]=min(low[i],dfn[tp]);
}
if(dfn[i]==low[i])
{
lts++;
do{
j=zhan[--top];
isins[j]=;
lt[lts].push_back(j);
}while(i!=j);
}
}
void solve(int n)
{
memset(dfn,-,sizeof dfn);
memset(low,-,sizeof low);
memset(zhan,-,sizeof zhan);
memset(isins,,sizeof isins);
for(int i=;i<n;i++)
if(dfn[i]==-)
tarjan(i);
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
tu[x].push_back(y);
}
solve(n);
for(int i=;i<=lts;i++)
{
cout<<i<<":";
for(int j=;j<lt[i].size();j++)
cout<<lt[i][j]<<" ";
cout<<endl;
}
return ;
}