-
Notifications
You must be signed in to change notification settings - Fork 0
/
disjoint_sets.cc
149 lines (91 loc) · 2.22 KB
/
disjoint_sets.cc
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
121
122
123
124
125
126
127
128
129
130
131
132
133
// by Wei Shi (based on code by Mark Weiss)
// last modified 09/23/16
// Modified DisjointSets data structure for use in image processing
#include "disjoint_sets.h"
DisjointSets::DisjointSets() {
}
/**
* Construct the disjoint sets object.
* numElements is the initial number of disjoint sets.
*/
DisjointSets::DisjointSets( size_t numElements ) : s( numElements ) {
for( int i = 0; i < s.size( ); i++ )
s[ i ] = -1;
}
/**
* Union two disjoint sets.
* For simplicity, we assume root1 and root2 are distinct
* and represent set names.
* root1 is the root of set 1.
* root2 is the root of set 2.
*/
void DisjointSets::unionSets( int root1, int root2 ) {
// check to see if they are already in the same set:
if(root1 == root2) {
return;
}
// e.g., root1 = 3, root2 = 6
if( s[ root2 ] < s[ root1 ] ) { // root2 is deeper
// Make root2 new root
s[ root1 ] = root2;
}
else
{
if( s[ root1 ] == s[ root2 ] )
s[ root1 ]--; // Update height if same
// s[6] = 3
s[ root2 ] = root1; // Make root1 new root of root2
}
}
/**
* Perform a find.
* Error checks omitted again for simplicity.
* Return the set containing x.
*/
int DisjointSets::find( const int& x ) const {
if( s[ x ] < 0 )
return x;
else
return find( s[ x ] );
}
/**
* Perform a find with path compression.
* Error checks omitted again for simplicity.
* Return the set containing x.
*/
int DisjointSets::find( int x ) {
// x = 3 s[x]
if( s[ x ] < 0 )
return x;
else
return s[ x ] = find( s[ x ] );
}
size_t DisjointSets::size() const {
return s.size();
}
bool DisjointSets::isUsed(size_t index) const{
return valid_index[index];
}
void DisjointSets::print() const {
for(auto& i: s) {
cout << i << ' ';
}
cout << endl;
}
void DisjointSets::setValidIndex(vector<bool>& rhs) {
valid_index = rhs;
}
void DisjointSets::printValidIndex() const{
for(const bool& i: valid_index) {
cout << i << ' ';
}
cout << endl;
}
const vector<int>& DisjointSets::getDisjointSet() const{
return s;
}
DisjointSets& DisjointSets::operator=(const DisjointSets& rhs) {
valid_index = rhs.valid_index;
s = rhs.s;
//group = rhs.group;
}