|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + |
| 6 | + public static List<List<int[]>> graph; |
| 7 | + public static int[] dist; |
| 8 | + public static int N; |
| 9 | + |
| 10 | + public static void main(String[] args) throws IOException { |
| 11 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 13 | + N = Integer.parseInt(st.nextToken()); |
| 14 | + int M = Integer.parseInt(st.nextToken()); |
| 15 | + graph = new ArrayList<>(); |
| 16 | + dist = new int[N+1]; |
| 17 | + for(int i=0; i<=N; i++) { |
| 18 | + graph.add(new ArrayList<>()); |
| 19 | + dist[i] = Integer.MAX_VALUE; |
| 20 | + } |
| 21 | + for(int i=0; i<M; i++) { |
| 22 | + st = new StringTokenizer(br.readLine()); |
| 23 | + int A = Integer.parseInt(st.nextToken()); |
| 24 | + int B = Integer.parseInt(st.nextToken()); |
| 25 | + int C = Integer.parseInt(st.nextToken()); |
| 26 | + graph.get(A).add(new int[]{B, C}); |
| 27 | + graph.get(B).add(new int[]{A, C}); |
| 28 | + } |
| 29 | + dijkstra(); |
| 30 | + } |
| 31 | + |
| 32 | + public static void dijkstra(){ |
| 33 | + PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1[1], o2[1])); |
| 34 | + pq.offer(new int[]{1, 0}); |
| 35 | + while(!pq.isEmpty()) { |
| 36 | + int v = pq.peek()[0]; |
| 37 | + int cost = pq.peek()[1]; |
| 38 | + pq.poll(); |
| 39 | + |
| 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[N]); |
| 56 | + } |
| 57 | +} |
0 commit comments