中文题目不解释,很经典的并查集题目
只要注意会用 find 和 find_set这两个函数就ok了;
#include<stdio.h>
int f[1010];
int find(int t)
{
if(f[t]==-1)
return t;
else
return f[t]=find(f[t]);
}
void find_set(int a,int b)
{
int t1=find(a);
int t2=find(b);
if(t1!=t2)
f[t1]=t2;
}
int main()
{
int n,m,i,a,b,res;
while(scanf("%d",&n)!=EOF&&n!=0)
{
scanf("%d",&m);
for(i=1;i<=n;i++)
f[i]=-1;
while(m--)
{
scanf("%d%d",&a,&b);
find_set(a,b);
}
res=0;
for(i=1;i<=n;i++){
if(f[i]==-1)
res++;
}
printf("%d\n",res-1);
}
return 0;
}