-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSU.cpp
More file actions
45 lines (45 loc) · 759 Bytes
/
DSU.cpp
File metadata and controls
45 lines (45 loc) · 759 Bytes
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
class DSU //https://github.com/seo-bo/Algorithm_templates/blob/main/DSU.cpp
{
private:
int n;
vector<int>parent, rank;
int get_path(int root)
{
return (parent[root] == root) ? parent[root] : parent[root] = get_path(parent[root]);
}
void merger(int root1, int root2)
{
int r1 = get_path(root1), r2 = get_path(root2);
if (r1 != r2)
{
if (rank[r1] > rank[r2])
{
parent[r2] = r1;
}
else
{
parent[r1] = r2;
if (rank[r1] == rank[r2])
{
rank[r2]++;
}
}
}
}
public:
DSU(int ok)
{
n = ok;
parent.resize(n + 1, 0);
rank.resize(n + 1, 0);
iota(parent.begin(), parent.end(), 0);
}
int find(int root)
{
return get_path(root);
}
void merge(int root1, int root2)
{
merger(root1, root2);
}
};