acwing-850. Dijkstra求最短路 II
| 12
 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
 
 | import java.util.*;class Main{
 
 static int N = 1000010;
 
 static int[] h = new int[N];
 static int[] e = new int[N];
 static int[] w = new int[N];
 static int[] ne = new int[N];
 
 static int[] dist = new int[N];
 
 static boolean[] st = new boolean[N];
 static int idx = 0;
 
 static PriorityQueue<int[]> queue = new PriorityQueue<>((o1, o2)->{
 return o1[1] - o2[1];
 });
 
 public static void main(String[] args){
 Scanner sc = new Scanner(System.in);
 int n = sc.nextInt();
 int m = sc.nextInt();
 
 Arrays.fill(h, -1);
 for(int i = 1; i <= m; i++){
 int a = sc.nextInt();
 int b = sc.nextInt();
 int c = sc.nextInt();
 add(a, b, c);
 }
 int result = dijstra(n);
 System.out.println(result == 1000000000 ? -1 : result);
 }
 
 public static int dijstra(int n){
 
 Arrays.fill(dist, 1000000000);
 
 dist[1] = 0;
 
 queue.offer(new int[]{1, 0});
 while( queue.size() > 0 ){
 int[] arr = queue.poll();
 int t = arr[0];
 int distance = arr[1];
 if(st[t]){
 continue;
 }
 
 st[t] = true;
 
 
 for(int i = h[t]; i != -1; i = ne[i]){
 int j = e[i];
 if(dist[j] > distance + w[i]){
 dist[j] = distance + w[i];
 queue.offer(new int[]{j, dist[j]});
 }
 }
 }
 return dist[n];
 }
 
 public static void add(int a, int b, int c){
 e[idx] = b;
 w[idx] = c;
 ne[idx] = h[a];
 h[a] = idx++;
 }
 }
 
 |