HDU 1856-More is better(并查集)

More is better

Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 327680/102400 K (Java/Others)
Total Submission(s): 40136 Accepted Submission(s): 14080

Problem Description

Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.

Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang’s selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.

Input

The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)

Output

The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.

Sample Input

4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8

Sample Output

4
2

Hint

A and B are friends(direct or indirect), B and C are friends(direct or indirect),
then A and C are also friends(indirect).

In the first sample {1,2,5,6} is the result.
In the second sample {1,2},{3,4},{5,6},{7,8} are four kinds of answers.

问题描述
王先生希望一些男孩帮助他做一个项目。由于项目相当复杂,男孩来的越多,情况就会越好。当然有一定的要求。

王先生选择了一个足以容纳男孩的房间。没有被选中的男孩必须立即离开房间。刚开始的时候,房间里有1000万个男孩,从1到1000万。在王先生被选出之后,仍然在这个房间里的两个人应该是朋友(直接或间接),或者只剩下一个男孩。考虑到所有直接的朋友对,您应该决定最佳方法。

输入
输入的第一行包含整数n(0≤n≤100 000)-直接朋友对的数量。接下来的n行分别包含一对数字A和B,并用一个空格隔开,表明A和B是直接朋友。(A≠B,1≤A,B≤10000000)

输出
一行中的输出正好包含一个整数,该整数等于王先生可以保留的男孩的最大数量。

样本输入
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8

样本输出
4
2

提示

A和B是朋友(直接或间接),B和C是朋友(直接或间接),
那么A和C也是朋友(间接)。

在第一个样本{1,2,5,6}中是结果。
在第二个示例{1,2},{3,4},{5,6},{7,8}中有四种答案。

题目链接

题目大意:给出n对朋友,其中朋友的关系可以是直接或间接的,如 1 2 ,2 3,则1 2 3 是一个集合。求这个集合的最大值。

解题思路:这道题用到的是并查集的知识,也是需要先进行合并,不过和以往不同的是我们需要设置一个存放当前集合元素数量的数组,最后输出元素数最多的数量。AC代码:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=1e5+50;
int f[N],pm[N],ans;
int find(int x)
{
	if(x!=f[x])
	  f[x]=find(f[x]);
    return f[x];
}
void merge(int x,int y)
{
	int t1,t2;
	t1=find(x);
	t2=find(y);
	if(t1!=t2)
	{
		f[t2]=t1;
		pm[t1]+=pm[t2];//数量与数量间的合并
	}
	if(pm[t1]>ans)//随时更新ans
	  ans=pm[t1];
}
int main()
{
	int t;
	while(cin>>t)
	{
		ans=1;
		for(int i=0;i<=N;i++)
		{
			f[i]=i;
			pm[i]=1;
		}
		for(int i=1;i<=t;i++)
		{
			int a,b;
			cin>>a>>b;
			merge(a,b);
		}
		cout<<ans<<endl;
	}
	system("pause");
	return 0;
}
原文地址:https://www.cnblogs.com/Hayasaka/p/14294301.html