-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdsu.h
More file actions
65 lines (57 loc) · 1.3 KB
/
dsu.h
File metadata and controls
65 lines (57 loc) · 1.3 KB
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
#ifndef INCLUDE
#include <vector>
#include <map>
using namespace std;
#endif
struct dsu {
vector<int> parent, rank;
dsu(int n) : parent(vector<int>(n + 1)), rank(vector<int>(n + 1)) {
for (int i = 0; i <= n; ++i)
make_set(i);
};
void make_set(int v) {
parent[v] = v;
rank[v] = 0;
}
int find_set(int v) {
if (v == parent[v])
return v;
return parent[v] = find_set(parent[v]);
}
void union_sets(int a, int b) {
a = find_set(a);
b = find_set(b);
if (a != b) {
if (rank[a] < rank[b])
swap(a, b);
parent[b] = a;
if (rank[a] == rank[b])
++rank[a];
}
}
};
template<class T>
struct dsumap {
multimap<T, T> parent;
multimap<T, int> rank;
void make_set(const T &v) {
parent[v] = v;
rank[v] = 0;
}
T find_set(const T &v) {
if (v == parent[v])
return v;
return parent[v] = find_set(parent[v]);
}
void union_sets(T a, T b) {
a = find_set(a);
b = find_set(b);
if (a != b) {
if (rank[a] < rank[b])
swap(a, b);
parent[b] = a;
if (rank[a] == rank[b])
++rank[a];
}
}
};