HDU1856_并查集

1.题目链接。题目的大意:和畅通工程的意思是一个意思,也是n个人,其中每两个人是朋友,给出这些朋友的关系,其中朋友可以使直接的朋友,也可以是间接朋友,所谓的间接的朋友就是朋友的朋友也是朋友。然后给出这些人朋友的信息,找一个朋友圈,是的其中的人数最多。哈哈,个人的理解哈,我形象的把它定义成朋友圈。

2.读完题之后就知道这是一个并查集的使用,但是有一个问题,我们平时使用的并查集一般都是确定两个类是否是等价类,没有涉及到计数的问题。现在显然需要计数,有一种并查集叫做带权并查集,这种并查集的节点包含了它有多少个儿子这种信息但是我们在这里还是使用简单的并查集,加上辅助的数组也是可以解决这个问题的。在合并的时候,我们将计数的数组也合并一下就oK。代码如下:

#include"stdafx.h"
#include<iostream>
#include<algorithm>
#pragma warning(disable:4996)
const int N = 1e5+ 10;
int pre[N], ans[N], maxn;
using namespace std;
int find(int x)
{
	return x == pre[x] ? x : pre[x] = find(pre[x]);
}
void join(int a, int b)
{
	int x = find(a);
	int y = find(b);
	if (x != y)
	{
		pre[x] = y;
		ans[y] += ans[x];
		maxn = max(maxn, ans[y]);
	}
}
int main()
{
	int n;
	int a, b;
	while (~scanf("%d", &n))
	{
		if (!n)
		{
			puts("1");
			continue;
		}
		maxn = 0;
		for (int i = 0; i <N; i++)
		{
			ans[i] = 1;
			pre[i] = i;
		}
		for (int i = 0; i < n; i++)
		{
			scanf("%d%d", &a, &b);
			join(a, b);
		}
		cout << maxn << endl;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41863129/article/details/85795502