poj 1308 Is It A Tree?

题目:
这里写图片描述
这里写图片描述
AC情况:
这里写图片描述
思路:
判断是不是树,主要两种情况:1.树根不止有一个。2.树根到某个结点的路径不唯一。
主要算法是并查集。
代码:

#include<iostream>
using namespace std;

int parent[101];
int flag[101];

void init() {
    for (int x = 0; x < 101; x++) {
        parent[x] = x;
        flag[x] = 0;
    }
}

int find(int x) {
    if (parent[x] != x) parent[x] = find(parent[x]);
    return parent[x];
}

int main() {
    int a, b,c=0,f,i,ctr;
    while (scanf_s("%d %d",&a,&b)) {
        if (a == -1 && b == -1) break;
        if (a == 0 && b == 0) {                       //空树也算树
            printf("Case %d is a tree.\n", ++c);
            continue;
        }

        init();

        flag[a] = 1;
        flag[b] = 1;
        f = 1;
        ctr = -1;                                    //ctr 记录树根数量,把0也算作树根ctr++

        do {
            a = find(a);
            b = find(b);
            if (a == b)f = 0;
            else parent[b] = a;
            scanf_s("%d %d", &a, &b);
            flag[a] = 1;
            flag[b] = 1;
        } while (a != 0 && b != 0);

        if (f) {
            for (i = 0; i < 101; i++)
                if (flag[i] && parent[i] == i)ctr++;


            if (ctr == 1)printf("Case %d is a tree.\n", ++c);
            else printf("Case %d is not a tree.\n", ++c);

        }
        else printf("Case %d is not a tree.\n", ++c);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值