题目 :Problem - 1232 (dingbacode.com)
#include<bits/stdc++.h>
using namespace std;
int a[1010];
int findx(int x){
while(a[x]!=x){
x=a[x];
}
return x;
}
void merge(int x,int y){
int fx=findx(x);
int fy=findx(y);
if(fx!=fy){
a[fx]=fy;
}
}
int main(){
int N,M,b,c,i,count;
while(scanf("%d",&N),N){
for(i=1;i<=N;i++){
a[i]=i;
}
for(scanf("%d",&M);M>0;M--){
scanf("%d %d",&b,&c);
merge(b,c);
}
for(count=-1,i=1;i<=N;i++){
if(a[i]==i){
count++;
}
}
printf("%d\n",count);
}
return 0;
}