POJ 1308 Is It A Tree?再谈 并查集3

是一个判断是否为树的题目 
下面是树的定义
There is exactly one node, called the root, to which no directed edges point. //根节点没有父节点
Every node except the root has exactly one edge pointing to it. //每一个节点有且仅有一个父节点
//这就是判断不要fv!=v且fv!=fu的原因 如果有一种相等就会导致有两个父节点了哦
There is a unique sequence of directed edges from the root to each node. //这是说各个节点连通
要另外判断一下是否是空树 
//poj 1308 Is It A Tree
//并查集
//第一次错误 没有考虑到样例三的情况 根在合并前还没有出现的情况
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
const int maxn=100000;
int pa[maxn];
int findset(int x){ return pa[x]!=x?pa[x]=findset(pa[x]):x;}
int k=0;
int main()
{
    int u,v;
    while(scanf("%d %d",&u,&v)&&u>=0&&v>=0)
    {
        for(int i=1;i<maxn;i++)
        {
            pa[i]=i;
        }
        map<int,int> m;//这里用map来映射一个每个点的值和编号 防止值过大 开不下
        int num=0;
        bool flag=true;
        if(u==0&&v==0){ printf("Case %d is a tree.\n",++k); continue; }
        while(u!=0&&v!=0)
        {
            if(m.count(u)==0) m[u]=++num;
            if(m.count(v)==0) m[v]=++num;
            int fu=findset(m[u]),fv=findset(m[v]);
            if(fu==fv)   flag=false;//每一个节点有且仅有一个父节点
            if(fv!=m[v]) flag=false;
            else{pa[m[v]]=fu;}
            scanf("%d %d",&u,&v);
        }
        int fa=findset(1);
        for(int i=2;i<=num&&flag;i++)//这是说各个节点连通
        {
            if(findset(i)!=fa) flag=false;
        }
        if(flag){printf("Case %d is a tree.\n",++k);  }
        else {printf("Case %d is not a tree.\n",++k); }
    }
    return 0;
}




                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值