六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 42|回复: 0

HDU_1856_More is better

[复制链接]

升级  68.4%

272

主题

272

主题

272

主题

进士

Rank: 4

积分
842
 楼主| 发表于 2013-2-1 11:23:39 | 显示全部楼层 |阅读模式
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;        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, con = 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;}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表