CSU 1045: 并查集(带权并查集)

CSU 1045: 并查集 带权并查集

Description

大一的学一下,大二以上还不会并查集的统统去面壁。

Input

多组数据,每组第一行两个正整数n,m,表示有1~n这n个编号,m个关系。

接下来m行,每行两个数i, j, 1 <= i, j <= n,表示i和j是一组的。

每个编号自己和自己是一组的。

1 < n < 1000000 ,1 < m < 100000 。

Output

每组数据输出一行,一个数,表示组员最多的组的组员个数。

Sample Input

10 5
1 2
3 5
2 6
4 7
9 6

Sample Output

4

Hint

Source

中南大学2012年暑期集训队选拔赛

思路: 带权并查集

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int f[1000005];
int n,m;
int a,b;
int father(int x)
{
    if(f[x] <=0 )
        return x;
    else
        return f[x] = father(f[x]);
}
void union_(int a,int b)
{
    int root1 = father(a);
    int root2 = father(b);
    if(root1 == root2)
        return;
    f[root1] += f[root2];
    f[root2] = root1;
}
int main()
{
    while(scanf("%d%d",&n,&m) != EOF)
    {
        memset(f,-1,sizeof(f));
        for(int i = 0 ; i < m ; i++)
            scanf("%d%d",&a,&b),union_(a,b);
        int minx = 0;
        for(int i = 1 ; i <= n ; i++)
            minx = min(minx,f[i]);
        printf("%d\n",-minx);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值