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

知识概览

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

  1. 将两个集合合并

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

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

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

问题1:如何判断树根:if (p[x] == x)

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

问题3:如何合并两个集合:px是x的集合编号,py是y的集合编号,则p[px] = 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;
}
相关推荐
C雨后彩虹1 天前
任务最优调度
java·数据结构·算法·华为·面试
少林码僧1 天前
2.31 机器学习神器项目实战:如何在真实项目中应用XGBoost等算法
人工智能·python·算法·机器学习·ai·数据挖掘
钱彬 (Qian Bin)1 天前
项目实践15—全球证件智能识别系统(切换为Qwen3-VL-8B-Instruct图文多模态大模型)
人工智能·算法·机器学习·多模态·全球证件识别
微露清风1 天前
系统性学习C++-第十八讲-封装红黑树实现myset与mymap
java·c++·学习
Niuguangshuo1 天前
EM算法详解:解密“鸡生蛋“的机器学习困局
算法·机器学习·概率论
a3158238061 天前
Android 大图显示策略优化显示(一)
android·算法·图片加载·大图片
CSARImage1 天前
C++读取exe程序标准输出
c++
一只小bit1 天前
Qt 常用控件详解:按钮类 / 显示类 / 输入类属性、信号与实战示例
前端·c++·qt·gui
一条大祥脚1 天前
26.1.9 轮廓线dp 状压最短路 构造
数据结构·c++·算法
鲨莎分不晴1 天前
反向传播的数学本质:链式法则与动态规划的完美共舞
算法·动态规划