`

HDU_1856_More is better

阅读更多
http://acm.hdu.edu.cn/showproblem.php?pid=1856


简单的并查集
题意:给出在同一个集合的2个元素,问最后那个最多元素的集合有多少个元素,注意,每个元素可以独立存在,因此至少有1个


#include <iostream>
using namespace std;

int pre[10000005], con[10000005];

int find (int a)
{
    int b = a;
    while (a != pre[a])
        a = pre[a];
    while (b != a)
    {
        int t = b;
        b = pre[b];
        pre[t] = a;
    }
    return a;
}
int main()
{
    int n, i, a, b, A, B, res;
    while (scanf ("%d", &n) != EOF)
    {
        res = 1;    //这里初始化一定是1,因为下面的合并操作有可能一次都不执行,况且至少每个集合有1个人
        for (i = 1; i <= 10000000; i++)
            pre[i] = i, con[i] = 1;
        for (i = 0; i < n; i++)
        {
            scanf ("%d%d", &a, &b);
            A = find (a);
            B = find (b);
            if (A != B)
            {
                pre[B] = A;
                con[A] += con[B];
                if (res < con[A])
                    res = con[A];
            }
        }
        printf ("%d\n", res);
    }
    return 0;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics