1
- // Quick find
2
- class UnionFind {
3
- public:
4
- UnionFind (int sz) : root(sz) {
5
- for (int i = 0 ; i < sz; i++) root[i] = i;
6
- }
7
-
8
- int find (int x) { return root[x]; }
9
-
10
- void unionSet (int x, int y) {
11
- int rootX = find (x);
12
- int rootY = find (y);
13
- if (rootX != rootY)
14
- for (int i = 0 ; i < root.size (); i++)
15
- if (root[i] == rootY)
16
- root[i] = rootX;
17
- }
18
-
19
- bool connected (int x, int y) {
20
- return find (x) == find (y);
21
- }
22
-
23
- private:
24
- vector<int > root;
25
- };
26
-
27
- // Quick union
1
+ // Quick Union
28
2
class UnionFind {
29
3
public:
30
4
UnionFind (int sz) : root(sz), rank(sz) {
31
- for (int i = 0 ; i < sz; i++) root[i] = i;
5
+ for (int i = 0 ; i < sz; i++) root[i] = i, rank[i] = 1 ;
32
6
}
33
7
34
- // normal
35
- // int find(int x) {
36
- // while (x != root[x]) x = root[x];
37
- // return x;
38
- // }
39
-
40
8
// path compression
41
9
int find (int x) {
42
10
if (x == root[x]) return x;
43
11
return root[x] = find (root[x]);
44
12
}
45
13
46
- // normal
47
- // void unionSet(int x, int y) {
48
- // int rootX = find(x);
49
- // int rootY = find(y);
50
- // if (rootX != rootY) root[rootY] = rootX;
51
- // }
52
-
53
14
// rank based
54
15
void unionSetRankBased (int x, int y) {
55
16
int rootX = find (x), rootY = find (y);
@@ -90,38 +51,4 @@ int main() {
90
51
uf.unionSet (9 , 4 );
91
52
cout << uf.connected (4 , 9 ) << endl; // true
92
53
return 0 ;
93
- }
94
-
95
- class UnionFind {
96
- private:
97
- vector<int > root;
98
- vector<int > rank;
99
- public:
100
- UnionFind (int sz) : root(sz), rank(sz) {
101
- for (int i = 0 ; i < sz; i++) {
102
- root[i] = i;
103
- rank[i] = 1 ;
104
- }
105
- }
106
-
107
- int find (int x) {
108
- if (x == root[x])
109
- return x;
110
- return root[x] = find (root[x]);
111
- }
112
-
113
- // Perform the union of two components
114
- void unionSet (int x, int y) {
115
- int rootX = find (x);
116
- int rootY = find (y);
117
- if (rootX != rootY) {
118
- if (rank[rootX] >= rank[rootY]) {
119
- root[rootY] = rootX;
120
- rank[rootX] += rank[rootY];
121
- } else {
122
- root[rootX] = rootY;
123
- rank[rootY] += rank[rootX];
124
- }
125
- }
126
- }
127
- };
54
+ }
0 commit comments