码迷,mamicode.com
首页 > 其他好文 > 详细

OpenJudge 兔子与樱花

时间:2018-12-01 15:36:19      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:from   分享图片   时间复杂度   pat   路径   void   open   ace   sys   

技术分享图片

技术分享图片

【题解】

        求任意两点间的最短路径。此题数据量较小,用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 兔子与樱花

标签:from   分享图片   时间复杂度   pat   路径   void   open   ace   sys   

原文地址:https://www.cnblogs.com/Jeffrey-Y/p/10048841.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!