hdu1213 How Many Tables

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

int father[1002];
//并查集
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;
	}
}

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

你可能感兴趣的:(hdu1213 How Many Tables)