一、实现程序:
#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 ==