nyoj-115-城市平乱(dijkstra算法)

 题目链接

 1 /*
 2     Name:nyoj-115-城市平乱
 3     Copyright:
 4     Author:
 5     Date: 2018/4/25 17:28:06
 6     Description:
 7     dijkstra模板题
 8     枚举从部队所在的城市到叛乱城市取最小值 
 9 */
10 #include <iostream>
11 #include <cstdio>
12 #include <cstring>
13 #include <cmath>
14 using namespace std;
15 const int MAXN = 1005, INF= 0x3f3f3f3f;
16 int dis[MAXN], g[MAXN][MAXN], N, M, P, Q, army[MAXN], src;
17 bool v[MAXN];
18 
19 void dijkstra() {
20     int N = M;
21     for (int i=1; i<=N; i++) dis[i] = INF;
22     dis[src] = 0;
23     memset(v, 0, sizeof(v));
24     for (int i=1; i<=N; ++i) {
25         int mark =-1, mindis=INF;
26         for (int j=1; j<=N; j++) {
27             if(!v[j] && dis[j]<mindis) {
28                 mindis = dis[j];
29                 mark = j;
30             }
31         }
32         v[mark] = 1;
33         for (int j=1; j<=N; j++) {
34             if (!v[j]) {
35                 dis[j] = min(dis[j], dis[mark] + g[mark][j]);
36             }
37         }
38     }
39 }
40 int main()
41 {
42     int t;
43     cin>>t;
44     while (t--) {
45         memset(g, 0x3f, sizeof(g));
46         memset(army, 0, sizeof(army));
47         cin>>N>>M>>P>>Q;
48          for (int i=0; i<N; i++) {
49              cin>>army[i];
50          }
51          for (int i=0; i<P; i++) {
52              int x, y, cost;
53              cin>>x>>y>>cost;
54             if (g[x][y]  < cost) continue;
55             g[x][y] = cost;
56             g[y][x] = cost;
57          }
58          int mindis = 0x3f3f3f3f;
59          for (int i=0; i<N; i++) {
60              memset(dis, 0, sizeof(dis));
61              src = army[i];
62              dijkstra();
63              mindis = min(mindis, dis[Q]);
64          }
65          cout<<mindis<<endl;
66     }
67     return 0;
68 }

 

posted @ 2018-04-27 16:55  朤尧  阅读(235)  评论(0编辑  收藏  举报