|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + static class Node implements Comparable<Node> { |
| 8 | + int idx, cost; |
| 9 | + |
| 10 | + Node(int idx, int cost) { |
| 11 | + this.idx = idx; |
| 12 | + this.cost = cost; |
| 13 | + } |
| 14 | + |
| 15 | + @Override |
| 16 | + public int compareTo(Node o) { |
| 17 | + return Integer.compare(this.cost, o.cost); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + public static void main(String[] args) throws Exception { |
| 22 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 23 | + StringTokenizer st; |
| 24 | + StringBuilder sb = new StringBuilder(); |
| 25 | + |
| 26 | + int n = Integer.parseInt(br.readLine()); |
| 27 | + int m = Integer.parseInt(br.readLine()); |
| 28 | + |
| 29 | + List<List<Node>> graph = new ArrayList<>(); |
| 30 | + for (int i = 0; i <= n; i++) |
| 31 | + graph.add(new ArrayList<>()); |
| 32 | + |
| 33 | + for (int i = 0; i < m; i++) { |
| 34 | + st = new StringTokenizer(br.readLine()); |
| 35 | + int from = Integer.parseInt(st.nextToken()); |
| 36 | + int to = Integer.parseInt(st.nextToken()); |
| 37 | + int c = Integer.parseInt(st.nextToken()); |
| 38 | + graph.get(from).add(new Node(to, c)); |
| 39 | + } |
| 40 | + |
| 41 | + st = new StringTokenizer(br.readLine()); |
| 42 | + int start = Integer.parseInt(st.nextToken()); |
| 43 | + int end = Integer.parseInt(st.nextToken()); |
| 44 | + |
| 45 | + int[] dist = new int[n + 1]; |
| 46 | + Arrays.fill(dist, Integer.MAX_VALUE); |
| 47 | + dist[start] = 0; |
| 48 | + |
| 49 | + PriorityQueue<Node> pq = new PriorityQueue<>(); |
| 50 | + pq.offer(new Node(start, 0)); |
| 51 | + |
| 52 | + while (!pq.isEmpty()) { |
| 53 | + Node cur = pq.poll(); |
| 54 | + int now = cur.idx; |
| 55 | + |
| 56 | + if (cur.cost > dist[now]) continue; |
| 57 | + |
| 58 | + for (Node next : graph.get(now)) { |
| 59 | + if (dist[next.idx] > dist[now] + next.cost) { |
| 60 | + dist[next.idx] = dist[now] + next.cost; |
| 61 | + pq.offer(new Node(next.idx, dist[next.idx])); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + System.out.println(dist[end]); |
| 66 | + } |
| 67 | +} |
| 68 | +``` |
0 commit comments