简简单单的一个并查集
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
int u[N], v[N], f[1010];
int find (int x) { return f[x] == x ? x : f[x] = find(f[x]); }
int main(){
int n, m;
while(scanf("%d", &n) && n != 0){
scanf("%d", &m);
for(int i = 1;i <= n;i ++) f[i] = i;
for(int i = 1;i <= m;i ++)scanf("%d%d", &u[i], &v[i]);
int ans = n;
for(int i = 1;i <= m;i ++){
int fx = find(u[i]), fy = find(v[i]);
if(fx != fy){
f[fx] = fy;
ans --;
}
}
printf("%d\n", ans - 1);
}
return 0;
}