HDU 2544 最短路 http://acm.hdu.edu.cn/showproblem.php?pid=2544
//代码: //方法1:Dijkstra's Algorithm #include<stdio.h> #include<math.h> #include<string.h> #define INF 0xfffffff #define N 110 #define min(a, b)(a < b ? a : b) int maps[N][N]; int d[N], visit[N]; int n, m; void Init() { int i, j; memset(visit, 0, sizeof(visit)); for(i = 1 ; i <= n ; i++) { d[i] = INF; for(j = 1 ; j <= n ; j++) maps[i][j] = INF; } } void Dij() { int i, j, x, min; d[1] = 0; for(i = 1 ; i <= n ; i++) { min = INF; for(j = 1 ; j <= n ; j++) { if(!visit[j] && d[j] < min) { min = d[j]; x = j; } } visit[x] = 1; for(j = 1 ; j <= n ; j++) { if(!visit[j] && d[j] > d[x] + maps[x][j]) d[j] = d[x] + maps[x][j]; } } } int main() { int i, a, b, c; while(scanf("%d%d", &n, &m), m + n != 0) { Init(); for(i = 1 ; i <= m ; i++) { scanf("%d%d%d", &a, &b, &c); maps[a][b] = min(maps[a][b], c); maps[b][a] = maps[a][b]; } Dij(); printf("%d\n", d[n]); } return 0; }//单元最短路 //方法2:弗洛伊德算法 #include<stdio.h> #include<string.h> #define N 110 #define INF 0xfffffff #define min(a, b) (a < b ? a : b) int maps[N][N]; int n, m; void Init() { int i, j; for(i = 1 ; i <= n ; i++) for(j = 1 ; j <= n ; j++) maps[i][j] = INF; } void Floyd() { int i, k, j; for(k = 1 ; k <= n ; k++) { for(i = 1 ; i <= n ; i++) { for(j = 1 ; j <= n ; j++) maps[i][j] = min(maps[i][j], maps[i][k] + maps[k][j]); } } } int main() { int a, b, c, i; while(scanf("%d%d", &n, &m), m + n != 0) { Init(); for(i = 1 ; i <= m ; i++) { scanf("%d%d%d", &a, &b, &c); maps[a][b] = min(maps[a][b], c); maps[b][a] = maps[a][b]; } Floyd(); printf("%d\n", maps[1][n]); } return 0; }//多元最短路