#include <iostream>
using namespace std;
typedef struct ufset *UFset;
typedef struct ufset
{
int *parent;
int *root;
}UFS;
UFset UFinit(int size)
{
UFset U = new ufset;
U->parent = new int[size+1];
U->root = new int[size+1];
for (int e = 1; e <= size; e++)
{
U->parent[e] = 1;
U->root[e] = 1;
}
return U;
}
int UFfind(int e, UFset U)
{
int i, j = e;
while ( !U->root[j] )
{
j = U->parent[j];
}
while ( j != e )
{
i = U->parent[e];
U->parent[e] = j;
e = i;
}
return j;
}
int UFunion(int i, int j, UFset U)
{
if (i == j) return i;
if (U->parent[i] < U->parent[j])
{
U->parent[j] += U->parent[i];
U->root[i] = 0;
U->parent[i] = j;
return j;
}
else {
U->parent[i] += U->parent[j];
U->root[j] = 0;
U->parent[j] = i;
return i;
}
}
void UFfree(UFset U)
{
delete [] U->parent;
delete [] U->root;
delete U;
}
void uni(int x, int y, UFset uf)
{
int a = UFfind(x, uf),
b = UFfind(y, uf);
UFunion(a, b, uf);
}
int main()
{
int N, M, index1, index2, count;
UFset uf;
while (true)
{
count = 0;
cin >> N;
if ( N == 0 ) break;
cin >> M;
uf = UFinit(N);
for (int i = 0; i < M; i++)
{
cin >> index1 >> index2;
uni(index1, index2, uf);
}
for (int i = 1; i <= N; i++)
{
int j = UFfind(i, uf);
if ( i == j ) count++;
}
cout << count - 1 << endl;
UFfree(uf);
}
}
|