forked from DanielW48/HackPack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSU.java
More file actions
50 lines (47 loc) · 1.15 KB
/
DSU.java
File metadata and controls
50 lines (47 loc) · 1.15 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
class DSU {
static int n;
static int[] root, height;
public static void main(String[] args){
root = new int[n];
height = new int[n];
for(int i = 0; i < n; ++i){
root[i] = i;
height[i] = 1;
}
PriorityQueue<edge> pq = new PriorityQueue<>();
long sum = 0;
int max = 0, numConnd = 1;
while(!pq.isEmpty() && numConnd < n){
edge curr = pq.poll();
if(union(curr.u, curr.v)){
sum += curr.w;
max = curr.w;
++numConnd;
}
}
}
static int getPar(int idx) {
if(root[idx] != idx) return getPar(root[idx]);
return idx;
}
static boolean union(int x, int y) {
int parX = getPar(x);
int parY = getPar(y);
if(parX == parY) return false;
if(height[parX] > height[parY]) parX = parX ^ parY ^ (parY = parX);
root[parY] = parX;
height[parX] += height[parY];
return true;
}
static class edge implements Comparable<edge>{
int u, v, w;
edge(int uu, int vv, int ww){
u = uu;
v = vv;
w = ww;
}
public int compareTo(edge in){
return w - in.w;
}
}
}