HDU1856 - More is better 利用并查集找最大群体数目

HDU1856 - More is better: http://acm.hdu.edu.cn/showproblem.php?pid=1856

题意: a和b认识,b和c认识,则a b c互相认识. 给出一些相互认识的两个人的编号. 判断最多有多少人互相认识(包括自己).

代码: 

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAXN = 100011;
int N;
int x,y;
int MaxId,MaxNum,Num[MAXN],Father[MAXN];
void Initial()
{
	MaxId = MaxNum = -1;
	for(int i = 0;i < MAXN;i++)
		Father[i] = i,Num[i] = 1;//Num数组的元素都初始化为 1,最少有一个人 
}
int Find(int x)
{
/*	if(x != Father[x])
		Father[x] = Find(Father[x]);
	return Father[x];
*/
	return x == Father[x] ? Father[x] : Father[x] = Find(Father[x]);
}
void Union(int x,int y)
{
	x = Find(x);
	y = Find(y);
	if(x != y)
		Father[x] = y,Num[y] += Num[x];//合并的同时将人数加到根节点上,这里要注意,不要写反了 
}
int main()
{
	while(~scanf("%d",&N))
	{
		if(!N)
		{
			printf("1\n");
			continue;
		}
		Initial();
		while(N--)
		{
			scanf("%d%d",&x,&y);
			//这里求出出现过的id最大为MaxId,因为这里是千万的数量级,全部循环一次会耗费较多的时间 
			if(MaxId < x)MaxId = x;
			if(MaxId < y)MaxId = y;
			Union(x,y);
		}
		for(int i = 0;i <= MaxId;i++)//找出最大的人数
			if(MaxNum < Num[i])
				MaxNum = Num[i];
		printf("%d\n",MaxNum);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值