-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdsu code
34 lines (28 loc) · 899 Bytes
/
dsu code
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
class DisjointSet{
List<Integer> size = new ArrayList<>();
List<Integer> parent = new ArrayList<>();
public DisjointSet(int n){
for(int i=0; i<=n; i++){
parent.add(i);
size.add(1);
}
}
public int findUparent(int node){
if(node == parent.get(node))
return node;
int ult_p = findUparent(parent.get(node));
parent.set(node,ult_p);
return parent.get(node);
}
public void unionBySize(int u,int v){
int ult_u = findUparent(u);
int ult_v = findUparent(v);
if(ult_u == ult_v)return;
if(size.get(ult_u) < size.get(ult_v)){
parent.set(ult_u,ult_v);
size.set(ult_v , size.get(ult_u) + size.get(ult_v));
}else{
parent.set(ult_v,ult_u);
size.set(ult_u , size.get(ult_u) + size.get(ult_v));
}
}