1. 程式人生 > >HDU - 1856 並查集,尋找最大集合元素個數

HDU - 1856 並查集,尋找最大集合元素個數

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int fa[10000000];
int mark[10000000];
int findroot(int x)
{
    if(fa[x] == x)
        return x;
    else
        return fa[x] = findroot(fa[x]);
}
void merge(int x , int y)
{
    int fax = findroot(x);
    int fay = findroot(y);
    if(fax != fay)
    {
        fa[fay] = fax;
        mark[fax] += mark[fay];
    }
}
int main(void)
{
    int n ;
    while(scanf("%d",&n)!=EOF)
    {
        int x , y;
        int ans = 1;
        for(int i = 0 ; i <= 10000000 ; i ++)
        {
            fa[i] = i;
            mark[i] = 1;
        }
        int maxn  = 0;
        int flag;
        for(int i = 1 ; i <= n ; i ++)
        {
            scanf("%d %d",&x, &y);
            flag = max(x,y);
            maxn = max(maxn,flag);
            merge(x , y);
        }
        for(int i = 1 ; i <= maxn; i ++)
        {
            if(mark[i] > ans)
                ans = mark[i];
        }
        printf("%d\n",ans);
    }
    return 0;
}