<span style= "font-family:arial, Helvetica, Sans-serif;" > #include <iostream></span>
#include <cstring>
using namespace std;
int pre[1005];
int find (int x)
{
int r=x;
while (R!=pre[r]) //Search root node, (Pre[r] is the superior of R,)
R=pre[r];
int i=x,j;
while (I!=R) //compression path, so that each child node superior directly to the root node, eliminating the layer of backtracking
{
j=pre[i];
Pre[i]=r;
i=j;
}
return r;
}
void Mix (int a,int b)
{
int fx=find (a); Select the root node
int fy=find (b); Select the root node
if (fx!=fy) //If equal, that is the same root node, otherwise, with the node to merge
{
pre[fx]=fy; Root node Merge
}
}
int main ()
{
int n,m;
while (Cin>>n>>m&&n)
{
bool t[1005]; Used to make the final statistic
int ans=-1;
memset (t,0,sizeof (t));
for (int i=1;i<=n;++i)
pre[i]=i; Initialize
int A, b;
for (int i=1;i<=m;++i)
{
cin>>a>>b;
Mix (A, b); Merge Operation
} for
(int i=1;i<=n;++i)
t[(Find (i))]=1;
for (int i=1;i<=n;++i)
if (T[i])
ans++;
cout<<ans<<endl;
}
Explanation: http://blog.csdn.net/kirito_j/article/details/51778229