zoukankan      html  css  js  c++  java
  • Is It A Tree? poj 1308(并查集)

    http://poj.org/problem?id=1308 

    题意:判断是否所有的节点只能组成一棵树,也就是判断是否有环。没有说有多少个节点,比较坑了。

    注意:1.若当输出只有0 0时,也能构成一棵树,因为空树也是树。

          2.所给的节点不能够构成森林(必须只能是一棵树)

    #include<stdio.h>
    #include<string.h>
    #include<iostream>
    #include<algorithm>
    #include<math.h>
    #define maxn 110
    #define INF 0xfffffff
    using namespace std;
    
    int father[maxn], v[maxn], flag;
    
    int Find(int x)
    {
        while(x!=father[x])
            x = father[x];
    
        return x;
    }
    
    void solve(int a, int b)
    {
        v[a] = v[b] = 1;
    
        if(a == b)  flag = 1;
        else
        {
            int ra = Find(a);
            int rb = Find(b);
    
            if(ra == rb) flag = 1;
            else father[rb] = ra;
        }
    }
    
    int main()
    {
        int a, b, fist, t=1;
    
        while(scanf("%d %d", &a, &b), a!=-1 || b!=-1)
        {
            fist = a;
    
            memset(v, 0, sizeof(v));
    
            for(int i=1; i<maxn; i++)
                father[i] = i;
    
            flag = 0;
    
            if(a==0 && b==0)
            {
                printf("Case %d is a tree.
    ",t++);//空树也是树;
                continue;
            }
    
            solve(a, b);
    
            while(scanf("%d %d", &a, &b), a+b)
            {
                solve(a, b);
            }
    
            for(int i=1; i<maxn; i++)
            {
                if(Find(i)!=Find(fist) && v[i])
                {
                    flag = 1;
                    break;
                }
            }
    
            if(!flag)  printf("Case %d is a tree.
    ", t++);
    
            else printf("Case %d is not a tree.
    ", t++);
    
        }
        return 0;
    }
    View Code

      

  • 相关阅读:
    Kafka生产者Producer配置 ,及C#中使用学习资料连接
    Oracle expdb异地备份
    查询redis当前连接数据和当前信息
    Oracle在sqldeveloper中按格式显示日期数据
    DB行转列
    2019.9.10面试反思
    配置webpack4
    代理
    es6 promise
    es6 symbol
  • 原文地址:https://www.cnblogs.com/daydayupacm/p/5720474.html
Copyright © 2011-2022 走看看