栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【数据结构】并查集

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构】并查集

文章目录
      • 一、引言
      • 二、C++实现
      • 三、测试

一、引言

并查集的相关介绍

二、C++实现
#include
using namespace std;

class Ufset
{
private:
	int* parent;
	size_t size;	//parent对象的个数
private:
	void Showchild(int child)const
	{
		cout << child << " ";
		for (int i = 0; i < size; ++i)
		{
			if (child == parent[i])
			{
				Showchild(i);
			}
		}
	}
public:
	Ufset(int sz) :parent(new int[sz]), size(sz)
	{
		for (int i = 0; i < size; ++i)
		{
			parent[i] = -1;
		}
	}
	~Ufset()
	{
		if (nullptr != parent)
		{
			delete[] parent;
			size = 0;
		}
	}
	//查找根节点
	int FindRoot(int child)const
	{
		while (parent[child] >= 0)
		{
			child = parent[child];
		}
		return child;
	}
	//并集
	bool Union(int cha, int chb)
	{
		bool res = false;
		//求得两个对象的根
		int left = FindRoot(cha);
		int right = FindRoot(chb);
		//两个未在同一个根下
		if (left != right)
		{
			parent[left] += parent[right];
			parent[right] = left;
			res = true;
		}
		return true;
	}
	//输出所有的集合
	void ShowAllSet()const
	{
		int si = 1;
		for (int i = 0; i < size; ++i)
		{
			//根节点
			if (parent[i] < 0)
			{
				cout << "set" << si++ << ": ";
				Showchild(i);
				cout << endl;
			}
		}
	}
};
三、测试
//测试
int main()
{
	Ufset s(12);
	s.Union(0, 4);
	s.Union(3, 1);
	s.Union(6, 10);
	s.Union(8, 9);
	s.Union(7, 4);
	s.Union(6, 8);
	s.Union(3, 5);
	s.Union(2, 11);
	s.Union(11, 0);
	s.ShowAllSet();
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/934534.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号