*/-->
pre.src {background-color: Black; color: White;}
pre.src {background-color: Black; color: White;}
pre.src {background-color: Black; color: White;}
hdu2544 最短路径
http://acm.hdu.edu.cn/status.php
错误 1:inf 开太小
错误 2:spfa 最后忘记了 inQue[u] = 0;
错误 3:spfa
for (int i = 1; i <= n; i++) { while (g[i].size()) { g[i].pop_back(); } }
/* CreateTime: 2015-04-07 10:53:26 */ #include <cstdio> int n; int m; int g[105][105]; const int inf = 0x3fffffff; int dis[105]; int v[105]; int min(int a, int b) { if (a < b) return a; return b; } void dij() { for (int i = 1; i <= n; i++) { dis[i] = inf; v[i] = 0; } dis[1] = 0; for (int i = 1; i <= n; i++) { int mark = -1; int mindir = inf; for (int j = 1; j <= n; j++) { if (!v[j] && dis[j] < mindir) { mark = j; mindir = dis[j]; } } v[mark] = 1; for (int j = 1; j <= n; j++) { if (!v[j]) { dis[j] = min(dis[j], g[mark][j]+dis[mark]); } } } } int main(void) { while (scanf("%d%d", &n, &m) && n && m) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { g[i][j] = inf; } } for (int i = 1; i <= m; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); g[a][b] = g[b][a] = c; } dij(); printf("%d\n", dis[n]); } return 0; }
/* CreateTime: 2015-04-07 11:06:58 */ #include <cstdio> #include <vector> #include <queue> using namespace std; int n; int m; queue<int> que; vector<pair<int, int> > g[105]; int dis[105]; const int inf = 0x3fffffff; int inQue[105]; void spfa() { for (int i = 1; i <= n; i++) { dis[i] = inf; } while (!que.empty()) { que.pop(); } que.push(1); inQue[1] = 1; dis[1] = 0; while (!que.empty()) { int u = que.front(); que.pop(); int num = g[u].size(); for (int t = 0; t < num; t++) { int i = u; int j = g[u][t].first; int w = g[u][t].second; if (dis[i] + w < dis[j]) { dis[j] = dis[i] + w; if (!inQue[j]) { inQue[j] = 1; que.push(j); } } } inQue[u] = 0; } } int main(void) { while (scanf("%d%d", &n, &m) && n && m) { for (int i = 1; i <= n; i++) { while (g[i].size()) { g[i].pop_back(); } } for (int i = 0; i < m; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); g[a].push_back(make_pair(b, c)); g[b].push_back(make_pair(a, c)); } spfa(); printf("%d\n", dis[n]); } return 0; }
/* CreateTime: 2015-04-07 11:43:01 */ #include <cstdio> int g[105][105]; int n; int m; #define inf 0x3fffffff int min(int a, int b) { if(a < b) return a; return b; } void floy() { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { g[i][j] = inf; } } for (int i = 1; i <= m; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); g[a][b] = g[b][a] = c; } for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (g[i][k] < inf && g[k][j] < inf) { g[i][j] = min(g[i][j], g[i][k]+g[k][j]); } } } } } int main(void) { while (scanf("%d%d", &n, &m) && n && m) { floy(); printf("%d\n", g[1][n]); } return 0; }
时间: 2024-10-23 12:40:47