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