|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | + |
| 6 | +public class Main { |
| 7 | + static int N, M, X; |
| 8 | + static int[][] arr, revArr; |
| 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 | + M = Integer.parseInt(st.nextToken()); |
| 15 | + X = Integer.parseInt(st.nextToken()); |
| 16 | + |
| 17 | + arr = new int[N+1][N+1]; // 정방향 (a->b) |
| 18 | + revArr = new int[N+1][N+1]; // 역방향 (a<-b) |
| 19 | + for (int i = 0; i < M; i++) { |
| 20 | + st = new StringTokenizer(br.readLine()); |
| 21 | + int a = Integer.parseInt(st.nextToken()); |
| 22 | + int b = Integer.parseInt(st.nextToken()); |
| 23 | + int c = Integer.parseInt(st.nextToken()); |
| 24 | + arr[a][b] = c; |
| 25 | + revArr[b][a] = c; |
| 26 | + } |
| 27 | + |
| 28 | + int[] fromX = dijkstra(X); |
| 29 | + |
| 30 | + arr = revArr; |
| 31 | + int[] toX = dijkstra(X); |
| 32 | + |
| 33 | + int answer = 0; |
| 34 | + for (int i = 1; i <= N; i++) { |
| 35 | + answer = Math.max(answer, fromX[i] + toX[i]); |
| 36 | + } |
| 37 | + System.out.println(answer); |
| 38 | + br.close(); |
| 39 | + } |
| 40 | + |
| 41 | + private static int[] dijkstra(int start) { |
| 42 | + int[] dist = new int[N+1]; |
| 43 | + Arrays.fill(dist, Integer.MAX_VALUE); |
| 44 | + dist[start] = 0; |
| 45 | + PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() { |
| 46 | + @Override |
| 47 | + public int compare(int[] o1, int[] o2) { |
| 48 | + return Integer.compare(o1[0], o2[0]); |
| 49 | + } |
| 50 | + }); |
| 51 | + pq.offer(new int[] {0, start}); // (cost, node) |
| 52 | + while (!pq.isEmpty()) { |
| 53 | + int[] info = pq.poll(); |
| 54 | + int node = info[1]; |
| 55 | + for (int nextNode = 1; nextNode <= N; nextNode++) { |
| 56 | + if (arr[node][nextNode] == 0) continue; |
| 57 | + int newDist = dist[node] + arr[node][nextNode]; |
| 58 | + if (dist[nextNode] > newDist) { |
| 59 | + dist[nextNode] = newDist; |
| 60 | + pq.offer(new int[] {newDist, nextNode}); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + return dist; |
| 65 | + } |
| 66 | +} |
| 67 | +``` |
0 commit comments