数据结构——并查集

目录

一.并查集原理

二.并查集的实现

三.并查集的应用

1.省份数量

2.等式方程的可满足性


一.并查集原理

        在一些应用问题中,需要将n个不同的元素划分成一些不相交的集合开始时,每个元素自成一个单元素集合,然后按一定的规律将归于同一组元素的集合合并。在此过程中要反复用到查询某一 个元素归属于那个集合的运算。适合于描述这类问题的抽象数据类型称为并查集(union-find set)

        比如:某公司今年校招全国总共招生10人,西安招4人,成都招3人,武汉招3人,10个人来自不同的学校,起先互不相识,每个学生都是一个独立的小团体,现给这些学生进行编号:{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 给以下数组用来存储该小集体,数组中的数字代表:该小集体中具有成员的个数

        毕业后,学生们要去公司上班,每个地方的学生自发组织成小分队一起上路,于是: 西安学生小分队s1={0,6,7,8},成都学生小分队s2={1,4,9},武汉学生小分队s3={2,3,5}就相互认识 了,10个人形成了三个小团体。假设右三个群主0,1,2担任队长,负责大家的出行

        一趟火车之旅后,每个小分队成员就互相熟悉,称为了一个朋友圈

        从上图可以看出:编号6,7,8同学属于0号小分队,该小分队中有4人(包含队长0);编号为4和9的同学属于1号小分队,该小分队有3人(包含队长1),编号为3和5的同学属于2号小分队,该小分队有3个人(包含队长1)

观察数组内数字,可以得出以下结论:

  1. 数组的下标对应集合中元素的编号
  2. 数组中如果为负数,负号代表根,数字代表该集合中元素个数
  3. 数组中如果为非负数,代表该元素双亲在数组中的下标

        在公司工作一段时间后,西安小分队中8号同学与成都小分队1号同学奇迹般的走到了一起,两个小圈子的学生相互介绍,最后成为了一个小圈子:

通过以上例子可知,并查集一般可以解决一下问题:

  1. 查找元素属于哪个集合:沿着数组表示树形关系以上一直找到根(即:树中中元素为负数的位置)
  2. 查看两个元素是否属于同一个集合:沿着数组表示的树形关系往上一直找到树的根,如果根相同表明在同一个集合,否则不在
  3. 将两个集合归并成一个集合:将两个集合中的元素合并, 将一个集合名称改成另一个集合的名称
  4. 集合的个数:遍历数组,数组中元素为负数的个数即为集合的个数

二.并查集的实现

class UnionFindSet
{
public:
	UnionFindSet(size_t n) :_ufs(n, -1)
	{ }

	int FindRoot(int x)
	{
		int root = x;
		while (_ufs[root] >= 0)
			root = _ufs[root];

		//路径压缩
		while (_ufs[x] >= 0)
		{
			int parent = _ufs[x];
			_ufs[x] = root;
			x = parent;
		}

		return root;
	}

	bool Union(int x1, int x2)
	{
		int root1 = FindRoot(x1);
		int root2 = FindRoot(x2);

		if (root1 == root2)//x1和x2本来就在一个集合中
			return false;

		//数据量小的向大的合并
		if (abs(_ufs[root1]) < abs(_ufs[root2]))
			swap(root1, root2);

		_ufs[root1] += _ufs[root2];
		_ufs[root2] = root1;
		return true;
	}

	bool InSet(int x1, int x2)
	{
		return FindRoot(x1) == FindRoot(x2);
	}

	size_t SetSize()
	{
		size_t n = 0;
		for (auto& e : _ufs)
		{
			if (e < 0)
				++n;
		}
		return n;
	}
private:
	vector<int> _ufs;
};

三.并查集的应用

1.省份数量

https://leetcode.cn/problems/bLyHh0/description/

这道题使用并查集解决,通过遍历,如果isConnected[i][j]==1的话就合并在一起

class UnionFindSet
{
public:
	UnionFindSet(size_t n) :_ufs(n, -1)
	{ }

	int FindRoot(int x)
	{
		int root = x;
		while (_ufs[root] >= 0)
			root = _ufs[root];

		//路径压缩
		while (_ufs[x] >= 0)
		{
			int parent = _ufs[x];
			_ufs[x] = root;
			x = parent;
		}

		return root;
	}

	bool Union(int x1, int x2)
	{
		int root1 = FindRoot(x1);
		int root2 = FindRoot(x2);

		if (root1 == root2)//x1和x2本来就在一个集合中
			return false;

		//数据量小的向大的合并
		if (abs(_ufs[root1]) < abs(_ufs[root2]))
			swap(root1, root2);

		_ufs[root1] += _ufs[root2];
		_ufs[root2] = root1;
		return true;
	}

	bool InSet(int x1, int x2)
	{
		return FindRoot(x1) == FindRoot(x2);
	}

	size_t SetSize()
	{
		size_t n = 0;
		for (auto& e : _ufs)
		{
			if (e < 0)
				++n;
		}
		return n;
	}
private:
	vector<int> _ufs;
};

class Solution {
public:
    int findCircleNum(vector<vector<int>>& isConnected) {
        UnionFindSet ufs(isConnected.size());
        for(int i=0;i<isConnected.size();++i)
        {
            for(int j=0;j<isConnected[i].size();++j)
            {
                if(isConnected[i][j]==1)
                    ufs.Union(i,j);
            }
        }
        return ufs.SetSize();
    }
};

2.等式方程的可满足性

https://leetcode.cn/problems/satisfiability-of-equality-equations/description/

这道题使用并查集解决,我们首先判断第一次出现的符号是=还是!,如果是=就将两个值放入集合中,遇到!时就判断有没有相等的值,如果有相等的值同时在=和!中,就互斥

class UnionFindSet
{
public:
	UnionFindSet(size_t n) :_ufs(n, -1)
	{ }

	int FindRoot(int x)
	{
		int root = x;
		while (_ufs[root] >= 0)
			root = _ufs[root];

		//路径压缩
		while (_ufs[x] >= 0)
		{
			int parent = _ufs[x];
			_ufs[x] = root;
			x = parent;
		}

		return root;
	}

	bool Union(int x1, int x2)
	{
		int root1 = FindRoot(x1);
		int root2 = FindRoot(x2);

		if (root1 == root2)//x1和x2本来就在一个集合中
			return false;

		//数据量小的向大的合并
		if (abs(_ufs[root1]) < abs(_ufs[root2]))
			swap(root1, root2);

		_ufs[root1] += _ufs[root2];
		_ufs[root2] = root1;
		return true;
	}

	bool InSet(int x1, int x2)
	{
		return FindRoot(x1) == FindRoot(x2);
	}

	size_t SetSize()
	{
		size_t n = 0;
		for (auto& e : _ufs)
		{
			if (e < 0)
				++n;
		}
		return n;
	}
private:
	vector<int> _ufs;
};

class Solution {
public:
    bool equationsPossible(vector<string>& equations) {
        UnionFindSet ufs(26);
        //将相等的值放进对应的集合
        for(auto& str:equations)
        {
            if(str[1]=='=')
            {
                ufs.Union(str[0]-'a',str[3]-'a');
            }
        }

        //判断不等的值如果在一个集合,就互斥冲突
        for(auto& str:equations)
        {
            if(str[1]=='!')
            {
                if(ufs.FindRoot(str[0]-'a')==ufs.FindRoot(str[3]-'a'))
                    return false;
            }
        }
        return true;
    }
};

评论 64
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值