NYOJ 920 Trees

先做了树的判定,在做了这道题,花费一上午的时间,对于并查集的使用,用深刻许多,对于这道题我们可以这样做:

1,首先判断有几个集合

2,判断每个集合是不是都能成树

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int out[10003];
int num1[250003],num2[250003];
int father[100001];
int find(int x)
{
    if(x==father[x])
    return father[x];
    return father[x] = find(father[x]);
}
bool uniom(int a,int b)
{
    int x = find(a);
    int y = find(b);
    if(x==y)return true;
    return false;
}
void merge(int a,int b)
{
     int x = find(a);
     int y = find(b);
     if(x<=y)
     father[x] = y;
     else
     father[y] = x;

}
void init(int n)
{
     memset(out,0,sizeof(out));
     for(int i=1;i<=n;i++)
     father[i] = i;
}
int main()
{
    int n,m;
    int a,b;
    int count = 1;
    while(~scanf("%d%d",&n,&m),n+m)
    {
        init(n);
        int cn = 0;
        for(int i=1;i<=m;i++)
        {
            scanf("%d%d",&a,&b);
            num1[++cn] = a;
            num2[cn] = b;
        }
        int tolly = n;
        for(int i=1;i<=cn;i++)
        {
            if(uniom(num1[i],num2[i]))
            out[find(num1[i])] = 1;
            else
            {
                 merge(num1[i],num2[i]);
                 tolly--;
            }
        }
        for(int i=1;i<=n;i++)
        if(father[i]==i &&out[i])tolly--;
        if(tolly==0)printf("Case %d: No Trees.\n",count++);
        else
        if(tolly==1)
        printf("Case %d: There is one tree.\n",count++);
        else
        printf("Case %d: A forest of %d trees.\n",count++,tolly);
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值