水了一发的并查集
#include<iostream>
#include<cstdio>
const int maxn = 1005;
using namespace std;
int par[maxn], rot[maxn];
int n,m;
void Init()
{
for(int i = 0; i < maxn; i++)
{
par[i] = i;
rot[i] = 0;
}
}
int Find(int x)
{
if(x == par[x])
return x;
par[x] = Find(par[x]);
return par[x];
}
int Union(int x, int y)
{
x = Find(x);
y = Find(y);
if(x == y)return 0;
if(rot[x] > rot[y])
{
par[y] = x;
}
else
{
par[x] = y;
rot[y]++;
}
return 1;
}
int main()
{
while(scanf("%d",&n) != EOF)
{
if(n == 0)break;
scanf("%d",&m);
Init();
int a,b;
while(m--)
{
scanf("%d%d",&a,&b);
Union(a,b);
}
int cnt = 0;
for(int i = 1; i <= n; i++)
if(par[i] == i)
cnt++;
printf("%d\n",cnt-1);
}
return 0;
}