TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
disjoint_set.cpp
Go to the documentation of this file.
1
22#include <iostream>
23#include <vector>
24
25using std::cout;
26using std::endl;
27using std::vector;
28
29vector<int> root, rank;
30
37void CreateSet(int n) {
38 root = vector<int>(n + 1);
39 rank = vector<int>(n + 1, 1);
40 for (int i = 1; i <= n; ++i) {
41 root[i] = i;
42 }
43}
44
53int Find(int x) {
54 if (root[x] == x) {
55 return x;
56 }
57 return root[x] = Find(root[x]);
58}
59
67bool InSameUnion(int x, int y) { return Find(x) == Find(y); }
68
78void Union(int x, int y) {
79 int a = Find(x), b = Find(y);
80 if (a != b) {
81 if (rank[a] < rank[b]) {
82 root[a] = b;
83 } else if (rank[a] > rank[b]) {
84 root[b] = a;
85 } else {
86 root[a] = b;
87 ++rank[b];
88 }
89 }
90}
91
93int main() {
94 // tests CreateSet & Find
95 int n = 100;
96 CreateSet(n);
97 for (int i = 1; i <= 100; ++i) {
98 if (root[i] != i) {
99 cout << "Fail" << endl;
100 break;
101 }
102 }
103 // tests InSameUnion & Union
104 cout << "1 and 2 are initially not in the same subset" << endl;
105 if (InSameUnion(1, 2)) {
106 cout << "Fail" << endl;
107 }
108 Union(1, 2);
109 cout << "1 and 2 are now in the same subset" << endl;
110 if (!InSameUnion(1, 2)) {
111 cout << "Fail" << endl;
112 }
113 return 0;
114}
void CreateSet(int n)
bool InSameUnion(int x, int y)
int Find(int x)
void Union(int x, int y)
int main()
#define endl