-
Notifications
You must be signed in to change notification settings - Fork 342
/
DSU
44 lines (38 loc) · 777 Bytes
/
DSU
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
//DSU Disjint Set Union
struct DSU
{
int connected;
vector<int> sz;
vector<int> parent;
void init(int n)
{
parent = sz = vector<int>(n+1);
for(int i=1; i<=n; i++)
parent[i]=i, sz[i]=1;
connected = n;
}
int getParent (int n)
{
if(n == parent[n])
return n;
parent[n] = getParent(parent[n]);
return parent[n];
}
int getSize(int u)
{
return sz[getParent(u)];
}
void merge (int a, int b)
{
int x = getParent(a);
int y = getParent(b);
if(x != y)
{
connected--;
if (sz[x] < sz[y])
swap(x,y);
sz[x] += sz[y];
parent[y] = parent[x];
}
}
};