1. 程式人生 > >OpenJudge 兔子與櫻花

OpenJudge 兔子與櫻花

ima pac spa pause img bsp != == point

技術分享圖片

技術分享圖片

【題解】

求任意兩點間的最短路徑。此題數據量較小,用Floyd算法,時間復雜度為O(n^3)。

參考https://blog.csdn.net/qq_34594236/article/details/64971883

【代碼】

 1 #include <iostream>
 2 #include <map>
 3 #include <string>
 4 #define maxn 50
 5 #define INF 100000
 6 using namespace std;
 7 
 8 int dist[50][50], path[50][50];
9 map<string, int> map1; 10 map<int, string>map2; 11 12 void init() 13 { 14 int P, Q; 15 string scene; 16 for (int i = 0; i < maxn; i++) { 17 for (int j = 0; j < maxn; j++) { 18 dist[i][j] = INF; 19 path[i][j] = j; // denotes the next point from point i on the shortest path from i to j
20 } 21 dist[i][i] = 0; 22 } 23 cin >> P; 24 for (int i = 0; i < P; i++) { 25 cin >> scene; 26 map1[scene] = i; 27 map2[i] = scene; 28 } 29 cin >> Q; 30 for (int i = 0; i < Q; i++) { 31 string t1, t2; 32 int
d; 33 cin >> t1 >> t2 >> d; 34 dist[map1[t1]][map1[t2]] = dist[map1[t2]][map1[t1]] = d; 35 } 36 } 37 38 void floyd() 39 { 40 for(int k = 0; k < maxn; k++) 41 for(int i = 0; i < maxn; i++) 42 for (int j = 0; j < maxn; j++) { 43 if (dist[i][j] > dist[i][k] + dist[k][j]) { 44 dist[i][j] = dist[i][k] + dist[k][j]; 45 path[i][j] = path[i][k]; 46 } 47 } 48 } 49 50 int main() 51 { 52 int R; 53 init(); 54 floyd(); 55 cin >> R; 56 for (int i = 0; i < R; i++) { 57 string t1, t2; 58 int k; 59 cin >> t1 >> t2; 60 if (t1 == t2) { 61 cout << t1 << endl; 62 continue; 63 } 64 k = path[map1[t1]][map1[t2]]; 65 cout << t1 << "->(" << dist[map1[t1]][k] << ")->"; 66 while (k != map1[t2]) { 67 cout << map2[k] << "->(" << dist[k][path[k][map1[t2]]] << ")->"; 68 k = path[k][map1[t2]]; 69 } 70 cout << t2 << endl; 71 } 72 //system("pause"); 73 return 0; 74 }

OpenJudge 兔子與櫻花