题目链接
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;
}