C++ 并查集(Union-Find Sets)

本文介绍了C++中并查集的数据结构及其使用,通过实例程序展示了并查集的基本操作,包括查找和合并。文章还提供了测试结果,帮助读者深入理解这一数据结构的应用。
摘要由CSDN通过智能技术生成

一、实现程序:

#include <iostream>
using namespace std;

struct Node { // 并查集结点类
    int data; // 保存数据
    int parent; // 保存父结点
};

class UnionFindSets {
public:
    UnionFindSets(int w[], int n); // 构造函数
    ~UnionFindSets(); // 析构函数
    void Union(int a, int b); // 并
    bool Find(int a, int b); // 查找两个数是否在同一集合
private:
    Node *s; // 数组
    int currentSize; // 实际存储的个数
    int Find(int x); // 查找x,并返回x的根结点
};

// 构造函数
UnionFindSets::UnionFindSets(int w[], int n) {
    // 初始化
    currentSize = n;
    s = new Node[n];
    for(int i = 0; i < n; i++) {
        s[i].data = w[i];
        s[i].parent = -1;
    }
}

// 析构函数
UnionFindSets::~UnionFindSets() {
    delete []s; // 释放空间
}

// 并
void UnionFindSets::Union(int a, int b) {
    int root1, root2;
    
    root1 = Find(a); // 找到a的根结点
    root2 = Find(b); // 找到b的根结点
    if(root1 == root2 || root1 == -1 || root2 ==
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值