hdu1856

时间:2021-10-16 16:20:16

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.

4

1 2

3 4

5 6

1 6

4

1 2

3 4

5 6

7 8

4

2

解:这个题是一个并查集的题,标记的红色字体是题目的关键,他只想留住有朋友关系的人。但是当n等于0时,也就是所有的人都互不认识的时候,就随机找一个人留下,当时这一点没有看到。当时看题目以为是如果所有人中的若干个人是朋友关系,就选出任意两个;如果一个人与其他的人无关系就让这个人留下,结果看到给出的例子纠结了好久,不知道哪里错了。正确的是合并两个人的时候判断一下两个人是否已经直接或者间接有朋友关系,再合并一下这个集合中所包含元素的个数,找出最大的集合人数。所以做题的时候不能看到题目想当然,结合数据理解题意。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const
int maxn=;
int
pre[maxn],num[maxn];
void
creat()
{

for
(int i=;i<maxn;i++)
{

pre[i]=i;
num[i]=;
}
}

int
findroot(int root)
{

if
(root==pre[root])
return
root;
pre[root]=findroot(pre[root]);
return
pre[root];
}

int
main()
{

int
t,n,m,maxx;
while
(scanf("%d",&t)!=EOF)
{

if
(t==)
{

puts("1");
continue
;
}

maxx=-;
creat();
while
(t--)
{

scanf("%d %d",&n,&m);
int
root1=findroot(n);
int
root2=findroot(m);
if
(root1!=root2)
{

if
(root1<root2)
swap(root1,root2);
pre[root2]=root1;
num[root1]+=num[root2];
maxx=max(maxx,num[root1]);
}
}

printf("%d\n",maxx);
}

return
;
}

相关文章