Skip to content

Commit 04dff90

Browse files
Union find update
1 parent a32494c commit 04dff90

File tree

1 file changed

+3
-76
lines changed

1 file changed

+3
-76
lines changed

algorithms/union-find.cpp

Lines changed: 3 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,16 @@
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
282
class UnionFind {
293
public:
304
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;
326
}
337

34-
// normal
35-
// int find(int x) {
36-
// while (x != root[x]) x = root[x];
37-
// return x;
38-
// }
39-
408
// path compression
419
int find(int x) {
4210
if (x == root[x]) return x;
4311
return root[x] = find(root[x]);
4412
}
4513

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-
5314
// rank based
5415
void unionSetRankBased(int x, int y) {
5516
int rootX = find(x), rootY = find(y);
@@ -90,38 +51,4 @@ int main() {
9051
uf.unionSet(9, 4);
9152
cout << uf.connected(4, 9) << endl; // true
9253
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

Comments
 (0)