hdu1856: More is better

hdu1856: http://acm.hdu.edu.cn/showproblem.php?pid=1856
题意:输入n对朋友,求最多的朋友集合(直接或间接为朋友) 解法:并查集:集合的合并及查询。 code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
const int maxn=10000002;
int fa[maxn],ans[maxn];
int find(int x)   //路径压缩,复杂度为常数
{
    int fx=fa[x];
    if(x!=fx)fa[x]=find(fx);
    return fa[x];
}
int main()
{
    int n,a,b,x,y;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<maxn;i++)
        {
            fa[i]=i;
            ans[i]=1;
        }
        for(int i=1;i<=n;i++)
        {
            scanf("%d%d",&a,&b);
            x=find(a);y=find(b);
            if(x!=y)
            {
                fa[x]=y;
                ans[y]=ans[y]+ans[x];    //集合合并
            }
        }
        int max=0;
        for(int i=0;i<maxn;i++)
        {
            if(fa[i]==i)
            {
                if(ans[i]>max)
                    max=ans[i];
            }
        }
        printf("%d\n",max);
    }
}
/*input:
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8
output:
4
2
*/

posted on 2012-07-25 20:54  acmer-jun  阅读(185)  评论(0编辑  收藏  举报

导航