zoukankan      html  css  js  c++  java
  • 强连通图,Tarjan——HDU-1269

    题目链接

    题目含义

    判断一个图是不是强连通图,即任意两点存在双向通道

    题目分析

    用Tarjan可以算出这个图中的强连通图有多少个,如果不是1那当然输出No

    而如果是1,只能说明有一个强连通子图而不能说明这个图是强连通图,就需要在当dfn[x]==low[x]时,找到这个强连通图所有的点,将他们全部指向x,最后再类似并查集,确定这个图所有点在不在这个强连通图里

    题目代码

    #include<iostream>
    #include<stdio.h>
    #include<string.h>
    using namespace std;
    typedef long long LL;
    const int maxn=1e5+7;
    const int maxm=1e4+7;
    struct edge{
        int to,next;
    }e[maxn];
    int tot,cnt,top,scc,n,m,a,b;
    int head[maxm],instack[maxm],dfn[maxm],low[maxm],st[maxm],root[maxm];
    void add(int u,int v){
        e[tot].to=v;
        e[tot].next=head[u];
        head[u]=tot++;
    }
    void init(){
        tot=cnt=top=scc=0;
        memset(head,-1,sizeof(head));
        memset(instack,0,sizeof(instack));
        memset(dfn,0,sizeof(dfn));
    }
    void Tarjan(int x){
        instack[x]=1;
        low[x]=dfn[x]=++cnt;
        st[++top]=x;
        for(int i=head[x];i!=-1;i=e[i].next){
            int y=e[i].to;
            if(!dfn[y]){
                Tarjan(y);
                low[x]=min(low[x],low[y]);
            }
            else if(instack[y])low[x]=min(low[x],dfn[y]);
        }
        instack[x]=0;
        if(low[x]==dfn[x]){
            do{
                root[st[top--]]=x;
            }while(st[top+1]!=x);
            scc++;
        }
    }
    int main(){
        while(scanf("%d%d",&n,&m)){
            if(n==0&&m==0)return 0;
            init();
            for(int i=1;i<=m;i++){
                scanf("%d%d",&a,&b);
                add(a,b);
            }
            Tarjan(1);
            for(int i=1;i<=n;i++)
                if(root[i]!=1)scc=2;
            if(scc==1)printf("Yes
    ");
            else printf("No
    ");
        }
    }
  • 相关阅读:
    【剑指Offer】面试题14- I. 剪绳子
    【剑指Offer】面试题56
    【LeetCode】202. 快乐数
    【LeetCode】1095. 山脉数组中查找目标值
    【LeetCode】260. 只出现一次的数字 III
    【剑指Offer】面试题56
    【LeetCode】33. 搜索旋转排序数组
    【LeetCode】23. 合并K个排序链表
    【LeetCode】46. 全排列
    mysql可视化工具下载地址2017.6.27
  • 原文地址:https://www.cnblogs.com/helman/p/11285126.html
Copyright © 2011-2022 走看看