这道题先直接求出每个点到其他点的最短距离,然后再枚举每一种组合。可以用dijkstra或者floyed都行!
http://acm.ustc.edu.cn/ustcoj/problem.php?id=1123
team579 | Accepted | Java | 1600ms | 27672kb | 2307 |
import java.util.Arrays; import java.util.Scanner; public class Main { private static int n; private static int[][] dist = new int[501][501]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testNum = sc.nextInt(); for (int i = 0; i < testNum; i++) { n = sc.nextInt(); int e = sc.nextInt(); int[][] map = new int[e + 1][e + 1]; boolean[] visted = new boolean[n + 1]; for (int j = 1; j <= e; j++) { int a = sc.nextInt(); int b = sc.nextInt(); int t = sc.nextInt(); if (a == b) continue; else if (map[a][b] == 0) { map[a][b] = t; map[b][a] = t; } else if (map[a][b] != 0 && map[a][b] > t) { map[a][b] = t; map[b][a] = t; } } solve(map, visted); } } public static void solve(int[][] map, boolean[] visted) { int sum = Integer.MAX_VALUE; int ans1 = -1; int ans2 = -1; for (int i = 1; i <= n; i++) { dijkstra(map, visted, dist[i], i); } for (int i = 1; i < n; i++) { for (int j = i + 1; j <= n; j++) { int tempSum = 0; for (int k = 1; k <= n; k++) { if (dist[i][k] != Integer.MAX_VALUE && dist[j][k] != Integer.MAX_VALUE && k != i && k != j) { if (dist[i][k] > dist[j][k]) { tempSum += dist[j][k]; } else { tempSum += dist[i][k]; } } } if (sum > tempSum) { sum = tempSum; ans1 = i; ans2 = j; } } } System.out.println(ans1 + " " + ans2); } public static void dijkstra(int[][] map, boolean[] visted, int[] dist, int s) { Arrays.fill(visted, false); Arrays.fill(dist, Integer.MAX_VALUE); for (int i = 1; i <= n; i++) { if (map[s][i] != 0 && !visted[i]) dist[i] = map[s][i]; } visted[s] = true; int temp = 0; while (true) { int min = Integer.MAX_VALUE; temp = 0; for (int i = 1; i <= n; i++) { if (!visted[i] && min > dist[i]) { min = dist[i]; temp = i; } } if (temp == 0) break; visted[temp] = true; for (int i = 1; i <= n; i++) { if (!visted[i] && map[temp][i] != 0 && dist[i] > dist[temp] + map[temp][i]) { dist[i] = dist[temp] + map[temp][i]; } } } } }