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