并查集简单题pku1611

并查集简单题pku1611,第1张

题目链接:http://poj.org/problem?id=1611

代码:

#include<stdio.h>
int father[30001];
int count[30001];
int i,m,n,first,a,b;
void setfather(int n) //初始化,将各自fahter设置为本身
{
	for(i=0;i<n;i++)
	{
		father[i]=i;
		count[i]=1;
	}
}
int findfather(int i)   
{
	if(i!=father[i])
		father[i]=findfather(father[i]);
	return father[i];
}
void Untion(int a,int b)  
{
	int m1=findfather(a);
	int m2=findfather(b);
	if(m1==m2)
		return;
    if(count[m1]>=count[m2])  //若不相等,则将值赋值给较大的
	{
		father[m2]=m1;
		count[m1]=count[m2]+count[m1];
	}
	else
	{
		father[m1]=m2;
		count[m2]=count[m1]+count[m2];
	}
}
int main()
{
	while(scanf("%d %d",&n,&m)!=EOF&&n>0)
	{
		if(n>=0&&n<=30000&&m>=0&&m<=500)
		{
			setfather(n);
			while(m>0)
			{
			scanf("%d %d",&a,&first);
			for(i=0;i<a-1;i++)
			{
				scanf("%d",&b);
				Untion(first,b);
			}
			m--;
			}
			printf("%d\n",count[findfather(0)]);
		}
	}

	return 0;
}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/2088423.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-07-22
下一篇 2022-07-22

发表评论

登录后才能评论

评论列表(0条)

保存