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
25
using
std::cout;
26
using
std::endl;
27
using
std::vector;
28
29
vector<int> root, rank;
30
37
void
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
53
int
Find
(
int
x) {
54
if
(root[x] == x) {
55
return
x;
56
}
57
return
root[x] =
Find
(root[x]);
58
}
59
67
bool
InSameUnion
(
int
x,
int
y) {
return
Find
(x) ==
Find
(y); }
68
78
void
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
93
int
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
}
CreateSet
void CreateSet(int n)
Definition
disjoint_set.cpp:37
InSameUnion
bool InSameUnion(int x, int y)
Definition
disjoint_set.cpp:67
Find
int Find(int x)
Definition
disjoint_set.cpp:53
Union
void Union(int x, int y)
Definition
disjoint_set.cpp:78
main
int main()
Definition
disjoint_set.cpp:93
endl
#define endl
Definition
matrix_exponentiation.cpp:36
data_structures
disjoint_set.cpp
Generated by
1.12.0