POJ1308 Is It A Tree?


1. 并查集,有点忘了,看维基百科回顾起来了,三个操作,路径压缩、合并、查找父节点。代码很简单,具体参考 http://zh.wikipedia.org/wiki/%E5%B9%B6%E6%9F%A5%E9%9B%86

2. WA了好多次,最后发现是当空树的时候也是一棵树,fuck。。。

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#define maxn 1000
using namespace std;
int p[maxn], flag[maxn];
int getfather(int x)
{
    return p[x] == x ? x : p[x] = getfather(p[x]);
}
int main()
{
    int t = 1, a, b;
    while (cin >> a >> b && a != -1)
    {
        if (!a)
        {
            cout << "Case " << t++ << " is a tree." << endl;
            continue;
        }
        int is = 1, tail = 0;
        for (int i = 1; i < maxn; ++i)
        {
            p[i] = i;
            flag[i] = 0;
        }
        while (a)
        {
            if (is)
            {
                int ra = getfather(a), rb = getfather(b);
                if (ra == rb)
                {
                    is = 0;
                }
                else
                {
                    p[rb] = ra;
                    flag[a] = flag[b] = 1;
                    tail = max(tail, max(a, b));
                }
            }
            cin >> a >> b;
        }
        if (!is)
        {
            cout << "Case " << t++ << " is not a tree." << endl;
        }
        else
        {
            int roots = 0;
            for (int i = 1; i <= tail; i++)
            {
                if (flag[i] && p[i] == i)
                {
                    roots++;
                    if (roots > 1)
                        break;
                }
            }
            if (roots == 1)
                cout << "Case " << t++ << " is a tree." << endl;
            else
                cout << "Case " << t++ << " is not a tree." << endl;
        }

    }
    return 0;
}



posted on 2012-07-07 09:53  赵乐ACM 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/dollarzhaole/archive/2012/07/07/3188905.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值