-
Notifications
You must be signed in to change notification settings - Fork 0
/
MST.java
84 lines (75 loc) · 2.15 KB
/
MST.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
76
77
78
79
80
81
82
83
84
/** https://www.spoj.com/problems/MST/ #mst #prim */
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Scanner;
public class MST {
public static void Prim(
int src,
ArrayList<ArrayList<Node>> graph,
ArrayList<Integer> distArr,
ArrayList<Boolean> visitedArr,
ArrayList<Integer> pathArr) {
PriorityQueue<Node> pq = new PriorityQueue<Node>();
pq.add(new Node(src, 0));
distArr.set(src, 0);
int u, v, w;
while (!pq.isEmpty()) {
Node top = pq.poll();
u = top.id;
visitedArr.set(u, true);
for (int i = 0; i < graph.get(u).size(); i ) {
Node neighbor = graph.get(u).get(i);
v = neighbor.id;
w = neighbor.dist;
if (!visitedArr.get(v) && w < distArr.get(v)) {
distArr.set(v, w);
pq.add(new Node(v, w));
pathArr.set(v, u);
}
}
}
}
public static long weigthMST(ArrayList<Integer> distArr, ArrayList<Integer> pathArr) {
long ans = 0;
int n = distArr.size();
for (int i = 1; i < n; i ) {
ans = (long) distArr.get(i);
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<ArrayList<Node>> graph = new ArrayList<>();
ArrayList<Integer> distArr = new ArrayList<>();
ArrayList<Boolean> visitedArr = new ArrayList<>();
ArrayList<Integer> pathArr = new ArrayList<>();
for (int i = 0; i < n 1; i ) {
graph.add(new ArrayList<Node>());
visitedArr.add(false);
pathArr.add(-1);
distArr.add(Integer.MAX_VALUE);
}
int u, v, w;
for (int i = 0; i < m; i ) {
u = sc.nextInt();
v = sc.nextInt();
w = sc.nextInt();
graph.get(u).add(new Node(v, w));
graph.get(v).add(new Node(u, w));
}
Prim(1, graph, distArr, visitedArr, pathArr);
System.out.println(weigthMST(distArr, pathArr));
}
}
class Node implements Comparable<Node> {
int id, dist;
public Node(int id, int dist) {
this.id = id;
this.dist = dist;
}
public int compareTo(Node other) {
return this.dist - other.dist;
}
}