zoukankan      html  css  js  c++  java
  • 【专题】图的连通性问题有向图的强连通性的求解及应用

    1.Tarjan算法:

    View Code
    #include <stdio.h>
    #include <iostream>
    #include <string.h>
    #define E 10000
    #define V 1000
    using namespace std;
    void tarjan(int u);
    void solve();
    void suodian();
    void addedge(int u,int v,int c);
    int top,cnt,index,n,ecnt;
    bool instack[V];
    int stack[V],id[V],dfn[V],low[V],num[V],in[V];
    int head[V];
    struct edge
    {
        int s;
        int t;
        int cost;
        int next;
    }e[E];
    
    void suodian()
    {
        for(int i=1;i<=n;i++)
        {
            for(int k=head[i];k!=-1;k=e[k].next)
            {
                if(id[e[k].s]!=id[e[k].t])
                    in[e[k].s]++;
            }
        }
        int con=0;
        for(int i=1;i<=n;i++)
        {
            if(in[i])
            {
                con++;
            }
        }
        if(con+1==cnt)
        {
            printf("The algo is right!");
        }
    }
    void solve()
    {
        int i;
        top=cnt=index=0;
        memset(dfn,0,sizeof(dfn));
        memset(num,0,sizeof(dfn));
        memset(in,0,sizeof(in));
        for(i=1;i<=n;i++)
        {
            if(!dfn[i])
                tarjan(i);
        }
        suodian();
    }
    
    void tarjan(int u)
    {
        int v;
        int tmp;
        dfn[u]=low[u]=++index;
        instack[u]=true;
        stack[++top]=u;
        for(int k=head[u];k!=-1;k=e[k].next)
        {
            v=e[k].t;
            if(!dfn[v])
            {
                tarjan(v);
                if(low[v]<low[u])
                    low[u]=low[v];
            }
            else if(instack[v] && dfn[v]<low[u])
            {
                low[u]=dfn[v];
            }
        }
        if(dfn[u]==low[u])
        {
            cnt++;
            do
            {
                tmp=stack[top--];
                instack[tmp]=false;
                id[tmp]=cnt;
                num[cnt]++;//统计标号为cnt的强连通分量中点的个数
            }
            while(tmp!=u);
        }
    }
    
    void addedge(int u,int v,int c)
    {
        e[ecnt].s=u;
        e[ecnt].t=v;
        e[ecnt].cost=c;
        e[ecnt].next=head[u];
        head[u]=ecnt++;
    }
    int main()
    {
        int ecnt=0;
        memset(head,-1,sizeof(head));
        return 0;
    }

    例题:

    POJ-2762;

    POJ-2186;

    POJ-2553;

    POJ-1236.

  • 相关阅读:
    寒号鸟不是鸟,爸爸你会吃。
    思杨的课外班的思考
    一年级第二学期
    City
    SON
    python(16)——生成器
    python(15)——迭代和迭代器
    python(14)——python中的数学模块
    python(13)——lambda表达式
    Python(12)——变量作用域及闭包操作
  • 原文地址:https://www.cnblogs.com/markliu/p/2517838.html
Copyright © 2011-2022 走看看