2130 Problem D More is better

问题 D: More is better

时间限制: 1 Sec  内存限制: 128 MB
提交: 130  解决: 42
 

题目描述

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.

输入

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)

输出

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

样例输入

3
1 3
1 5
2 5
4
3 2
3 4
1 6
2 6

样例输出

4
5

经验总结

这题。。。还是有坑的。。

一、注意输入0的处理,题目说的很清楚,在Mr.Wang进行所有的选择之后,房间中剩下的男孩之间的关系必须是直接或者间接的朋友关系,除非,房间中只有一个男孩,那么就意味着,n=0时,Mr.Wang可保留下来的男孩数目为1。

二、这个题目的男孩的编号取值范围在1~1e7,这里,千万别被1e7的数量级给吓住了,如果这里使用map映射,恰巧就中了出题人的下怀,因为这题使用map会超时,原因可能是频繁的进行查找,map的速度毕竟不能达到数组下标直接访问这么快,所以,直接开数组就行,一个1e7的整型数组大小,emmmmm我也不知道大概多大,如果照理论上来算,一个整型4字节1e7大概也就是40000KB左右也就是大约40MB,并没有超过128MB的限制,所以,这题说白了就是在考编程者是否熟悉程序测试的内存限制= =

三、关于最大值的获得问题,可以定义一个数组存储当前结点为头结点时集合结点的数量,在并查集合并A和B的过程中,新头结点A的集合数量就等于原来A的数量+原来B的数量,再定义一个maxnum变量进行比较存储即可~   当然,等所有结点合并完,再统计相同头结点的数量,最终获得所有集合中结点数量最多的结点也是可以的,就是稍微费了一丢丢时╮(๑•́ ₃•̀๑)╭

正确代码

#include <cstdio>
#include <vector>
#include <utility>
using namespace std;
const int maxn=10000010;
int father[maxn]={0},num[maxn];
int maxnum;

int findFather(int a)
{
	int x=a;
	while(x!=father[x])
	{
		x=father[x];
	}
	while(a!=father[a])
	{
		int z=a;
		a=father[a];
		father[z]=x;
	}
	return x;
}
void Union(int a, int b)
{
	int A=findFather(a);
	int B=findFather(b);
	if(A!=B)
	{
		father[A]=B;
		num[B]+=num[A];
		if(maxnum<num[B])
			maxnum=num[B];
	}
}
void init(int n)
{
	father[n]=n;
	num[n]=1;
}
int main()
{
	int n,dot1,dot2;
	vector<pair<int,int> > input;
    while(~scanf("%d",&n))
    {
    	if(n==0)
    	{
    		printf("1\n");
    		continue;
		}
    	input.clear();
    	for(int i=0;i<n;++i)
    	{
    		scanf("%d %d",&dot1,&dot2);
			init(dot1);
			init(dot2);
			input.push_back(make_pair(dot1,dot2));
		}
		maxnum=0;
		for(int i=0;i<input.size();++i)
		{
			Union(input[i].first,input[i].second);
		}
		printf("%d\n",maxnum);
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a845717607/article/details/81611408
今日推荐