思路没什么特别的,就是换个java的写法
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = 0x3f3f3f3f;
int n = scanner.nextInt(), m = scanner.nextInt();
Map<Integer, List<PII>> g = new HashMap<>();
int[] distance = new int[n + 1];
boolean[] state = new boolean[n + 1];
// 初始化距离数组
Arrays.fill(distance, N);
distance[1] = 0;
// 构造邻接表
while (m-- > 0) {
int x = scanner.nextInt(), y = scanner.nextInt(), w = scanner.nextInt();
if(!g.containsKey(x)) g.put(x, new ArrayList<>());
g.get(x).add(new PII(w,y));
}
dijkstra(n, g, state, distance);
if (distance[n] == N)
System.out.println(-1);
else
System.out.println(distance[n]);
scanner.close();
}
private static void dijkstra(int n, Map<Integer, List<PII>> g, boolean[] state, int[] distance) {
PriorityQueue<PII> heap = new PriorityQueue<>();
heap.offer(new PII(0, 1));
while (!heap.isEmpty()) {
PII top = heap.poll();
if(state[top.index]) continue;
state[top.index] = true;
List<PII> list = g.get(top.index);
if (list == null)
continue;
for (PII item : list) {
if (!state[item.index] && distance[item.index] > top.weiget + item.weiget) {
distance[item.index] = top.weiget + item.weiget;
heap.offer(new PII(distance[item.index], item.index));
}
}
}
}
// 邻接表元素
static class PII implements Comparable<PII> {
int weiget;
int index;
/**
* @param weiget 权重
* @param index 结点编号
*/
public PII(int weiget, int index) {
this.weiget = weiget;
this.index = index;
}
@Override
public int compareTo(PII o) {
// 重写比较器,即指定PII类在排序比较大小时的规则,方便使用优先队列
// 比较器要求返回一个整数(正数代表o1>o2),我们想按照权重来排序,只需返回两者权重的差值即可
return this.weiget - o.weiget;
}
}
}
写的真好