zoukankan      html  css  js  c++  java
  • 并查集树数据结构hdu1325

    我的解法就是去构造了一棵树


    以数组的存储方式


    数组的值存放节点的根。


    排除空树

    剩下的就是出现环和多根节点的情况

    也就是排除森林和有一个节点多个入度的情况

    排除森林就用到了并查集

    也就是便利数组让其仅仅有一个根

    排除多个入度的情况更简单

    就是把这个点插入到数上时

    假设这个点已经有了根节点,就出现了两个入度

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    int sett[1000 + 100],g[1000 + 100];
    int find2(int x)
    {
        while(x != sett[x] ) x = sett[x];
        return x;
    }
    int main()
    {
        int x,y,flag=1,cases=1;
        while(scanf("%d%d",&x,&y)){
        flag=1;
            for(int i=1;i<=1000;i++) sett[i]=i;
    //        for(int i=1;i<=1000;i++) g[i]=i;
            memset(g,0,sizeof(g));
    
            if(x == 0 && y == 0) flag=0;
            if(x < 0 && y < 0) break;
            else sett[y]=x;
            g[x]=1;
            g[y]=1;
    
            while(scanf("%d%d",&x,&y)){
            g[x]=1;
            g[y]=1;
                if(!x&&!y) break;
                int fx = sett[x];
                int fy = sett[y];
                if( fy != y) //out circle and two roots
                    flag=0;
                else sett[fy]=fx;
            }
    
            int countt=0;
            for(int i=1;i<=1000;i++) if(g[i]&&sett[i]==i) countt++;
    //        printf("countt %d
    ",countt);
            if(countt > 1) flag=0;
    //        printf("flag %d
    ",flag
                     if(flag) printf("Case %d is a tree.
    ",cases);
                        else printf("Case %d is not a tree.
    ",cases);
            cases++;
    //        for(int i=1;i<=10;i++)
    //            printf("%d ",i);
    //             printf("
    ");
    //             for(int i=1;i<=10;i++)
    //            printf("%d ",sett[i]);
    //        printf("
    ");
        }
        return 0;
    }
    


  • 相关阅读:
    接口报错mixed content blocked
    重拾单片机
    部署ajax服务-支持jsonp
    linkageSystem--串口通信、socket.io
    node安装问题
    jshint之对!的检验
    node之websocket
    调试node服务器-过程
    oracle取某字符串字段的后4位
    vmware 共享文件夹
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6934661.html
Copyright © 2011-2022 走看看