How Many Tables并查集

How Many Tables
原题链接https://vjudge.net/contest/350427#problem/C
在这里插入图片描述
在这里插入图片描述
只有认识的人会坐到一桌,将所有认识的人合并起来,最后判断有多少个根即可。

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <queue>
using namespace std;
long long pre[30005];
long long find(long long x)
{
	if (x == pre[x])
	{
		return x;
	}
	return pre[x] = find(pre[x]);
}
void join(long long x, long long y)
{
	long long ss1 = find(x);
	long long ss2 = find(y);
	if (ss1 != ss2)
	{
		pre[ss1] = ss2;
	}
}
int main()
{
	long long t;
	scanf("%lld", &t);
	while (t--)
	{
		long long n, m;
		scanf("%lld %lld", &n, &m);
		long long i, j;
		for (i = 1; i <= n; i++)
		{
			pre[i] = i;
		}
		long long sum1, sum2;
		for (i = 0; i < m; i++)
		{
			scanf("%lld %lld", &sum1, &sum2);
			join(sum1, sum2);//认识的人没有坐到一桌的将他们的集合链接起来,也就是全部坐到一桌去,
		}
		long long sum = 0;
		for (i = 1; i <= n; i++)
		{
			//	printf("链接%lld\n",pre[i]);
			if (pre[i] == i)
			{
				sum++;//如果一个数的根是他自己,那他就一定是一个集合的根,相反就不是,所以判断有多少个根是自己的数就是集合的数目。
			}
		}
		printf("%lld\n", sum);
	}
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值