|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.InputStreamReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.Comparator; |
| 7 | +import java.util.LinkedList; |
| 8 | +import java.util.PriorityQueue; |
| 9 | +import java.util.Queue; |
| 10 | +import java.util.StringTokenizer; |
| 11 | + |
| 12 | +public class Main { |
| 13 | + |
| 14 | + static int N,M,X; |
| 15 | + static ArrayList<int []> A[]; |
| 16 | + static int INF = Integer.MAX_VALUE; |
| 17 | + public static void main(String[] args) throws IOException { |
| 18 | + |
| 19 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 20 | + |
| 21 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 22 | + |
| 23 | + N = Integer.parseInt(st.nextToken()); |
| 24 | + M = Integer.parseInt(st.nextToken()); |
| 25 | + X = Integer.parseInt(st.nextToken()); |
| 26 | + |
| 27 | + A = new ArrayList[N+1]; |
| 28 | + |
| 29 | + for(int i =1; i<=N; i++) { |
| 30 | + A[i] = new ArrayList<>(); |
| 31 | + } |
| 32 | + |
| 33 | + for(int i =0; i<M; i++) { |
| 34 | + st = new StringTokenizer(br.readLine()); |
| 35 | + |
| 36 | + int u = Integer.parseInt(st.nextToken()); |
| 37 | + int v = Integer.parseInt(st.nextToken()); |
| 38 | + int w = Integer.parseInt(st.nextToken()); |
| 39 | + |
| 40 | + A[u].add(new int[]{ v,w}); |
| 41 | + } |
| 42 | + |
| 43 | + int answer = Integer.MIN_VALUE; |
| 44 | + for(int i =1; i<=N; i++) { |
| 45 | + if(i ==X) continue; |
| 46 | + answer = Math.max(answer, dijkstra(i, X) + dijkstra(X, i)); |
| 47 | + } |
| 48 | + |
| 49 | + System.out.println(answer); |
| 50 | + } |
| 51 | + static int dijkstra(int startNode, int endNode) { |
| 52 | + |
| 53 | + int diff[] = new int[N+1]; |
| 54 | + |
| 55 | + Arrays.fill(diff, INF); |
| 56 | + |
| 57 | + diff[startNode] = 0; |
| 58 | + |
| 59 | + PriorityQueue<int []> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1])); |
| 60 | + |
| 61 | + pq.add(new int[] {startNode, 0}); |
| 62 | + |
| 63 | + while(!pq.isEmpty()) { |
| 64 | + |
| 65 | + int now[] = pq.poll(); |
| 66 | + |
| 67 | + int currentNode= now[0]; |
| 68 | + int currentValue = now[1]; |
| 69 | + |
| 70 | + if(diff[currentNode] < currentValue) { |
| 71 | + continue; |
| 72 | + } |
| 73 | + for(int next[]: A[currentNode]) { |
| 74 | + int nextNode = next[0]; |
| 75 | + int nextValue = next[1]; |
| 76 | + |
| 77 | + if(diff[nextNode] > diff[currentNode] + nextValue) { |
| 78 | + diff[nextNode] = diff[currentNode] + nextValue; |
| 79 | + pq.add(new int[] {nextNode, diff[nextNode]}); |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + return diff[endNode]; |
| 84 | + } |
| 85 | +} |
0 commit comments