hdu1232 畅通工程

#include <stdio.h>
#include <string.h>

int father[1002],sum;
//并查集
int find (int k)
{
	if(father[k]!=k)
		father[k]=find(father[k]);
	return father[k];
}
void make(int x,int y)
{
	int f1=find(x);
	int f2=find(y);
	if(f1!=f2)
	{
		father[f2]=f1;
		//sum++;
	}
}

int main()
{
	int n,m,i,x,y;
	while(scanf("%d",&n)&&n!=0)
	{
		scanf("%d",&m);
		memset(father,0,sizeof(father));
		sum=0;
		for(i=1;i<=n;i++)
			father[i]=i;
		for(i=0;i<m;i++)
		{
			scanf("%d %d",&x,&y);
			make(x,y);
		}
		for(i=1;i<=n;i++)
		{
			if(father[i]==i)
				sum++;
		}
		printf("%d\n",sum-1);
		//printf("%d\n",n-1-sum);
	}
	return 0;
}

你可能感兴趣的:(hdu1232 畅通工程)