zoukankan      html  css  js  c++  java
  • HDU1272 小希的迷宫

    用并查集判断图是否连通,以及是否存在环~

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<vector>
    #include<unordered_map>
    using namespace std;
    const int maxn=1e6+14;
    const int inf=1e9;
    int father[maxn],isRoot[maxn],flag,visit[maxn];
    void init () {
        for (int i=0;i<maxn;i++) father[i]=i;
        flag=0;
        fill (isRoot,isRoot+maxn,0);
        fill (visit,visit+maxn,0);
    }
    int findfather (int x) {
        int a=x;
        while (x!=father[x]) x=father[x];
        while (a!=father[a]) {
            int z=a;
            a=father[a];
            father[z]=x;
        }
        return x;
    }
    void Union (int a,int b) {
        int faA=findfather(a);
        int faB=findfather(b);
        if (faA!=faB) father[faA]=faB;
    }
    int main () {
        while (1) {
            int flag=0,x,y;
            init ();
            while (1) {
                scanf ("%d %d",&x,&y);
                if (x==0&&y==0) break; 
                if (x==-1&&y==-1) return 0;
                if (findfather(x)==findfather(y)) flag++;
                visit[x]=1;visit[y]=1;
                Union (x,y);
            }
            for (int i=0;i<maxn;i++) if (visit[i]) isRoot[findfather(i)]++;
            int ans=0;
            for (int i=0;i<maxn;i++) if (isRoot[i]&&visit[i]) ans++;
            if (ans>1) flag++; 
            //printf ("%d
    ",ans);
            if (flag==0) printf ("Yes
    ");
            else printf ("No
    ");
        }
        return 0;
    }
  • 相关阅读:
    USACO 5.5 Twofive
    USACO 5.4 Telecowmunication
    USACO 5.4 Character Recognition
    BZOJ 1001: [BeiJing2006]狼抓兔子
    USACO 5.4 Canada Tour
    USACO 5.3 Big Barn
    USACO 5.3 Network of Schools
    USACO 5.3 Window Area
    2017辽宁冬令营-4.蚂蚁
    2017辽宁冬令营-3.斐波那契
  • 原文地址:https://www.cnblogs.com/zhanglichen/p/12305544.html
Copyright © 2011-2022 走看看