File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
union-find/05-quick-union-path-compression Expand file tree Collapse file tree 1 file changed +56
-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 UF5 {
7
+ class UnionFind {
8
+ private:
9
+ int * parent;
10
+ int * rank;
11
+ int count;
12
+ public:
13
+ UnionFind (int count){
14
+ parent = new int [count];
15
+ rank = new int [count];
16
+ this ->count = count;
17
+ }
18
+ ~UnionFind (){
19
+ delete [] parent;
20
+ delete [] rank;
21
+ }
22
+ int find (int q){
23
+ assert (q >= 0 && q < count);
24
+ /* path compression
25
+ * not best solution
26
+ while(q != parent[q]){
27
+ parent[q] = parent[parent[q]]
28
+ q = parent[q];
29
+ }
30
+ return q;
31
+ */
32
+ // using recursion to get shortest tree
33
+ if (q != parent[q])
34
+ parent[q] = find (parent[q]);
35
+ return parent[q];
36
+ }
37
+ bool isConnected (int q, int p){
38
+ return find (q) == find (p);
39
+ }
40
+ void unionElements (int q, int p){
41
+ int pRoot = find (p);
42
+ int qRoot = find (q);
43
+ if (qRoot == pRoot){
44
+ return ;
45
+ }
46
+ if (rank[qRoot] < rank[pRoot]){
47
+ parent[qRoot] = pRoot;
48
+ } else if (rank[pRoot] < rank[qRoot]){
49
+ parent[pRoot] = qRoot;
50
+ } else { // rank[qRoot] == rank[pRoot]
51
+ parent[pRoot] = qRoot;
52
+ rank[pRoot] += 1 ;
53
+ }
54
+ }
55
+ };
56
+ }
You can’t perform that action at this time.
0 commit comments