|
| 1 | +public class JM_72413 { |
| 2 | + static final int INF = Integer.MAX_VALUE; |
| 3 | + static int[][] edge; |
| 4 | + |
| 5 | + public static int floydWarshall(int n, int s, int a, int b) { |
| 6 | + for(int k = 1; k <= n; k++) { |
| 7 | + for(int i = 1; i <= n; i++) { |
| 8 | + if(edge[i][k] == INF) continue; |
| 9 | + for(int j = 1; j <= n; j++) { |
| 10 | + if(edge[k][j] == INF) continue; |
| 11 | + if(edge[i][j] > edge[i][k] + edge[k][j]) { |
| 12 | + edge[i][j] = edge[i][k] + edge[k][j]; |
| 13 | + } |
| 14 | + } |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + int answer = Math.min(INF, edge[s][a] + edge[s][b]); |
| 19 | + for(int i = 1; i <= n; i++) { |
| 20 | + if(i == s) continue; |
| 21 | + int cost = Math.min(INF, edge[s][i] + edge[i][a] + edge[i][b]); |
| 22 | + answer = Math.min(answer, cost); |
| 23 | + } |
| 24 | + |
| 25 | + return answer; |
| 26 | + } |
| 27 | + |
| 28 | + public static int solution(int n, int s, int a, int b, int[][] fares) { |
| 29 | + edge = new int[n + 1][n + 1]; |
| 30 | + |
| 31 | + for(int i = 1; i <= n; i++) { |
| 32 | + for(int j = 1; j <= n; j++) { |
| 33 | + if(i != j) edge[i][j] = INF; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + for(int[] fare : fares) { |
| 38 | + edge[fare[0]][fare[1]] = fare[2]; |
| 39 | + edge[fare[1]][fare[0]] = fare[2]; |
| 40 | + } |
| 41 | + |
| 42 | + return floydWarshall(n, s, a, b); |
| 43 | + } |
| 44 | + |
| 45 | + public static void main(String[] args) { |
| 46 | + System.out.println(solution(6, 4, 6, 2, new int[][] {{4, 1, 10}, {3, 5, 24}, {5, 6, 2}, {3, 1, 41}, {5, 1, 24}, {4, 6, 50}, {2, 4, 66}, {2, 3, 22}, {1, 6, 25}})); |
| 47 | + System.out.println(solution(7, 3, 4, 1, new int[][] {{5, 7, 9}, {4, 6, 4}, {3, 6, 1}, {3, 2, 3}, {2, 1, 6}})); |
| 48 | + System.out.println(solution(6, 4, 5, 6, new int[][] {{2,6,6}, {6,3,7}, {4,6,7}, {6,5,11}, {2,5,12}, {5,3,20}, {2,4,8}, {4,3,9}})); |
| 49 | + } |
| 50 | +} |
0 commit comments