码迷,mamicode.com
首页 > 其他好文 > 详细

[HDU - 1856]More is better

时间:2019-08-20 22:14:47      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:friend   nbsp   return   for   efi   print   friends   include   names   

并查集求最大集合中元素数量

#include <cstdio>
#include <cstring>
#define maxn 10000000 + 5
using namespace std;
struct friends
{
    int root;
    int num;
}p[maxn];
void init()
{
    for (int i = 1; i <= maxn; i++)
    {
        p[i].root = i;
        p[i].num = 1;
    }
}
int Find(int x)
{
    return p[x].root == x ? x : (p[x].root = Find(p[x].root));
}
void Join(int x, int y)
{
    int fx = Find(x), fy = Find(y);
    if (fx != fy)
    {
        p[fx].root = fy;
        p[fy].num += p[fx].num;
        //printf("%d %d %d %d\n", fx, fy, p[fy].num, p[fx].num);
    }
}
int main()
{
    int n, m;
    while (~scanf("%d", &n))
    {
        if(n == 0)
        {
             printf("1\n");
             continue;
        }
        init();
        for (int i = 0; i < n; i++)
        {
            int temp1, temp2;
            scanf("%d %d", &temp1, &temp2);
            Join(temp1, temp2);
        }
        int maxnum = 0;
        for (int i = 1; i <= maxn; i++)
            //printf("%d\n", p[i].num);
            if (Find(i) == i)
            {
                if (p[i].num > maxnum)
                    maxnum = p[i].num;

            }
        printf("%d\n", maxnum);

    }

    return 0;
}

 

[HDU - 1856]More is better

标签:friend   nbsp   return   for   efi   print   friends   include   names   

原文地址:https://www.cnblogs.com/Vikyanite/p/11385556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!