牛客练习赛8 D加边的无向图

题目链接

https://www.nowcoder.com/acm/contest/39/D

解题思路

         利用并查集查找一共有几个独立的集合,最后需要的最少边为集合个数减一

AC代码

#include<stdio.h>
#include<algorithm>
using namespace std;

typedef long long LL;
const int maxn = 100010;
LL pa[maxn],ran[maxn];

//init
void init()
{
    for(LL i = 0; i <= maxn; i++)
        pa[i] = i,ran[i] = 0;
}

LL find(LL x)
{
    return pa[x] != x ? pa[x] = find(pa[x]) : x;
}

void unite(LL x, LL y)
{
    x = find(x);
    y = find(y);
    if(x == y) return;

    if(ran[x] < ran[y])
    {
        pa[x] = y;
    }
    else
    {
        pa[y] = x;
        if(ran[x] == ran[y]) ran[x]++;
    }
}

int main()
{
    LL n,m;
    while(scanf("%lld%lld",&n,&m) == 2)
    {
        init();
        LL cnt = n;
        if(cnt == 0)
        {
            printf("0\n");
            continue;
        }
        for(LL i = 0; i < m; i++)
        {
            LL u,v;
            scanf("%lld%lld",&u,&v);
            LL x = find(u);
            LL y = find(v);
            if(x != y)
            {
                cnt--;
                unite(x,y);
            }
        }
        printf("%lld\n",cnt - 1);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值