HDU 1856-More is better

来源:互联网 发布:华腾软件 编辑:程序博客网 时间:2024/06/10 02:28

More is better

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


题目链接:点击打开链接


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.


题意:
有 10000000 个人,现在给你n组人的直接朋友关系,每组 a 和 b 表示 a 和 b 是直接的好朋友,间接的朋友也算是朋友,问最多的朋友团体有多少人


分析:
本题有用并查集,但要注意两点,第一在Find函数中要有路径压缩,不然的话就会超时。第二,如果 n 为 0,则最多的朋友团体为 1.因为要求最多元素的集合,所以要记录下团体的元素数量,便于判断,同时也省时间。





#include <iostream>#include<stdio.h>using namespace std;int pre[10000010],s[10000010],sum;int Find(int x){    /*if(pre[x]==x)        return x;    else        return Find(pre[x]);*/    int t,r;    r=x;    while(r!=pre[r])        r=pre[r];    while(x!=r)    {        t=pre[x];        pre[x]=r;        x=t;    }    return r;}void pei(int x,int y){    int f1=Find(x);    int f2=Find(y);    if(f1!=f2)    {        pre[f1]=f2;        s[f2]+=s[f1];        if(s[f2]>sum)            sum=s[f2];    }}int main(){    int n,a,b;    while(~scanf("%d",&n))    {        for(int i=1;i<=10000000;i++)        {            pre[i]=i;            s[i]=1;        }        sum=1;        while(n--)        {            scanf("%d %d",&a,&b);            pei(a,b);        }        printf("%d\n",sum);    }    return 0;}



原创粉丝点击