【并查集】HDU 1325 Is It A Tree?

判断是否为树 

森林不是树

空树也是树

成环不是树

数据:

1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1 0 0  

1 2 2 3 4 5 0 0  

2 5 0 0 

ans:

no

no

yes  

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <malloc.h>
#include <ctype.h>
#include <math.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
typedef long long LL;
const int maxn =10000+5;
const int maxe = 15000+5;
const int INF = 460002326;
const int mod = 1000000009;//q[i]表示点i 对应的点 rank[i]表示入度
int fa[maxn],q[maxn],rank[maxn],taj,flag;//taj表示当前点的编号个数
void init()
{
    flag=0;
    taj=1;
    for(int i=0; i<maxn; i++)
        fa[i]=i,q[i]=-1,rank[i]=0;
}
int find(int x)
{
    if(fa[x]==x)
        return x;
    else
    {
        fa[x]=find(fa[x]);
        return fa[x];
    }
}
void merge(int x,int y)
{
    int fx=find(x),fy=find(y);
    if(fx==fy)
    {
        flag=1;//重复
        return ;
    }
    else
    {
        fa[fy]=fx;
        rank[y]++;//入度+1
        return ;
    }
}
void dian(int a,int b)
{
    if(q[a]==-1)
        q[a]=taj++;
    if(q[b]==-1)
        q[b]=taj++;
}
int main()
{
    int a,b,cas=0;
    //   freopen("in.txt","r",stdin);
    while(scanf("%d%d",&a,&b),a+b>=0)
    {
        init();//初始化
        if(a==0&&b==0)// 0 0 也算树
        {
            printf("Case %d is a tree.\n",++cas);
            continue;
        }
        a=q[a],b=q[b];
        merge(a,b);
        while(scanf("%d%d",&a,&b))
        {
            if(a+b==0) break;
            dian(a,b);
            a=q[a],b=q[b];
            merge(a,b);
        }
        a=0;
        for(int i=1; i<maxn; i++)
            find(i);
        for(int i=1; i<maxn; i++)
        {
            if(q[i]!=-1&&fa[q[i]]==q[i])//根节点
                a++;
            if(rank[i]>1)
                flag=1;
        }
        printf("Case %d is ",++cas);
        if(a==1&&flag==0&&taj>2)
            puts("a tree.");
        else puts("not a tree.");
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值