zoukankan      html  css  js  c++  java
  • tarjan强连通分量 (模板)

    #include<iostream>
    #include<cstdio>
    
    using namespace std;
    const int MAXN = 10005;
    
    struct Edge{
        int nxt,to;
    }edge[10*MAXN];
    
    int n,m,stack[MAXN],low[MAXN],dfn[MAXN];
    int cnt,head[MAXN],col[MAXN],num,top,col_num;
    bool vis[MAXN];
    
    inline void add(int bg,int ed){
        edge[++cnt].to=ed;
        edge[cnt].nxt=head[bg];
        head[bg]=cnt;
    }
    
    inline void tarjan(int u){
        dfn[u]=low[u]=++num;
        vis[u]=1;
        stack[++top]=u;
        for(int i=head[u];i;i=edge[i].nxt){
            int v=edge[i].to;
            if(!dfn[v]){
                tarjan(v);
                low[u]=min(low[v],low[u]);
            }
            else if(vis[v]) 
                low[u]=min(low[u],dfn[v]);
        }
        if(dfn[u]==low[u]){
            vis[u]=0;
            col[u]=++col_num;
            while(stack[top]!=u){
                col[stack[top]]=col_num;
                printf("%d ",stack[top]);
                vis[stack[top--]]=0;
            }
            printf("%d
    ",u);
            top--;
        }
    }
    
    int main(){
        scanf("%d%d",&n,&m);
        for(register int i=1;i<=m;i++){
            int x,y;
            scanf("%d%d",&x,&y);
            add(x,y);
        }   
        for(register int i=1;i<=n;i++){
            if(!dfn[i]) tarjan(i);
        }
    }
  • 相关阅读:
    2016.7.31整机升级计划
    UVa 1588
    UVa1587
    Jzoj4714 公约数
    Jzoj4714 公约数
    Jzoj4713 A
    Jzoj4713 A
    Jzoj4711 Binary
    Jzoj4711 Binary
    Jzoj4710 Value
  • 原文地址:https://www.cnblogs.com/sdfzsyq/p/9677136.html
Copyright © 2011-2022 走看看