CSU1045: 并查集

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

并查集模板题

#include <iostream>  
#include <cmath>
#include <math.h>  
#include <string.h> 
#include <string> 
#include <algorithm>
#include <queue>
using namespace std;
int fa[1000005];
int num[1000005];
int n, m;
void init()
{
	for (int i = 0; i < n; i++)
	{
		fa[i] = i;
		num[i] = 1;
	}
	return;
}
int find(int x)
{
	if (fa[x] == x)
		return x;
	return fa[x] = find(fa[x]);
}
void join(int x, int y)
{
	int fx = find(x);
	int fy = find(y);
	if (fx != fy)
	{
		fa[fx] = fy;
		num[fy] += num[fx];
	}
	return;
}
int main()
{
	while (cin >> n >> m)
	{
		int a, b;
		init();
		for (int i = 0; i < m; i++)
		{
			cin >> a >> b;
			join(a, b);
		}
		sort(num, num + n + 1);
		cout << num[n] << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值