-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1584.minCostToConnectAllPoints.krushkal.java
75 lines (71 loc) · 2.12 KB
/
1584.minCostToConnectAllPoints.krushkal.java
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
class Solution {
public int minCostConnectPoints(int[][] points) {
// we can create fully connected graph.
// then apply mst algorithm.
int n=points.length;
ArrayList<int[]> edges=new ArrayList<>();
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j)continue;
int x1=points[i][0];
int y1=points[i][1];
int x2=points[j][0];
int y2=points[j][1];
// edge weight will be manhattan distance
edges.add(new int[]{i,j,Math.abs(x1-x2)+ Math.abs(y1-y2)});
}
}
Collections.sort(edges,(a,b)->a[2]-b[2]); // sort by edge weight
DSU dis=new DSU(edges.size());
int ans=0;
for(int[] edge:edges){
int src=edge[0],des=edge[1],wt=edge[2];
if(dis.find(src)==dis.find(des)){
// both belong to same component
// adding src<->des will form a cycle
}else{
// we should take this as this will not form a cycle
dis.union(src,des);
ans+=wt;
}
}
return ans;
}
}
class DSU{
ArrayList<Integer> sizes;
ArrayList<Integer> parents;
public DSU(int n){
sizes=new ArrayList<>(n);
parents=new ArrayList<>(n);
for(int i=0;i<n;i++){
sizes.add(1);
parents.add(i);
}
}
void union(int i,int j){
if(find(i)==find(j))return;
int ui=find(i);
int uj=find(j);
int ui_size=sizes.get(ui);
int uj_size=sizes.get(uj);
int combined=ui_size+uj_size;
if(ui_size<uj_size){
parents.set(ui,uj);
sizes.set(uj,combined);
}else{
// ui_size >= uj_size
parents.set(uj,ui);
sizes.set(ui,combined);
}
}
int find(int i){
if(parents.get(i)==i)return i;
int uparent=find(parents.get(i));
parents.set(i,uparent);
return uparent;
}
}