tarjan1
#include<iostream> #include<cstring> using namespace std; struct node { int v; int next; }edge[1010]; int dfn[1010],low[1010],heads[1010]; int cnt,visit[1010],stack[1010],tot; int idx,ans; void add(int x,int y) { edge[++cnt].next=heads[x]; edge[cnt].v=y; heads[x]=cnt; return; } void tarjan(int x) { dfn[x]=low[x]=++tot; stack[++idx]=x; visit[x]=1; for(int i=heads[x];i!=-1;i=edge[i].next) { if(dfn[edge[i].v]==0) { tarjan(edge[i].v); low[x]=min(low[x],low[edge[i].v]); } else if(visit[edge[i].v]) { low[x]=min(low[x],dfn[edge[i].v]); } } if(low[x]==dfn[x]) { do { cout<<stack[idx]; visit[stack[idx]]=0; idx--; }while(x!=stack[idx+1]); cout<<endl; } return; } int main() { memset(heads,-1,sizeof(heads)); int n,m; cin>>n>>m; int x,y; for(int i=1;i<=m;i++) { cin>>x>>y; add(x,y); } for(int i=1;i<=n;i++) { if(dfn[i]==0) { tarjan(i); } } return 0; }