这是一道并查集问题,把所有认识的人合并到一组,最后检查根节点个数,即是需要的桌子数。由于本人的粗心,导致WA一次,在遍历根节点个数时,我错误的选择了范围,实在不应该犯这种低级错误。代码如下:
#include <iostream>
#include <cstdio>
using namespace std;
int par[1100];
int find1(int x)
{
int r = x;
while(par[r] != r) r = par[r];
int i = x, j;
while(i != r)
j = par[i], par[i] = r, i = j;
return r;
}
void unite(int x, int y)
{
x = find1(x);
y = find1(y);
par[x] = y;
}
bool same(int x, int y)
{
return find1(x) == find1(y);
}
int main()
{
int t, n, m, a, b;
scanf("%d", &t);
while(t--)
{
int sum = 0;
for(int i = 1; i < 1100; i++)
par[i] = i;
scanf("%d%d", &n, &m);
for(int i = 0; i < m; i++)
{
scanf("%d%d", &a, &b);
if(! same(a, b)) unite(a, b);
}
for(int i = 1; i <= n; i++)
if(par[i] == i) sum++;
printf("%d\n", sum);
}
return 0;
}