-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKruskals.java
51 lines (44 loc) · 981 Bytes
/
Kruskals.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
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Kruskals {
public static ArrayList<edge> adj;
public static int n;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
adj= new ArrayList<>();
for (int i = 0; i < m; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
int w = in.nextInt();
adj.add(new edge(a,b,w));
}
Collections.sort(adj);
DisjointSet dj= new DisjointSet(n);
int nume=0;
long mst= 0;
int i=0;
while(nume<n-1) {
edge cur= adj.get(i);
i++;
boolean flag= dj.merge(cur.v1, cur.v2);
if(!flag) continue;
mst+= cur.w;
nume++;
}
System.out.println(mst);
}
static class edge implements Comparable<edge> {
int v1, v2, w;
public edge(int vbeg, int vend, int ww) {
v1 = vbeg;
v2 = vend;
w = ww;
}
public int compareTo(edge o) {
return this.w- o.w;
}
}
}