POJ 1308(简单并查集)

本文通过POJ1308题目实例介绍并查集的实现方式,并演示如何使用并查集判断输入数据是否构成一棵树。文章提供了一段完整的C语言代码,包括并查集的查找和合并操作。

此博客详细介绍了并查集的基本概念:并查集的初级应用及进阶

   POJ1308:题意是输入每两个的数第二个的父亲是第一个数,判断输入结束之后是否是一颗树的结构。

#include<stdio.h>
int father[10020];
int Find_it(int x)
{
    int temp = x,t;
    while(father[temp] != temp)
        temp = father[temp];
    while(father[x] != x){
        t = father[x];
        father[x] = temp;
        x = t;
    }
    return temp;
}
int main()
{
    int nCase = 1;
    while(1){
        int flag = 1,x,y,i;
        for(i = 1;i <= 10001; i++)
            father[i] = i;
        while(scanf("%d%d",&x,&y) != EOF){
            if(x == 0 && y == 0)
                break;
            if(x == -1 && y == -1)
                return 0;
            int tx = Find_it(x);
            int ty = Find_it(y);
            if(tx == ty)
                flag = 0;
            else father[ty] = tx;
        }
        int k = 0;
        for(i = 1;i <= 10001; i++){
            int temp = Find_it(i);
            if(temp != i){
                if(k == 0)
                    k = temp;
                else if(k != temp){
                    flag = 0;
                    break;
                }
            }
        }
        if(flag)
            printf("Case %d is a tree.\n",nCase++);
        else printf("Case %d is not a tree.\n",nCase++);
    }
    return 0;
}











评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值