左神算法学习日记——并查集

并查集实现 

#include<vector>
#include<hash_map>
using namespace std;

class unionfinset
{
private:
	hash_map<char, char> father;
	hash_map<char, int> size;
public:
	unionfinset() = default;
	unionfinset(vector<char> data)//用数组data初始化并查集
	{
		father.clear();
		size.clear();
		for (char var:data)
		{
			father.insert({ var, var });
			size.insert({var,1});
		}
	}
	char findrep(char node)
	{
		char f = father[node];
		if (node != f)
		{
			node = f;
			f = findrep(node);//通过递归来传递代表结点
		}
		father[node] = f;//将所有结点的父节点都设为代表结点
		return f;
	}
	bool issameset(char a, char b)
	{
		return findrep(a) == findrep(b);
	}
	void Union(char a, char b)
	{
		char arep = findrep(a);
		char brep = findrep(b);
		if (arep != brep)
		{
			int asize = size[arep];
			int bsize = size[brep];
			if (asize > bsize)
			{
				father[b] = a;
				size[a] += size[b];
			}
			else
			{
				father[a] = b;
				size[b] += size[a];
			}
		}
	}
};

int main()
{
	vector<char> temp = { 'A', 'B', 'C', 'D', 'E', 'H', 'G' };
	unionfinset s(temp);
	s.Union('A', 'B');
	cout << s.issameset('A', 'B');
}

猜你喜欢

转载自blog.csdn.net/w275412237/article/details/89404920