并查集的入门题,非常的简单,只要懂一点并查集就能写出来,就不解释了。
#include<stdio.h>
#include<stdlib.h>
#define MAX 1000
void connect(int *nums,int a,int b){
a = find(nums,a);
b = find(nums,b);
nums[b] = a;
}
int find(int *nums,int a){
while(nums[a]!=a){
nums[a] = nums[nums[a]];
a = nums[a];
}
return a;
}
int c(int* nums,int a,int b){
return find(nums,a) == find(nums,b);
}
int main()
{
int n,m,a,b;
int city[MAX];
while(1){
scanf("%d",&n);
if(n == 0){
return 0;
}
scanf("%d",&m);
for(int i=1;i<=n;i++){
city[i] = i;
}
for(int i=0;i<m;i++){
scanf("%d%d",&a,&b);
connect(city,a,b);
}
int res = 0;
for(int i=1;i<=n;i++){
if(city[i] == i){
res++;
}
}
printf("%d\n",res-1);
}
}