首页 > 代码库 > 【HDOJ】2544 最短路

【HDOJ】2544 最短路

Dijkstra。

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 #define INF 0xfffffff
 5 
 6 int map[105][105];
 7 int dp[105];
 8 char visit[105];
 9 
10 int main() {
11     int n, m;
12     int i, j, k, min;
13 
14     while (scanf("%d %d",&n,&m)!=EOF && (n||m)) {
15         memset(visit, 0, sizeof(visit));
16         for (i=1; i<=n; ++i)
17             for (j=1; j<=n; ++j)
18                 map[i][j] = INF;
19         while (m--) {
20             scanf("%d %d %d", &i, &j, &k);
21             if (map[i][j] > k)
22                 map[i][j] = map[j][i] = k;
23         }
24         for (i=1; i<=n; ++i)
25             dp[i] = map[1][i];
26         visit[1] = 1;
27         for (i=1; i<n; ++i) {
28             min = INF;
29             for (j=1; j<=n; ++j) {
30                 if ( !visit[j] && dp[j]<min) {
31                     min = dp[j];
32                     k = j;
33                 }
34             }
35             visit[k] = 1;
36             for (j=1; j<=n; ++j) {
37                 if ( !visit[j] && min + map[k][j] < dp[j]) {
38                     dp[j] = min + map[k][j];
39                 }
40             }
41         }
42         printf("%d\n", dp[n]);
43     }
44 
45     return 0;
46 }