【模板】tarjan

强连通分量
基于dfs序
dfn[i] : 节点i的发现时间
low[i] : i或i的子树能够追溯到的最早的栈中节点的次序号
http://www.cppblog.com/sosi/archive/2010/09/26/127797.aspx

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
const int M=500010;
const int N=100010;
struct E {int to,nxt;}edge[M];
int tot=1,idx[N];
int low[N],dfn[N];
bool ins[N];
stack<int>S;
int Time,ans;
int n,m;
void addedge(int from,int to){
    edge[tot].to=to;edge[tot].nxt=idx[from];idx[from]=tot++;
}
void dfs(int x){
    dfn[x]=low[x]=++Time;
    S.push(x);ins[x]=1;
    for(int t=idx[x];t;t=edge[t].nxt){
        E e=edge[t];
        if(!dfn[e.to]){
            dfs(e.to);
            low[x]=min(low[x],low[e.to]);
        }
        else if(ins[e.to])
            low[x]=min(low[x],dfn[e.to]);
    }
    int now;
    if(dfn[x]==low[x]){
        do{
            now=S.top();
            S.pop();
            ins[now]=0;
        }while(now!=x);
        ans++;
    }
}
int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++){
        int x,y;
        scanf("%d%d",&x,&y);
        addedge(x,y);
    }
    for(int i=1;i<=n;i++)
        if(!dfn[i]) dfs(i);
    printf("%d\n",ans);
    return 0;
}

你可能感兴趣的:(模板,Tarjan)