首页 > 代码库 > hdu 1856 More is better

hdu 1856 More is better

题目:

    链接:点击打开链接

题意:

    给出n个直接认识的朋友,最大的直接或间接认识的朋友。

思路:

算法:

    并查集,,,

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define MAXN 100010

int root[MAXN];
int member[MAXN];//表示在i结点处的,认识的朋友

int find(int x)
{
    return x == root[x] ? x : root[x] = find( root[x] );
}

void merge(int x,int y)
{
    int fx = find(x);
    int fy = find(y);
    if(fx != fy)
    {
        root[fx] = fy;
        member[fy] += member[fx];
    }
}

int main()
{
    //freopen("input.txt","r",stdin);
    int n,a,b;
    int fa,maxn;
    while(scanf("%d",&n) != EOF)
    {
        for(int i=0; i<MAXN; i++)
        {
            root[i] = i;
            member[i] = 1;
        }
        fa = 1;
        for(int i=0; i<n; i++)
        {
            scanf("%d%d",&a,&b);
            if(a>fa || b>fa)
                fa = max(a,b);
            merge(a,b);
        }
        maxn = 0;
        for(int i=1; i<=fa; i++)
        {
            if(member[i] > maxn)
                maxn = member[i];
        }
        printf("%d\n",maxn);
    }
    return 0;
}