并查集求集合个数和每个集合中的元素个数

思路:维护一个数组,代表以某个结点为根的树的结点数目,初始化为全1。在合并两个集合时,将秩较小的集合的元素数目加到秩较大的集合上。这里需要注意一下,就是Union过程处理两个祖先相同的结点,此时实际上没有真正的合并这两个结点,所以不需要更新集合的元素数目。至于统计集合个数就比较简单了,直接扫描一遍所有的结点,如果某个结点的祖先结点不是它自己,说明该结点是某个集合的祖先元素,统计这种结点个数即可。

代码:

// 1389.cpp : 定义控制台应用程序的入口点。
// 并查集,求每个集合中的元素个数
// 在合并时将子树中的结点数目加到根结点

#include "stdafx.h"
#include <iostream>
#include <cstdio>

#define MAX 100000+5

int father[MAX]; //父节点
int people[MAX]; //每个集合中的元素个数
int rank[MAX]; //秩

int find(int x) 
{
	if (x != father[x])
		father[x] = find(father[x]);

	return father[x];
}

//合并并返回合并后的祖先序号
void Union(int x, int y) 
{
	x = find(x);
	y = find(y);

	if (rank[x] > rank[y])
	{
		father[y] = x;

		//两者祖先相同时,实际没发生合并,只考虑祖先不同的情况
		if (x != y)
			people[x] += people[y];
	}
	else
	{
		father[x] = y;
		
		//两者祖先相同时,实际没发生合并,只考虑祖先不同的情况
		if (x != y)
			people[y] += people[x];

		if (rank[x] == rank[y]) //树高相同时让父节点的树高值加一
			rank[y] += 1;
	}
}

//计算集合的个数
int count_sets(int n)
{
	int cnt = 0;
	for (int i = 1; i <= n; i++)
		if (find(i) == i)
			cnt++;

	return cnt;
}

int main()
{
	int n, m;
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++)
	{
		father[i] = i;
		people[i] = 1;
		rank[i] = 0;
	}

	char cmd;
	int x, y;
	while (m--)
	{
		getchar();
		scanf("%c", &cmd);
		if (cmd == 'M')
		{
			scanf("%d %d", &x, &y);
			Union(x, y);
		}
		else if (cmd == 'Q')
		{
			scanf("%d", &x);
			printf("%d\n", people[find(x)]);
		}
	}

	printf("集合个数:%d\n", count_sets(n));

	system("pause");
	return 0;
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值