題目:有一個班級的學生要一起寫作業,所以他們要到一個統一的地點,現在給你他們各自的位置,
問集合地點定在哪,可以讓所有人走的總路徑長度最小。
分析:圖論、最短路。直接利用Floyd計算最短路,找到和值最小的輸出即可。
說明:又是太長時間沒刷題了,╮(╯▽╰)╭。
#include <algorithm> #include <iostream> #include <string> #include <map> using namespace std; int dist[23][23]; int main() { int n, m, u, v, d, cases = 1; string place; while (cin >> n >> m && n+m) { map<int, string>nameList; for (int i = 0; i < n; ++ i) { cin >> place; nameList[i] = place; } for (int i = 0; i < n; ++ i) { for (int j = 0; j < n; ++ j) dist[i][j] = 500000; dist[i][i] = 0; } for (int i = 0; i < m; ++ i) { cin >> u >> v >> d; dist[u-1][v-1] = dist[v-1][u-1] = d; } for (int k = 0; k < n; ++ k) for (int i = 0; i < n; ++ i) for (int j = 0; j < n; ++ j) if (dist[i][j] > dist[i][k]+dist[k][j]) dist[i][j] = dist[i][k]+dist[k][j]; int space = 0, max = 500000; for (int i = 0; i < n; ++ i) { int sum = 0; for (int j = 0; j < n; ++ j) if (i != j) sum += dist[i][j]; if (max > sum) { max = sum; space = i; } } cout << "Case #" << cases ++ << " : " << nameList[space] << endl; } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-07 12:22:12