单源最短路径,Dijkstra,参考白书的写法;
注意INF不能定义为0x7fffffff,因为后面相加可能会溢出,题目中距离最大为10000;
这道题的变态之处在于有重边,遇到重边时需要更新w[i, j]和w[j, i],WA多次,15ms。
# include <stdio.h> # include <string.h> # define INF 0x10ffffff int main() { int k, i, j, n, m, s, t; char v[201]; int x, d[201], w[201][201]; while (~scanf("%d%d", &n, &m)) { for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) w[i][j] = INF; for (k = 0; k < m; ++k) { scanf("%d%d%d", &i, &j, &x); if (w[i][j] > x) w[j][i] = w[i][j] = x; } scanf("%d%d", &s, &t); if (s == t) {puts("0"); continue;} memset(v, 0, sizeof(v)); for (k = 0; k < n; ++k) d[k] = INF; d[s] = 0; for (k = 0; k < n; ++k) { x = INF; for (j = 0; j < n; ++j) if (!v[j] && d[j]<=x) x = d[i=j]; v[i] = 1; for (j = 0; j < n; ++j) if (d[j] > (m=d[i]+w[i][j])) d[j] = m; } if (d[t] < INF) printf("%d\n", d[t]); else puts("-1"); } return 0; }