Is It A Tree?(并查集)

时间:2022-05-08
本文章向大家介绍Is It A Tree?(并查集),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

判断树是否唯一

1.只有一个根节点,(1)在一棵树上一个根节点。1 2 3 2就是两个根节点(1)只有一棵树

2.不成环,入度不大于1

由于数组运行超界导致wa,这是老毛病了 还一直错

#include<stdio.h>
const int MAXN=1000100;
int father[MAXN],rank[MAXN];

struct Node
{
    int x,y;
} node[MAXN];

void Make_set()
{
    for(int i=1; i<MAXN; i++)
    {
        rank[i]=0;
        father[i]=i;
    }
}

int Find(int x)
{
    int r=x;
    while(r!=father[r])
    {
        r=father[r];
    }
    if(r!=x) father[x]=r;
    return father[x];
}

void Union(int x,int y)
{
    //秩小的加到大的里
   /* if(rank[x]>rank[y])
    {
        father[y]=x;
    }
    else
    {
        if(rank[x]==rank[y])
        {
            rank[y]++;
        }
        father[x]=y;
    }*/
    father[y]=x;
}

int main()
{
    int cas,flag,i;
    int tes=1;
    while(1)
    {
        cas=flag=0;
        while(scanf("%d%d",&node[cas].x,&node[cas].y))
        {
            if(node[cas].x==-1 && node[cas].y==-1) return 0;
            if(node[cas].x==0 && node[cas].y==0) break;
            cas++;
        }
        Make_set();
        for(i=0; i<cas; i++)
        {
            int x=Find(node[i].x);
            int y=Find(node[i].y);
            if(x==y)
            {
                flag=1;
            }
            else Union(x,y);
        }
        int temp=Find(node[0].x);
        for(i=0; i<cas; i++)
        {
            if(Find(node[i].x)!=temp) flag=1;
            if(Find(node[i].y)!=temp) flag=1;
        }
        if(flag) printf("Case %d is not a tree.n",tes++);
        else printf("Case %d is a tree.n",tes++);
    }
    return 0;
}