HDU - 1272 并查集判定图是否为树 坑点挺多

题目

在这里插入图片描述

题解思路

当在已为同一棵树里再加边时,可以判断不为树。
再加上树的性质 : 点的数量等于边数减一 (判定非连通图)
这两个条件加上去就可以AC了
坑点

  1. 0 0 为Yes
  2. 1 2 2 1 (自环)这条可以用第一个条件筛去 这样只要特判0 0即可!

AC代码

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int a[100010];
bool un[100010];
int ans = 0,book = 1;
int find2( int x  )
{
    int r =x ;
    while( r != a[r] )
    {
        r = a[r];
    }
    while( x != a[x] )
    {
        int t = a[x];
        a[x] = r;
        x = a[x];
    }
    return r;
}
void  u (int x,int y)
{
    int fx = find2(x);
    int fy = find2(y);
  //  cout<<x<<"  "<<fx<<"   "<<y<<"   "<<fy<<"    \n";
      if (fx != fy)
      {
     //     cout<<ans<<"\n";
          ans++;
          a[fx] = fy;
      }else
      {
          book = 0;
      }
}
void ini()
{
    for (int i = 0; i<= 100000 ; i++ )
        a[i] = i;
}
int main ()
{
    int x,y,flag = 0;
    ini();
    while(~scanf("%d%d",&x,&y))
   {
      if ( x == -1 && y == -1)
           break;
        if ( x == 0 && y == 0 )
        {
            if (flag == 0 )
            {
                cout<<"Yes\n";
                continue;
            }
           // cout<<flag<<"   "<<ans<<"  \n";
            if (flag == ans+1 && book == 1 )
                cout<<"Yes\n";
            else
                cout<<"No\n";
            memset(un,0,sizeof(un));
            flag = 0;
            ans = 0;
            book = 1;
            ini();
            continue;
        }
        if ( un[x] == 0 )
        {
            un[x] = 1;
            flag++;
        }
        if ( un[y] == 0 )
        {
            un[y] = 1;
            flag++;
        }
        if (book)
        u(x,y);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值