hdu1856

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=10000500;
int pre[maxn],num[maxn];
void creat()
{
    for(int i=0;i<maxn;i++)
    {
        pre[i]=i;
        num[i]=1;
    }
}
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==0)
        {
            puts("1");
            continue;
        }
        maxx=-1;
        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 0;
}

转载于:https://www.cnblogs.com/qiuhua7777/p/9657442.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值