第一次做并查集的题,选了道比较简单的。 用数组很简单,不多说了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <cstdio>
#include <cstdlib>

int a[1010];

void Init(int N){
for(int i = 1;i <= N;i++)
a[i] = i;
}

int Find(int x){
while(x != a[x])
x = a[x];
return x;
}

void Union(int x, int y){
int x1 = Find(x);
int y1 = Find(y);
if(x1 != y1)
a[y1] = x1;
return ;
}

int main(){
//freopen("in.txt","r",stdin);
int T;
scanf(" %d",&T);
while(T--){
int N,M;
scanf(" %d%d",&N,&M);
Init(N);
for(int i = 0;i < M;i++){
int x,y;
scanf("%d%d",&x,&y);
Union(x,y);
}

int ans = 0;
for(int i = 1;i <= N;i++){
if(i == a[i])
ans++;
}
printf("%d\n",ans);
//getchar();
}
return 0;
}