HDU-1856 More is better

HDU-1856 More is better

题目大意:朋友在一个集合,朋友的朋友也是朋友,求元素最多的集合的元素个数。

#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
int fa[10000010] = {0};
int ranks[10000010] = {0};
int getfather(int v)
{
    return (fa[v] == v) ? v : fa[v] = getfather(fa[v]);
}
void merge(int x,int y)
{
    x = getfather(x);
    y = getfather(y);
    if (x != y)
    {
        fa[x] = y;
        ranks[y] += ranks[x];
    }
}
int main(){
    int n;
    while(cin >> n)
    {
        if (n == 0)
            cout << 1 << endl;
        else
        {
            int cnt = 0;
            int maxnum = 0;
            for (int i = 1; i <= 10000000; i++)
            {
                fa[i] = i;
                ranks[i] = 1;
            }
            for (int i = 0; i < n; i++)
            {
                int a,b;
                cin >> a >> b;
                if (a > maxnum) maxnum = a;
                if (b > maxnum) maxnum = b;
                merge(a,b);
            }
            int maxn = 0;
            for (int i = 1; i <= maxnum; i++)
            {
                if (ranks[i] > maxn)
                    maxn = ranks[i];
            }       
            cout << maxn << endl;
        }
    }
    return 0;
}

你可能感兴趣的:(并查集,hdoj-1856,More-is-be)