-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfindUnionSet.h
68 lines (59 loc) · 1.23 KB
/
findUnionSet.h
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//
// Created by so_go on 2020/2/24.
//
#ifndef SRC_UNIONSET_H
#define SRC_UNIONSET_H
#include<vector>
using namespace std;
class UnionFindSet{
public:
vector<int> parent;
UnionFindSet(int n){
for(int i = 0; i < n; i++){
parent.push_back(i);
}
}
/*
* 一个写法
int find(int i){
int root= i;
while(parent[root] != root){
root= parent[root];
}
// 路劲压缩
int cur= i, tmp;
while(cur != root){
tmp = parent[cur];
parent[cur]= root;
cur= tmp;
}
return root;
}
*/
// 递归写法:
int find(int i){
// 对于当前节点,查找根节点,并返回
if(parent[i] != i){
parent[i] = find(parent[i]); // 路径压缩在find不断上溯的过程中完成
}
return parent[i]
}
// 或者
/*
int find(int i){
if(parent[i] == i){
return i;
}
pre[x] = find(pre[x]);
return pre[x];
}
*/
int join(int i, int j){
int rti= find(i);
int rtj = find(j);
if(rti != rtj){
parent[rti] = rtj;
}
}
};
#endif //SRC_UNIONSET_H