算法

2023-11-10

并查集:https://blog.csdn.net/YSJ367635984/article/details/113504723

C++代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <vector>

class DisjointSets{
public:
DisjointSets();
~DisjointSets();
int findParentNode(int x);
void unionSetNode(int x, int y);
private:
std::vector<int> parent;
int count;
};

DisjointSets::DisjointSets(): count(10) {
for(int i = 0; i < count; ++i){
parent[i] = i;
}
}

DisjointSets::~DisjointSets() {}

/*
int DisjointSets::findParentNode(int x){
if(x != parent[x]){
findParentNode(parent[x]);
}
return x;
}
*/

// 优化版本的并查集,减小以后查找时间
int DisjointSets::findParentNode(int x){
while(x != parent[x]){
// 找一次x只是压缩一次,多找几次就会导致父节点为根节点
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}

void DisjointSets::unionSetNode(int x, int y){
int parent_x = findParentNode(x);
int parent_y = findParentNode(y);

if(parent_x == parent_y) return;

parent[parent_y] = parent_x;

--count;
}