-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.java
More file actions
55 lines (43 loc) · 1.55 KB
/
Dijkstra.java
File metadata and controls
55 lines (43 loc) · 1.55 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
import java.util.*;
import java.io.*;
//Dijkstra's single source shortest distance
public class Dijkstra {
static long MAX = (long) 1e14; //any max value >= maxweight*numnodes
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
ArrayList<int[]>[] adj = new ArrayList[n];
Arrays.setAll(adj, x -> new ArrayList<>());
for (int i = 0; i < m; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
int w = in.nextInt();
adj[u].add(new int[] {v, w});
}
long[] dist = new long[n];
Arrays.setAll(dist, x -> MAX);
dijkstra(0, adj, dist);
//prints min distances
for (int i = 0; i < n; i++) {
out.print(dist[i] + " ");
}
out.close();
}
static void dijkstra(int src, ArrayList<int[]>[] adj, long[] dist) {
PriorityQueue<long[]> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[1]));
dist[src] = 0;
pq.add(new long[] {src, 0});
while (!pq.isEmpty()) {
long[] cur = pq.poll();
int vtx = (int) cur[0];
if (dist[vtx] != cur[1]) continue;
for (int[] edge : adj[vtx]) {
if (dist[vtx] + edge[1] < dist[edge[0]]) {
pq.add(new long[] {edge[0], dist[edge[0]] = dist[vtx] + edge[1]});
}
}
}
}
}