How Many Tables HDU - 1213
思路:并查集,开始时需要n个桌子,每合并一次需要桌子数量-1
具体代码如下
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 1010;
int n, m;
int p[N];
int find(int x){
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main(){
int T;
scanf("%d", &T);
while(T--){
scanf("%d%d", &n, &m);
int cnt = n;
for(int i=1; i<=n; ++i) p[i] = i;
while(m--){
int x, y;
scanf("%d%d", &x, &y);
x = find(x), y = find(y);
if(x != y){
p[x] = y;
cnt--;
}
}
printf("%d\n", cnt);
}
return 0;
}