POJ 1308

利用树的性质来判断所给的图是否为一棵树,空树的时候要特判。

树的性质:边数 == 顶点数 - 1; 每个顶点入度 <= 1。

本来这道题想用并查集做的,但是并查集只能判断两点是否在同一集合中,但是没想出来对于成环和入度上怎么判断,就放弃了,用树的性质反而简单。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;
int edge[11117][2];
int ver[11117];

int main(){
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
#endif
    int a, b, cse = 0, vers, flag, maxc, bian, i;
    while(scanf("%d %d", &a, &b) != EOF){
        cse++;
        bian = vers = flag = maxc = 0;
        memset(edge, 0, sizeof(edge));
        memset(ver, 0, sizeof(ver));
        if(a == -1 && b == -1){
            break;
        }
        if(a == 0 && b == 0){
            printf("Case %d is a tree.\n", cse);
            continue;
        }
        while(a != 0 && b != 0){
            maxc = max(maxc, max(a, b));
            bian++;
            edge[a][1] = edge[b][1] = 1;
            edge[b][0]++;
            if(edge[b][0] > 1){
//                printf("\n%d %d\n", a, b);
                printf("Case %d is not a tree.\n", cse);
                flag = 1;
                break;
            }
            scanf("%d %d", &a, &b);
        }
//        printf("%d\n", bian);
        if(flag == 1){
            while(a != 0 && b != 0){
                scanf("%d %d", &a, &b);
            }
            continue;
        }
        for(i = 0; i <= maxc; i++){
            if(edge[i][1] != 0){
                vers++;
            }
        }
//        printf("\n%d %d %d\n", bian, vers, maxc);
//        for(i = 1; i <= maxc; i++){
//            printf("%d ", edge[i][1]);
//        }
//        printf("\n");
        if(vers == bian + 1){
            printf("Case %d is a tree.\n", cse);
        }
        else{
            printf("Case %d is not a tree.\n", cse);
        }
    }
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值