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

知识概览

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

  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;
}
相关推荐
wuqingshun3141593 分钟前
蓝桥杯 5. 交换瓶子
数据结构·c++·算法·职场和发展·蓝桥杯
Demons_kirit14 分钟前
Leetcode 2845 题解
算法·leetcode·职场和发展
球求了32 分钟前
C++:继承机制详解
开发语言·c++·学习
adam_life44 分钟前
http://noi.openjudge.cn/——2.5基本算法之搜索——200:Solitaire
算法·宽搜·布局唯一码
超爱笑嘻嘻1 小时前
shared_ptr八股收集 C++
c++
我想进大厂1 小时前
图论---朴素Prim(稠密图)
数据结构·c++·算法·图论
我想进大厂2 小时前
图论---Bellman-Ford算法
数据结构·c++·算法·图论
AIGC大时代2 小时前
高效使用DeepSeek对“情境+ 对象 +问题“型课题进行开题!
数据库·人工智能·算法·aigc·智能写作·deepseek
光而不耀@lgy2 小时前
C++初登门槛
linux·开发语言·网络·c++·后端
lkbhua莱克瓦242 小时前
用C语言实现——一个中缀表达式的计算器。支持用户输入和动画演示过程。
c语言·开发语言·数据结构·链表·学习方法·交友·计算器