zoukankan      html  css  js  c++  java
  • 并查集判树 poj 1308

    例题: poj 1308

    题目大意比较简单,对任意两个点,有且仅有一条道路,也就是一棵树。

    题解:一棵树中,肯定是不能有环的,而且只能由一个根节点。(没认真读题,只知道在那里判环。。。。),所以这个题先判环然后就是判根节点的唯一性。

    //#include<bits/stdc++.h>
    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    
    using namespace std;
    const int N=1e5+7;
    int fa[N];
    bool mark[N];
    int find(int x){
        return fa[x]==x? x:fa[x]=find(fa[x]);
    }
    bool unite(int x,int y){
        x=find(x);y=find(y);
        if(x==y) return 1;
        else {
            fa[x]=y;
            return 0;
        }
    }
    
    
    int main(){
        int n,m,time=0;
        while(cin>>n>>m){
            if(n==-1&&m==-1) break;
            for(int i=0;i<=100000;i++) {
                fa[i]=i;mark[i]=0;
            }
            
            if(n==0&&m==0) {
                printf("Case %d ",++time);
                cout<<"is a tree."<<endl;
                continue ;
            }
            
            mark[n]=mark[m]=1;
            
            bool flag=0;
            
            if(unite(n,m)) flag=1;
            
            while(cin>>n>>m,n||m){
                mark[n]=mark[m]=1;
                if(unite(n,m)) flag=1;
            }
            printf("Case %d ",++time);
            
            if(flag) cout<<"is not a tree."<<endl;
            
            else{
                int tmp=0;
                for(int i=1;i<=100000;i++){
                    if(mark[i]&&find(i)==i)   tmp++;
                }
                if(tmp!=1) cout<<"is not a tree."<<endl;
                else cout<<"is a tree."<<endl;
            }
        }
        return 0;
     } 
  • 相关阅读:
    使用Android自定义格式的定义Button
    Java Binary Search
    非常成功的人会做的八件事
    Ubuntu12.04 安装java
    NetBeans 时事通讯(刊号 # 125 Nov 17, 2010)
    NetBeans IDE 7.0 Beta 发布
    关于 IPv6 你需要知道的 10 件事
    开始学习 Go
    开始学习 Go
    Quartz 1.8.4 发布
  • 原文地址:https://www.cnblogs.com/Accepting/p/12658337.html
Copyright © 2011-2022 走看看