并查集C++实现

#include <iostream>

using namespace std;
class UF    {
	//cnt is the number of disjoint sets.
	//id is an array that records distinct identity of each set,when two sets are merged ,their id will be same.
	//sz is an array that records the child number of each set including the set self.
	int *id, cnt, *sz;
public:
	// Create an empty union find data structure with N isolated sets.
	UF(int N)   {
		cnt = N;
		id = new int[N];
		sz = new int[N];
		for (int i = 0; i<N; i++)	{
			id[i] = i;
			sz[i] = 1;
		}
	}
	~UF()	{
		delete[] id;
		delete[] sz;
	}
	// Return the id of component corresponding to object p.
	int find(int p)	{
		
		if (p != id[p]){
			id[p] = find(id[p]);
		}
		return id[p];
	}
	// Replace sets containing x and y with their union.
	void merge(int x, int y)	{
		int i = find(x);
		int j = find(y);
		if (i == j) return;

		// make smaller root point to larger one
		if (sz[i] < sz[j])	{
			id[i] = j;
			sz[j] += sz[i];
		}
		else	{
			id[j] = i;
			sz[i] += sz[j];
		}
		cnt--;
	}
	// Are objects x and y in the same set?
	bool connected(int x, int y)    {
		return find(x) == find(y);
	}
	// Return the number of disjoint sets.
	int count() {
		return cnt;
	}
};

void main(){
	UF test(5);
	test.merge(2, 3);
	test.merge(3, 4);
	cout << test.find(4);
	cout << test.count();
}

转载于:https://www.cnblogs.com/muyangshaonian/p/9650520.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值