hdu 2544 最短路
SPFA
#include<stdio.h> #include<math.h> #include<string.h> #include<vector> #include<algorithm> using namespace std; const int maxn = 2222; vector<int>abc[maxn]; int s[maxn][maxn]; int js[maxn]; struct aaa{ int s, node; }dt[maxn]; bool cmp(const aaa&a, const aaa&b) { return a.s<b.s; } int main() { int n, m; while (~scanf("%d%d", &n, &m)) { if (n == 0 && m == 0) break; int i, u, v, ss, j; for (i = 0; i <= n; i++) for (j = 0; j <= n; j++) s[i][j] = 999999999; for (i = 0; i<maxn; i++) js[i] = 999999999; for (i = 0; i<maxn; i++) abc[i].clear(); for (i = 1; i <= m; i++) { scanf("%d%d%d", &u, &v, &ss); if (ss<s[u][v]) { abc[u].push_back(v); s[u][v] = ss; abc[v].push_back(u); s[v][u] = ss; } } int sx, ex, b = 0; sx = 1; // scanf("%d%d",&sx,&ex); js[sx] = 0;//第一个点 dt[0].node = sx; dt[0].s = 0; for (i = 0; i <= b; i++) { // sort(dt + i, dt + b, cmp); for (j = 0; j<abc[dt[i].node].size(); j++) { int yy = s[dt[i].node][abc[dt[i].node][j]]; if (yy != 0) { if (dt[i].s + yy<js[abc[dt[i].node][j]]) { b++; dt[b].node = abc[dt[i].node][j]; dt[b].s = dt[i].s + yy; js[abc[dt[i].node][j]] = dt[i].s + yy; } } } } ex = n; if (js[ex] == 999999999)printf("%d\n", -1); else printf("%d\n", js[ex]); } return 0; }