Tarjan模板

#include<cstdio>
#include<stack>
#include<cstring>
#include<algorithm>
const int N=5001;
const int M=500001;
struct edge{
    int to,next;
}edge[M];
int DFN[N],LOW[N],belong[N],head[N],cnt[N];
bool f[N];
int n,m,i,k,x,y,t,ecnt,scnt,cntt,maxn;
using namespace std;
stack<int>mystack;
void add(int x,int y){
    edge[ecnt].next=head[x];
    edge[ecnt].to=y;
    head[x]=ecnt++;
}
void tarjan(int u){
    int i,v;
    DFN[u]=LOW[u]=++scnt;
    f[u]=1;
    mystack.push(u);
    for (i=head[u];i!=-1;i=edge[i].next){
        v=edge[i].to;
        if (!DFN[v]){
            tarjan(v);
            LOW[u]=min(LOW[u],LOW[v]);
        }
        else if (f[v]) LOW[u]=min(LOW[u],DFN[v]);
    }
    if (DFN[u]==LOW[u]){
        cntt++;
        do{  
            i=mystack.top(); 
            mystack.pop(); 
            f[i]=0;  
            belong[i]=cntt; 
            cnt[cntt]++;
        }  
        while (i!=u);  
    }
}
int main(){
    scanf("%d%d",&n,&m);
    memset(head,-1,sizeof(head));
    for (i=1;i<=m;i++){
        scanf("%d%d",&x,&y);
        add(x,y);
    }
    for (i=1;i<=n;i++)
        if (!DFN[i]) tarjan(i);
    for (i=1;i<=n;i++)
    	printf("%d ",belong[i]);
    return 0;
}
posted @ 2019-02-19 12:13  Weakest-konjac  阅读(118)  评论(0编辑  收藏  举报