模板——Tarjan
#include <cstdio> #include <cstring> #include <iostream> #include <vector> using namespace std; const int maxn=2000; vector<int>tu[maxn]; vector<int>lt[maxn]; int n,m,lts=0; int js=0; int dfn[maxn],low[maxn]; int zhan[maxn],top=0; bool isins[maxn]; void tarjan(int i) { int j; dfn[i]=low[i]=++js; isins[i]=1; zhan[top++]=i; for(int j=0;j<tu[i].size();j++) { int tp=tu[i][j]; if(dfn[tp]==-1) 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]=0; lt[lts].push_back(j); }while(i!=j); } } void solve(int n) { memset(dfn,-1,sizeof dfn); memset(low,-1,sizeof low); memset(zhan,-1,sizeof zhan); memset(isins,0,sizeof isins); for(int i=0;i<n;i++) if(dfn[i]==-1) tarjan(i); } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=m;i++) { int x,y; scanf("%d%d",&x,&y); tu[x].push_back(y); } solve(n); for(int i=1;i<=lts;i++) { cout<<i<<":"; for(int j=0;j<lt[i].size();j++) cout<<lt[i][j]<<" "; cout<<endl; } return 0; }