AcWing 850. Dijkstra求最短路 II-java-非手写堆优化版
原题链接
简单
作者:
Astarion
,
2021-02-14 09:56:21
,
所有人可见
,
阅读 252
import java.io.*;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
class Main {
static final int INF = Integer.MAX_VALUE / 2;
//邻接表存储图
static int idx;
static int[] h = new int[200010];
static int[] e = new int[200010];
static int[] ne = new int[200010];
static int[] w = new int[200010];
static int n, m;
static boolean[] visited = new boolean[200010];
static int[] dist = new int[200010];
static {
Arrays.fill(dist, INF);
Arrays.fill(h, -1);
}
static class MinDist implements Comparable<MinDist> {
int e, d;
public MinDist(int e, int d) {
this.e = e;
this.d = d;
}
@Override
public int compareTo(MinDist o) {
return this.d - o.d;
}
}
static Queue<MinDist> heap = new PriorityQueue<>();
static void insert(int a, int b, int v) {
e[idx] = b;
ne[idx] = h[a];
w[idx] = v;
h[a] = idx++;
}
static int dijkstra() {
dist[1] = 0;
heap.add(new MinDist(1,0));
while (!heap.isEmpty()) {
MinDist next = heap.poll();
if (visited[next.e]) continue;
visited[next.e] = true;
for (int i = h[next.e]; i !=-1 ; i=ne[i]) {
int point = e[i];
int distance = w[i];
if (dist[point]>dist[next.e]+distance) {
dist[point] = dist[next.e]+distance;
heap.add(new MinDist(point,dist[point]));
}
}
}
if (dist[n]!=INF) return dist[n];
else return -1;
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
n = Integer.parseInt(strs[0]);
m = Integer.parseInt(strs[1]);
for (int i = 0; i < m; i++) {
strs = in.readLine().split(" ");
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
int v = Integer.parseInt(strs[2]);
insert(a, b, v);
}
System.out.println(dijkstra());
in.close();
isr.close();
}
}