-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdsu.java
More file actions
66 lines (52 loc) · 1.35 KB
/
Copy pathdsu.java
File metadata and controls
66 lines (52 loc) · 1.35 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
package templates;
import java.util.*;
import java.io.*;
public class dsu {
static int[] dsupar, dsusz;
static ArrayList<ArrayList<Integer>> adj;
// initialise dsu;
public static void init(int n) {
dsupar = new int[n];
dsusz = new int[n];
adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
dsupar[i] = i;
adj.add(new ArrayList<>());
}
Arrays.fill(dsusz, 1);
}
// find parent
public static int find(int v) {
if (v == dsupar[v])
return v;
return dsupar[v] = find(dsupar[v]);
}
// check whether in same set
public static boolean isConnected(int u, int v) {
return find(v) == find(u);
};
// merging two component
public static boolean merge(int u, int v) {
v = find(v);
u = find(u);
if (u == v)
return false;
// assuming rank of u is always greater than v
if (dsusz[u] < dsusz[v]) {
int t = v;
v = u;
u = t;
}
dsupar[v] = u;
dsusz[u] = dsusz[u] + dsusz[v];
return true;
}
public static void relabel(int v, int target) {
if (dsupar[v] == target)
return;
dsupar[v] = target;
for (int x : adj.get(v)) {
relabel(x, target);
}
}
}