前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Is It A Tree?(并查集)

Is It A Tree?(并查集)

作者头像
用户1624346
发布2018-04-11 17:34:25
6200
发布2018-04-11 17:34:25
举报
文章被收录于专栏:calmoundcalmound

判断树是否唯一

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

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

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

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-08-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档