hdu-2544-最短路(SPFA模板)
题意很清晰,入门级题目,适合各种模板,可用dijkstra, floyd, Bellman-ford, spfa
1 /* 2 Name:HDU-2544-最短路 3 Copyright: 4 Author: 5 Date: 2018/4/17 10:34:47 6 Description: 7 SPFA 8 */ 9 #include <cstring> 10 #include <cstdio> 11 #include <iostream> 12 #include <vector> 13 #include <queue> 14 #include <utility> 15 using namespace std; 16 const int MAXN = 1010; 17 int n, m; 18 vector <pair<int, int>> g[MAXN]; 19 int dist[MAXN]; 20 bool inQue[MAXN]; 21 queue<int> que; 22 void spfa() { 23 memset(inQue, 0, sizeof(inQue)); 24 memset(dist, 0x3f, sizeof(dist)); 25 dist[1] = 0; 26 while (!que.empty()) que.pop(); 27 que.push(1); 28 inQue[1] = true; 29 while (!que.empty()) { 30 int u = que.front(); 31 que.pop(); 32 inQue[u] = false; 33 for (int i=0; i<g[u].size(); i++) { 34 if(dist[u]+g[u][i].second < dist[g[u][i].first]) { 35 dist[g[u][i].first] = dist[u] + g[u][i].second; 36 if (!inQue[g[u][i].first]) { 37 inQue[g[u][i].first] = true; 38 que.push(g[u][i].first); 39 } 40 } 41 } 42 } 43 } 44 int main() 45 { 46 // freopen("in.txt", "r", stdin); 47 while (~scanf("%d %d", &n, &m) && (n+m)) { 48 for (int i=0; i<=100; i++) { 49 while (!g[i].empty()) {// while 50 g[i].pop_back(); 51 } 52 } 53 for (int i=1; i<=m; i++) { 54 int a, b, c; 55 scanf("%d %d %d", &a, &b, &c); 56 g[a].push_back(make_pair(b, c)); 57 g[b].push_back(make_pair(a, c)); 58 } 59 spfa(); 60 printf("%d\n", dist[n]); 61 } 62 return 0; 63 }