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;
}