chapter §31 并查集

并查集支持查找以下操作:
1、合并:合并两个集合;
2、查找:判断两个元素是否在同一个集合中。其核心是用一个数组实现。


#include <iostream>
#include <set>

using namespace std;
const int MAX = 10;
int father[MAX];//并查集,father[i]表示元素i的父结点
bool flag[MAX] = {false};
int count = 0;

void initUFS() { //初始化
    for (int i = 1; i <= MAX; ++i) {
        father[i] = i;
    }
}

int findFather(int x) {//查找元素x所在集合的根结点,递推写法
    while (x != father[x]) {
        x = father[x];
    }
    return x;
}

int findFather1(int x) {//查找元素x所在集合的根结点,递归写法
    if (x == father[x]) return x;
    else return findFather1(father[x]);
}

void Union(int a, int b) {//合并a和b所在的集合
    int fatherA = findFather(a);
    int fatherB = findFather(b);
    if (fatherA != fatherB)
        father[fatherA] = fatherB;
}

int BestfindFather(int x) { //查找根结点优化,路径压缩,将从x开始查到根结点的路径所经过的所有结点的父结点都置为根结点
    int a = x;
    while (x != father[x]) {
        x = father[x];
    }
    while (a != father[a]) {
        int z = a;
        a = father[a];
        father[z] = x;
    }
    return x;
}

int main() {
    set<int> s;
    int n, m;
    cin >> n >> m;
    initUFS();
    for (int i = 0; i < m; ++i) {
        int a, b;
        cin >> a >> b;
        Union(a, b);
    }
    for (int j = 1; j <= n; ++j) {
        s.insert(findFather(j));
    }
    cout << s.size();
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Missヾaurora

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值