|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + |
| 6 | + public static int city; |
| 7 | + public static List<List<int[]>> graph; |
| 8 | + public static int[] dist; |
| 9 | + |
| 10 | + public static void main(String[] args) throws IOException { |
| 11 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + city = Integer.parseInt(br.readLine()); |
| 13 | + int bus = Integer.parseInt(br.readLine()); |
| 14 | + graph = new ArrayList<>(); |
| 15 | + dist = new int[city+1]; |
| 16 | + for(int i=0; i<=city; i++) { |
| 17 | + graph.add(new ArrayList<>()); |
| 18 | + dist[i] = Integer.MAX_VALUE; |
| 19 | + } |
| 20 | + for(int i=0; i<bus; i++) { |
| 21 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 22 | + int v1 = Integer.parseInt(st.nextToken()); |
| 23 | + int v2 = Integer.parseInt(st.nextToken()); |
| 24 | + int cost = Integer.parseInt(st.nextToken()); |
| 25 | + graph.get(v1).add(new int[]{v2, cost}); |
| 26 | + } |
| 27 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 28 | + int start = Integer.parseInt(st.nextToken()); |
| 29 | + int end = Integer.parseInt(st.nextToken()); |
| 30 | + dijkstra(start, end); |
| 31 | + } |
| 32 | + |
| 33 | + public static void dijkstra(int start, int end) { |
| 34 | + PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1[1], o2[1])); |
| 35 | + pq.offer(new int[]{start, 0}); |
| 36 | + while(!pq.isEmpty()) { |
| 37 | + int v = pq.peek()[0]; |
| 38 | + int cost = pq.peek()[1]; |
| 39 | + pq.poll(); |
| 40 | + |
| 41 | + if(dist[v] < cost) { |
| 42 | + continue; |
| 43 | + } |
| 44 | + |
| 45 | + List<int[]> list = graph.get(v); |
| 46 | + for(int i=0; i<list.size(); i++) { |
| 47 | + int nextV = list.get(i)[0]; |
| 48 | + int nextCost = list.get(i)[1]; |
| 49 | + if(dist[nextV] > cost + nextCost) { |
| 50 | + dist[nextV] = cost + nextCost; |
| 51 | + pq.offer(new int[]{nextV, dist[nextV]}); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + System.out.println(dist[end]); |
| 56 | + } |
| 57 | +} |
0 commit comments