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