-
Notifications
You must be signed in to change notification settings - Fork 3
/
DSU2.cpp
59 lines (43 loc) · 1.19 KB
/
DSU2.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
#include<bits/stdc++.h>
using namespace std;
class DSU {
public:
int n;
int setCount;
vector<set<int>> _sets; // Can be unordered_set<int> as well
vector<int> _setIndex;
DSU(int n): n(n), setCount(n) {
for(int i = 0; i < n; i++) {
_sets.push_back({i});
_setIndex.push_back(i);
}
}
int setIndex(int i) {
return _setIndex[i];
}
set<int>& getSet(int i) {
return _sets[_setIndex[i]];
}
int setSize(int i) {
return getSet(i).size();
}
void join(int i, int j) {
if(setIndex(i) == setIndex(j))return;
if(setSize(i) < setSize(j))
swap(i, j);
auto &set1 = getSet(i);
auto &set2 = getSet(j);
int targetSetIndex = setIndex(i);
set1.insert(set2.begin(), set2.end());
for(int k: set2)
_setIndex[k] = targetSetIndex;
setCount--;
set2.clear();
}
vector<set<int>> getSets() {
vector<set<int>> results;
for (auto v: _sets)
if(v.size())results.push_back(v);
return results;
}
};