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;
     } 
  • 相关阅读:
    smarty-2014-02-28
    PHP Functions
    Zabbix自定义监控网站服务是否能够正常响应
    Zabbix自定义监控网站服务是否能够正常响应
    shell技巧
    shell技巧
    ansible安装配置zabbix客户端
    ansible安装配置zabbix客户端
    shell命令getopts
    shell命令getopts
  • 原文地址:https://www.cnblogs.com/Accepting/p/12658337.html
Copyright © 2011-2022 走看看