tarjan

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<ctime>
using namespace std;
const int N=50005;
int n,m,head[N],dfs[N],stack[N],low[N],cnt,t,top,ans;
bool vis[N];
struct node{
    int u,v,next;
}edge[N];
void push(int u,int v){
    ++cnt;
    edge[cnt].u=u;
    edge[cnt].v=v;
    edge[cnt].next=head[u];
    head[u]=cnt;
}
void tarjan(int u){
    dfs[u]=low[u]=++t;
    stack[++top]=u;
    vis[stack[top]]=1;
    for(int i=head[u];i!=-1;i=edge[i].next){
        if(!dfs[edge[i].v]){
            tarjan(edge[i].v);
        }
        if(vis[edge[i].v]){
            low[u]=min(low[u],low[edge[i].v]);
        }
    }
    if(low[u]==dfs[u]){
        for(++ans;stack[top+1]!=u;){
            vis[stack[top--]]=0;
        }
    }
}
int main(){
    int u,v;
    scanf("%d%d",&n,&m);
    memset(head,-1,sizeof(head));
    for(int i=1;i<=m;i++){
        scanf("%d%d",&u,&v);
        push(u,v);
    }
    for(int i=1;i<=n;i++){
        if(!dfs[i]){
            tarjan(i);
        }
    }
    printf("%d\n",ans);
    system("pause");
    return 0;
}
上一篇:[模板]tarjan——最后通牒


下一篇:Android常见错误整理