File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
union-find/04-quick-union-optimized-based-on-rank Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < cassert>
3
+
4
+ using namespace std ;
5
+
6
+ namespace UF4 {
7
+ class UnionFind {
8
+ private:
9
+ int * parent;
10
+ int * rank; // size[i]表示以i为根的集合所表示的层数
11
+ int count;
12
+ public:
13
+ UnionFind (int count){
14
+ parent = new int [count];
15
+ rank = new int [count];
16
+ this ->count = count;
17
+ for (int i = 0 ; i < count; i++)
18
+ {
19
+ parent[i] = i;
20
+ rank[i] = 1 ;
21
+ }
22
+ }
23
+ ~UnionFind (){
24
+ delete [] parent;
25
+ delete [] rank;
26
+ }
27
+ int find (int q){
28
+ assert (q >= 0 && q < count);
29
+ while (q != parent[q]){
30
+ q = parent[q];
31
+ }
32
+ return q;
33
+ }
34
+ bool isConnected (int p, int q){
35
+ return find (q) == find (q);
36
+ }
37
+ void unionElements (int p, int q){
38
+ int pRoot = find (p);
39
+ int qRoot = find (q);
40
+ if (qRoot == pRoot)
41
+ return ;
42
+ if (rank[pRoot] < rank[qRoot]){
43
+ parent[pRoot] = qRoot;
44
+ } else if (rank[qRoot] < rank[pRoot]){
45
+ parent[qRoot] = pRoot;
46
+ } else { // rank[pRoot] = rank[qRoot]
47
+ parent[pRoot] = qRoot;
48
+ rank[qRoot] +=1 ;
49
+ }
50
+ }
51
+ };
52
+ }
You can’t perform that action at this time.
0 commit comments