左神算法课——并查集c++实现

class UnionFindSet
{
private:
	hash_map<char, char>fatnerMap;
	hash_map<char, int>sizeMap;
public:
	UnionFindSet(vector<char>data);
	char findHead(char cur);//找代表结点
	bool isSame(char a, char b);//是否同集合
	void Union(char a, char b);//合并
};
UnionFindSet::UnionFindSet(vector<char>data)
{
	fatnerMap.clear();
	sizeMap.clear();
	for (auto var : data)
	{
		fatnerMap.insert(pair<char, char>(var, var));
		sizeMap.insert(pair<char, int>(var, 1));
	}
}
char UnionFindSet::findHead(char cur)
{
	stack<char>s;
	while (fatnerMap[cur] != cur)
	{
		s.push(cur);
		cur = fatnerMap[cur];
	}
	while (!s.empty())
	{
		fatnerMap[s.top()] = cur;//扁平化处理
		s.pop();
	}
	return cur;
}

bool UnionFindSet::isSame(char a, char b)
{
	return findHead(a) == findHead(b);
}
void  UnionFindSet::Union(char a, char b)
{
	char p1 = findHead(a);
	char p2 = findHead(b);
	if (p1 == p2)
		return;
	if (p1 == NULL || p2 == NULL)
		return;
	else
	{
		int num1 = sizeMap[p1];
		int num2 = sizeMap[p2];
		if (num1 <= num2)
		{
			fatnerMap[p1] = p2;
			sizeMap[p2] = num1 + num2;
		}
		else
		{
			fatnerMap[p2] = p1;
			sizeMap[p1] = num1 + num2;
		}
	}
}

你可能感兴趣的:(编程学习,数据结构与算法)