-
Notifications
You must be signed in to change notification settings - Fork 1
/
DisjointSet.cpp
120 lines (103 loc) · 2.92 KB
/
DisjointSet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// Techie Delight https://www.techiedelight.com/disjoint-set-data-structure-union-find-algorithm/
// Naive, Union-Find, Path compression
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
class DisjointSetNaive
{
private:
std::unordered_map<std::string, std::string> parent;
public:
void makeSet(std::vector<std::string> const &objects)
{
for (auto object : objects) {
parent[object] = object;
}
}
std::string find(const std::string& item)
{
while (parent[item] == item) {
return item;
}
return find(parent[item]);
}
void merge(const std::string& itemA, const std::string& itemB) {
std::string parentA = find(itemA);
std::string parentB = find(itemB);
parent[parentA] = parentB;
}
void printSet()
{
for (auto& pair : parent) {
std::cout << pair.first << " : " << pair.second << "\n";
}
std::cout << "=================================\n";
}
};
// Path compression and union by rank
class DisjointSetImproved
{
private:
std::unordered_map<std::string, std::string> parent;
std::unordered_map<std::string, int> rank;
public:
void makeSet(std::vector<std::string> const &objects)
{
for (auto object : objects) {
parent[object] = object;
rank[object] = 0;
}
}
std::string find(const std::string& item)
{
while (parent[item] != item) {
parent[item] = parent[parent[item]];
}
return parent[item];
}
void merge(const std::string& itemA, const std::string& itemB) {
std::string parentA = find(itemA);
std::string parentB = find(itemB);
int rankA = rank[itemA];
int rankB = rank[itemB];
if (parentA == parentB) {
return;
}
if (rankA > rankB) {
parent[parentB] = parentA;
} else if (rankA < rankB) {
parent[parentA] = parentB;
} else {
parent[parentB] = parentA;
rank[parentA]++;
}
}
void printSet()
{
for (auto& pair : parent) {
std::cout << pair.first << " : " << pair.second << " : " << rank[pair.first] << "\n";
}
std::cout << "=================================\n";
}
};
int main()
{
std::vector<std::string> names {"Alice", "Bob", "Charlie", "Dave", "Eve",
"Frank", "Grace", "Heidi", "Ivan", "Judy"};
DisjointSetNaive setn;
setn.makeSet(names);
setn.merge("Alice", "Bob");
setn.merge("Eve", "Charlie");
setn.merge("Dave", "Alice");
setn.merge("Grace", "Ivan");
setn.printSet();
DisjointSetImproved seti;
seti.makeSet(names);
seti.merge("Alice", "Bob");
seti.merge("Eve", "Charlie");
seti.merge("Dave", "Alice");
seti.merge("Grace", "Ivan");
seti.printSet();
return 0;
}