并查集树数据结构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;
}


原文地址:https://www.cnblogs.com/claireyuancy/p/6934661.html