zoukankan      html  css  js  c++  java
  • POJ1308 Is It A Tree? 并查集

    判定是否成环,是否只有一个根,是否为空.

    代码如下:

    #include <cstdlib>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <map>
    #define MAXN 100000
    using namespace std;
    
    int stk[MAXN+5], top, flag;
    
    int set[MAXN+5];
    
    map<int,int>mp;
    
    void init()
    {
        for (int i = 1; i <= MAXN; ++i) set[i] = i;
        top = flag = 0;
        mp.clear();    
    }
    
    int find(int x)
    {
        return set[x] = x == set[x] ? x : find(set[x]);
    }
    
    int main()
    {
        int x, y, ca = 0;
        init();
        while (scanf("%d %d", &x, &y), x >= 0 && y >= 0) {
            if (!x && !y) {
                int k = 0;
                for (int i = top; i >= 1; --i) {
                    if (set[stk[i]] == stk[i]) {
                        ++k;
                    }
                }
                if (k == 1 && !flag || top == 0) {
                    printf("Case %d is a tree.\n", ++ca);
                }
                else {
                    printf("Case %d is not a tree.\n", ++ca);    
                }
                init();
            }
            else {
                if (!mp.count(x)) {
                    mp[x] = 1;
                    stk[++top] = x;
                }
                if (!mp.count(y)) {
                    mp[y] = 1;
                    stk[++top] = y;
                }
                int a, b;
                a = find(x), b = find(y);
                if (a != b) {
                    set[a] = b;
                }
                else {
                    flag = 1;
                }
            }
        }
        return 0;    
    }
  • 相关阅读:
    待你长发及腰
    《线段树》讲稿
    Codeforces #Round 376 F 题解
    包裹快递 题解
    Codeforces #Round 376 部分题解
    圆圈舞蹈 题解
    奶牛晒衣服 题解
    BZOJ 1034 题解
    BZOJ 1045 题解
    BZOJ 1054 题解
  • 原文地址:https://www.cnblogs.com/Lyush/p/2043731.html
Copyright © 2011-2022 走看看