-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisjointSet2.java
More file actions
111 lines (91 loc) · 2.63 KB
/
Copy pathDisjointSet2.java
File metadata and controls
111 lines (91 loc) · 2.63 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import java.util.*;
class DisjointSet {
List<Integer> rank = new ArrayList<>();
List<Integer> parent = new ArrayList<>();
List<Integer> size = new ArrayList<>();
public DisjointSet(int n){
for(int i = 0; i <= n; i++){
rank.add(0);
parent.add(i);
size.add(0);
}
}
int findUpar(int node){
if(node == parent.get(node)){
return node;
}
int ulp = findUpar(parent.get(node));
parent.set(node, ulp);
return parent.get(node);
}
void unionByRank(int u, int v){
int ulp_u = findUpar(u);
int ulp_v = findUpar(v);
if(ulp_u == ulp_v){
return;
}
if(rank.get(ulp_u) < rank.get(ulp_v)){
parent.set(ulp_v, ulp_u);
}
else if(rank.get(ulp_v) < rank.get(ulp_u)){
parent.set(ulp_u, ulp_v);
}
else{
parent.set(ulp_v, ulp_u);
int rankU = rank.get(ulp_u);
rank.set(ulp_u, rankU+1);
}
}
void unionBySize(int u, int v){
int ulp_u = findUpar(u);
int ulp_v = findUpar(v);
if(ulp_u == ulp_v){
return;
}
if(size.get(ulp_u) < size.get(ulp_v)){
parent.set(ulp_u, ulp_v);
size.set(ulp_v, size.get(ulp_v) + size.get(ulp_u));
}
else{
parent.set(ulp_v, ulp_u);
size.set(ulp_u, size.get(ulp_u) + size.get(ulp_v));
}
}
}
public class DisjointSet2{
public static void main(String[] args) {
DisjointSet ds = new DisjointSet(7);
// ds.unionByRank(1,2);
// ds.unionByRank(2,3);
// ds.unionByRank(4,5);
// ds.unionByRank(6,7);
// ds.unionByRank(5,6);
ds.unionBySize(1,2);
ds.unionBySize(2,3);
ds.unionBySize(4,5);
ds.unionBySize(6,7);
ds.unionBySize(5,6);
// checking that 3 and 7 are in same component or not.
if(ds.findUpar(3) == ds.findUpar(7)){
System.out.println("Same component.");
}
else{
System.out.println("Different component.");
}
// ds.unionByRank(3,7);
ds.unionBySize(3,7);
if(ds.findUpar(3) == ds.findUpar(1)){
System.out.println("Same component.");
}
else{
System.out.println("Different component.");
}
ds.unionBySize(3,3);
if(ds.findUpar(3) == ds.findUpar(3)){
System.out.println("Same component.");
}
else{
System.out.println("Different component.");
}
}
}