-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathdisjoint_sets_union.cpp
93 lines (82 loc) · 2.09 KB
/
disjoint_sets_union.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
#include <bits/stdc++.h>
using namespace std;
/**
* Disjoint-set data structure to tracks a set of elements partitioned
* into a number of disjoint subsets.
*/
class DSU {
int setsCount;
vector<int> siz;
mutable vector<int> par;
public:
/**
* Initializes the DSU with "n" independent sets.
*
* @param n the number of sets to initialize.
*/
DSU(int n) {
setsCount = n;
siz.resize(n, 1);
par.resize(n);
iota(par.begin(), par.end(), 0);
}
/**
* Finds the set id of an element.
*
* @param u the element to find its set id.
*
* @return the set id of the given element.
*/
int findSetId(int u) const {
return u == par[u] ? u : par[u] = findSetId(par[u]);
}
/**
* Checks whether two elements are in the same set.
*
* @param u the first element.
* @param v the second element.
*
* @return {@code true} if elements "u" and "v" are in the same set;
* {@code false} otherwise.
*/
bool areInSameSet(int u, int v) const {
return findSetId(u) == findSetId(v);
}
/**
* Unions two sets together into one set.
*
* @param u an element in the first set.
* @param v an element in the second set.
*
* @return {@code true} if the set having element "u" is merged with the
* set having element "v"; {@code false} if elements "u" and "v" were
* already in the same set.
*/
bool unionSets(int u, int v) {
u = findSetId(u);
v = findSetId(v);
if (u == v) {
return false;
}
setsCount--;
siz[v] += siz[u];
par[u] = v;
return true;
}
/**
* Returns the number of elements of a set.
*
* @param u an element in the required set.
*
* @return the size of the set having the given element "u".
*/
int getSetSize(int u) const {
return siz[findSetId(u)];
}
/**
* @return the number of disjoint sets.
*/
int getSetsCount() const {
return setsCount;
}
};