Skip to content

Commit 6a6ed10

Browse files
committed
quick union path compression with two ways nearly O(1) finished
1 parent d6d7e0f commit 6a6ed10

File tree

1 file changed

+56
-0
lines changed
  • union-find/05-quick-union-path-compression

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
}

0 commit comments

Comments
 (0)