Tarjan 强连通分量

//Tarjan 强连通分量 
//dfn[]时间戳 low[]经过一条非回溯边可到达的时间戳最小节点 即其能回溯到的最小节点 
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
int n,m,cnt,head[10001];
int t,sta[10001],vis[10001];
int dot,dfn[10001],low[10001];
struct uio{
    int to,next;
}edge[200001];
void add(int x,int y)
{
    edge[++cnt].next=head[x];
    edge[cnt].to=y;
    head[x]=cnt;
}
void tarjan(int x)
{
    dfn[x]=low[x]=++dot;
    sta[++t]=x;
    vis[x]=1;
    for(int i=head[x];i;i=edge[i].next)
    {
        int y=edge[i].to;
        if(!dfn[y])
        {
            tarjan(y);
            low[x]=min(low[x],low[y]);
        }
        else if(vis[y])
            low[x]=min(low[x],dfn[y]);
    }
    if(low[x]==dfn[x])
    {
        while(1)
        {
            printf("%d ",sta[t]);
            vis[sta[t]]=0;
            t--;
            if(x==sta[t+1])
                break;
        }
        printf("\n");
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        add(u,v);
    }
    for(int i=1;i<=n;i++)
        if(!dfn[i])
            tarjan(i);
     return 0;
}

 

posted @ 2018-07-08 16:55  radishえらい  阅读(126)  评论(0编辑  收藏  举报