poj 1308 Is It A Tree? 并查集,有向树的判断

题目地址:poj 1308

首先注意trick:空树(直接 0,0)  也是树

然后,首先用并查集保证是一颗无向树的结构。  没有环,而且合并的次数等于结点的次数减1.

然后保证没有一个结点被指向两次,这样就符合题意了,只是,不题目没说数据范围.... 搞个100000;

代码:


#include<iostream>
#include<set>
#include<map>

using namespace std;

const int maxn=100000;
 int fa[maxn];


 int find(int x)
 {
     return fa[x]==x?x:fa[x]=find(fa[x]);
 }

 void init()
 {
     for(int i=0;i<maxn;i++)
     {
         fa[i]=i;
     }
 }

set<int> s;
set<int> s_to;

int n,m;
int cnt=0;


int main()

{
    int a,b;
    int index=0;
    init();
    bool ok=1;
    n=0;
    int cc_minus=0;


    while(cin>>a>>b)
    {

        if(a==-1&&b==-1)  break;
        if(a==0&&b==0)
       {

            if((ok&&s.size()-1==cc_minus)||s.size()==0) cout<<"Case "<<++index<<" is a tree."<<endl;
            else cout<<"Case "<<++index<<" is not a tree."<<endl;

            init();
            ok=1;
            cc_minus=0;
            s.clear();
            s_to.clear();
       }

        else{

        s.insert(a);
        s.insert(b);
        if(s_to.find(b)!=s_to.end())
         {
             ok=0;
         }
         else
         {
             s_to.insert(b);
         }

        int x=find(a-1);
        int y=find(b-1);

         if(x!=y)
         {
              fa[x]=y;
              cc_minus++;
         }

        else  ok=0;


        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值