C++ 实现并查集

并查集是一种用于处理不相交集合的操作的数据结构,常用于判断元素是否属于同一集合及合并集合。文章通过公司招聘和学生团队的例子介绍了并查集的原理,包括查找元素所属集合、判断元素间关系和合并集合。并提供了C++实现的代码示例,展示了如何使用并查集解决实际问题,如在力扣平台上的图论问题。
摘要由CSDN通过智能技术生成

目录

1. 并查集原理

2. 并查集实现

3. 并查集应用


1. 并查集原理

在一些应用问题中,需要 n 个不同的元素划分成一些不相交的集合 开始时,每个元素自成一个
单元素集合,然后按一定的规律将归于同一组元素的集合合并 。在此过程中 要反复用到查询某一
个元素归属于那个集合的运算 。适合于描述这类问题的抽象数据类型称为 并查集 (union-fifind
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 号同学奇迹般的走到了一起,两个 小圈子的学生相互介绍,最后成为了一个小圈子:

现在 0 集合有 7 个人, 2 集合有 3 个人,总共两个朋友圈。
通过以上例子可知,并查集一般可以解决一下问题
1. 查找元素属于哪个集合
沿着数组表示树形关系以上一直找到根 ( 即:树中中元素为负数的位置 )
2. 查看两个元素是否属于同一个集合
沿着数组表示的树形关系往上一直找到树的根,如果根相同表明在同一个集合,否则不在
3. 将两个集合归并成一个集合
  • 将两个集合中的元素合并
  • 将一个集合名称改成另一个集合的名称

集合的个数

遍历数组,数组中元素为负数的个数即为集合的个数 

2. 并查集实现

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class UnionFindset
{

public:
    //初始化的时候将所有元素都这只成1
    UnionFindset(size_t size) : _ufs(size, -1) {}
    //给元素一个编号,找到元素所在的的集合名称
    int FindRoot(int index)
    {

        while (_ufs[index] >= 0)
        {
            index = _ufs[index];
        }
        return index;
    }

    bool Union(int x1, int x2)
    {

        int root1 = FindRoot(x1);
        int root2 = FindRoot(x2);

        if (root1 == root2)
            return false;
        //将两个集合中元素合并
        _ufs[root1] += _ufs[root2];

        //将其中一个集合名称改变成另一个名称
        _ufs[root2] = root1;
        return true;
    }
    // 数组中负数的个数,即为集合的个数
    size_t Count() const
    {

        size_t count = 0;

        for (auto e : _ufs)
        {
            if (e < 0)
                count++;
        }
        return count;
    }

    int &operator[](int index)
    {
        if (index >= _ufs.size())
        {
            _ufs.resize(_ufs.size() * 2);
        }
        return _ufs[index];
    }

private:
    vector<int> _ufs;
};

int main()
{
    // vector<int> v(5, -1);
    // vector<int> v1(2,4);
    // vector<int> v2(3,5);
    // v1+v2;
    UnionFindset u(10);
    u[0] = -4;
    u[1] = -3;
    u[2] = -3;
    u[3] = 2;
    u[4] = 1;
    u[5] = 2;
    u[6] = 0;
    u[7] = 0;
    u[8] = 0;
    u[9] = 1;
    int index = u.FindRoot(8);
    cout << index << endl;
    cout << u.Count() << endl;

    bool ans = u.Union(1, 8);
    cout << ans << endl;

    cout << u.Count() << endl;

    system("pause");
    return 0;
}

3. 并查集应用

        力扣

#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <map>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <deque>
using namespace std;

void PrintVector2D(const vector<vector<int>> &array)
{

    for (const auto &row : array)
    {
        cout << "[";
        for_each(row.begin(), row.end(), [](int num)
                 { cout << num << " "; });
        cout << "]";
        cout << endl;
    }
}

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(nullptr), right(nullptr) {}
};

class Solution
{
public:
    int findCircleNum(vector<vector<int>> &isConnected)
    {
        vector<int> ufs(isConnected.size(), -1);
        //查找根
        auto findRoot = [&ufs](int x)
        {
            while (ufs[x] >= 0)
            {
                x = ufs[x];
            }
            return x;
        };
        for (size_t i = 0; i < isConnected.size(); i++)
        {
            for (size_t j = 0; j < isConnected[i].size(); j++)
            {
                if (isConnected[i][j] == 1)
                {
                    int root1 = findRoot(i);
                    int root2 = findRoot(j);
                    if (root1 != root2)
                    {
                        ufs[root1] += ufs[root2];
                        ufs[root2] = root1;
                    }
                }
            }
        }
        int n = 0;
        for (auto e : ufs)
        {
            if (e < 0)
                ++n;
        }
        return n;
    }
};

int main()
{

    Solution s;
    vector<vector<int>> isConnected = {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}};
    int x = s.findCircleNum(isConnected);
    cout << x << endl;

    system("pause");
    return 0;
}

        力扣

class Solution {
public:
    bool equationsPossible(vector<string>& equations) {
        vector<int> ufs(26,-1);

    //查出并查集的lambda 
        auto findRoot=[&ufs](int x){
            while(ufs[x]>=0)
                x=ufs[x];
            return x;
        };

        for(auto &str:equations){

           if(str[1]=='='){
               int root1=findRoot(str[0]-'a');
               int root2=findRoot(str[3]-'a');
               if(root1!=root2){

                   ufs[root1]+=ufs[root2];
                   ufs[root2]=root1;
               }
           }

        }

        for(auto &str:equations){

            if(str[1]=='!'){
                int root1=findRoot(str[0]-'a');
                int root2=findRoot(str[3]-'a');
                if(root1==root2){
                    return false;
                }
            }

        }
        return true;


    }
};

 

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值