Skip to content

Commit 095c01d

Browse files
committed
Rewrite Disjoint Set Union
1 parent 3d9da5a commit 095c01d

File tree

7 files changed

+88
-117
lines changed

7 files changed

+88
-117
lines changed

Disjoint-Sets/Compressed.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
using namespace std;
3+
static int parent[264], sz[264], rnk[264];
4+
5+
// Create a new set.
6+
void make_set(int vertex) {
7+
parent[vertex] = vertex;
8+
sz[vertex] = 1;
9+
rnk[vertex] = 0;
10+
}
11+
12+
// O(logN) time.
13+
int find_set(int vertex) {
14+
if (vertex == parent[vertex]) return vertex;
15+
16+
return parent[vertex] = find_set(parent[vertex]);
17+
}
18+
19+
// Union By Size.
20+
void union_sets_by_sz(int set_a, int set_b) {
21+
set_a = find_set(set_a);
22+
set_b = find_set(set_b);
23+
if (set_a != set_b) {
24+
if (sz[set_a] < sz[set_b]) swap(set_a, set_b);
25+
26+
parent[set_b] = set_a;
27+
sz[set_a] += sz[set_b];
28+
}
29+
}
30+
31+
// Union By Rank.
32+
void union_sets_by_rank(int set_a, int set_b) {
33+
set_a = find_set(set_a);
34+
set_b = find_set(set_b);
35+
if (set_a != set_b) {
36+
if (rnk[set_a] < rnk[set_b]) swap(set_a, set_b);
37+
38+
parent[set_b] = set_a;
39+
if (rnk[set_a] == rnk[set_b]) ++rnk[set_a];
40+
}
41+
}
42+
43+
int main() {
44+
// Create 3 different sets.
45+
make_set(1);
46+
make_set(2);
47+
make_set(3);
48+
49+
// Union Operation bw 1 and 2.
50+
union_sets_by_sz(1, 2);
51+
union_sets_by_rank(2, 3);
52+
53+
cout << find_set(3); // 1
54+
}
55+

Disjoint-Sets/Naive.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include <iostream>
2+
using namespace std;
3+
static int parent[264];
4+
5+
void make_set(int vertex) {
6+
parent[vertex] = vertex;
7+
}
8+
9+
// O(n) time.
10+
int find_set(int vertex) {
11+
if (vertex == parent[vertex]) return vertex;
12+
13+
return find_set(parent[vertex]);
14+
}
15+
16+
void union_sets(int set_a, int set_b) {
17+
set_a = find_set(set_a);
18+
set_b = find_set(set_b);
19+
if (set_a != set_b)
20+
parent[set_b] = set_a;
21+
}
22+
23+
int main() {
24+
// Create 3 different sets.
25+
make_set(1);
26+
make_set(2);
27+
make_set(3);
28+
29+
// Union Operation bw 1 and 2.
30+
union_sets(1, 2);
31+
32+
cout << find_set(2); // 1
33+
}

Disjoint-Sets/_quickFind.hpp

Lines changed: 0 additions & 32 deletions
This file was deleted.

Disjoint-Sets/_quickUnion.hpp

Lines changed: 0 additions & 50 deletions
This file was deleted.

Disjoint-Sets/a.out

12.9 KB
Binary file not shown.

Disjoint-Sets/quickFind.cpp

Lines changed: 0 additions & 17 deletions
This file was deleted.

Disjoint-Sets/quickUnion.cpp

Lines changed: 0 additions & 18 deletions
This file was deleted.

0 commit comments

Comments
 (0)