并查集的复习水题
#include <stdio.h>
#include <iostream>
using namespace std;
#define LEN 10000
int p[LEN];
void init(int n) {
int i;
for(i = 1; i <= n; i++) {
p[i] = i;
}
}
int find(int x) {
return p[x] == x ? x : (p[x] = find(p[x]));
}
void make_set(int px, int py) {
if(px == py) {
return;
}
p[px] = py;
}
int main() {
int files;
int i, j;
scanf("%d", &files);
while(files--) {
int n, m;
scanf("%d%d", &n, &m);
init(n);
for(i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
int t1 = find(a);
int t2 = find(b);
if(t1 != t2) {
make_set(t1, t2);
}
}
int ans = 0;
for(i = 1; i <= n; i++) {
if(i == p[i]) {
ans++;
}
}
printf("%d\n", ans);
}
return 0;
}