加油 ( •̀ ω •́ )y!

POJ 2387 Til the Cows Come Home(最短路模板)

题目链接:http://poj.org/problem?id=2387

题意:有n个城市点,m条边,求n到1的最短路径。n<=1000; m<=2000

  就是一个标准的最短路模板。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<vector>
 5 #include<queue>
 6 
 7 using namespace std;
 8 const int maxn = 2010;
 9 const int INF = 0x3f3f3f3f3f;
10 int n, m;
11 struct node{
12     int to, cost;
13     node() {}
14     node(int a, int b) :to(a), cost(b) {}
15 };
16 vector<node> e[maxn];
17 int vis[maxn], f[maxn], dis[maxn];
18 void SPFA(int s)
19 {
20     for (int i = 0; i < maxn; i++) {
21         vis[i] = 0; f[i] = 0;
22         dis[i] = INF;
23     }
24     dis[s] = 0;
25     vis[s] = 1; f[s]++;
26     queue<int>Q;
27     Q.push(s);
28     while (!Q.empty()) {
29         int t = Q.front(); Q.pop();
30         vis[t] = 0;
31         for (int i = 0; i < e[t].size(); i++) {
32             int tmp = e[t][i].to;
33             if (dis[tmp] > dis[t] + e[t][i].cost) {
34                 dis[tmp] = dis[t] + e[t][i].cost;
35                 if (!vis[tmp]) {
36                     vis[tmp] = 1;
37                     Q.push(tmp);
38                     if (++f[tmp] > n)return;
39                 }
40             }
41         }
42     }
43     return;
44 }
45 int main()
46 {
47     ios::sync_with_stdio(false);
48     while (cin >> m >> n) {
49         for (int a, b, c, i = 1; i <= m; i++) {
50             cin >> a >> b >> c;
51             e[a].push_back(node(b, c));
52             e[b].push_back(node(a, c));
53         }
54         SPFA(1);
55         cout << dis[n] << endl;
56     }
57     return 0;
58 }

 

posted @ 2018-08-18 09:55  皮皮虎  阅读(153)  评论(0编辑  收藏  举报