【数据结构】并查集算法总结

知识概览

并查集主要解决两个问题:

  1. 将两个集合合并

  2. 询问两个元素是否在一个集合当中

上面两个操作的时间复杂度近乎O(1)。

并查集的基本原理:每个集合用一棵树表示。树根的编号就是整个集合的编号。每个节点存储它的父节点。px表示x的父节点。

问题1:如何判断树根:if (px == x)

问题2:如何求x的集合编号:while (px != x) x = px;

问题3:如何合并两个集合:px是x的集合编号,py是y的集合编号,则ppx = py

优化:路径压缩

例题展示

题目链接

合并集合

https://www.acwing.com/problem/content/838/

代码

cpp 复制代码
#include <iostream>

using namespace std;

const int N = 100010;

int n, m;
int p[N];

int find(int x)  // 返回x的祖宗节点 + 路径压缩
{
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int main()
{
    scanf("%d%d", &n, &m);
    
    for (int i = 1; i <= n; i++) p[i] = i;
    
    while (m--)
    {
        char op[2];
        int a, b;
        scanf("%s%d%d", op, &a, &b);
        
        if (op[0] == 'M') p[find(a)] = find(b);
        else
        {
            if (find(a) == find(b)) puts("Yes");
            else puts("No");
        }
    }
    
    return 0;
}

题目链接

连通块中点的数量

https://www.acwing.com/problem/content/839/

题解

并查集中需要维护集合中点的数量。

代码

cpp 复制代码
#include <cstdio>

const int N = 100010;

int n, m;
int p[N], size[N];

int find(int x)  // 返回x的祖宗节点 + 路径压缩
{
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int main()
{
    scanf("%d%d", &n, &m);
    
    for (int i = 1; i <= n; i++)
    {
        p[i] = i;
        size[i] = 1;
    }
    
    while (m--)
    {
        char op[5];
        int a, b;
        scanf("%s", op);
        
        if (op[0] == 'C')
        {
            scanf("%d%d", &a, &b);
            if (find(a) == find(b)) continue;
            size[find(b)] += size[find(a)];
            p[find(a)] = find(b);
        }
        else if (op[1] == '1')
        {
            scanf("%d%d", &a, &b);
            if (find(a) == find(b)) puts("Yes");
            else puts("No");
        }
        else
        {
            scanf("%d", &a);
            printf("%d\n", size[find(a)]);
        }
    }
    
    return 0;
}
相关推荐
纪念 2291 小时前
C++ string(三)
android·c++
PascalXie1 小时前
地面机器人VSLAM技术调研与实现方案参考:算法、硬件平台与工程落地
算法·机器人
纪念 2292 小时前
c++ string(最终篇)
android·c++
aqiu1111113 小时前
【C++算法打怪专栏】8. 字符串转换整数 (atoi)
开发语言·c++·算法
h39748 小时前
DirectShow过滤器开发-视频源过滤器
c++·windows·音视频·directshow
程序猿编码10 小时前
榨干 RTX5090 算力!Qwen3 专用单卡推理引擎,手写C++/CUDA 算子实现 MTP 推测解码
开发语言·c++·大模型推理·qwen3·多模态推理
西飘客11 小时前
vs 怎么根据dll 生成lib文件
c++·qt
程序员老陆11 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
信奥卷王12 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵12 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表