-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDSU.CPP
73 lines (63 loc) · 1.68 KB
/
DSU.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
#include <bits/stdc++.h>
using namespace std;
class DSU
{
private:
vector<int>parent;
vector<int>size;
vector<int>rank;
int count;
public:
DSU (int n):parent(n),size(n),rank(n),count(n)
{
for(int i=0;i<n;i++)
{
parent[i]=i;
size[i]=1;
rank[i]=1;
}
}
int findPar(int node)
{
if(node==parent[node])
return node;
return parent[node]=findPar(parent[node]);
}
void unionSize(int u,int v)
{
int pu=findPar(u);
int pv=findPar(v);
if(pu!=pv)
{
if(size[pu] < size[pv]) {
parent[pu] = pv;
size[pv] += size[pu];
}
else {
parent[pv] = pu;
size[pu] += size[pv];
}
count--;
}
}
void unionRank(int x, int y)
{
int rootX = findPar(x);
int rootY = findPar(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX] += 1;
}
count--;
}
}
int getCount()
{
return count;
}
};