最短路
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 33752 Accepted Submission(s): 14662
Problem Description
在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?
Input
输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。
输入保证至少存在1条商店到赛场的路线。
Output
对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间
Sample Input
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
Sample Output
3 2
代码1:(floyd)46ms
#include <stdio.h> #include <string.h> #define M 105 #define INF 0x3f3f3f3f int map[M][M], dis[M], n, m; bool vis[M]; int min(int a, int b){ return a<b?a:b; } void floyd(){ int i, j, k; for(k = 1; k <= n; k ++) for(i = 1; i <= n; i ++) for(j = 1; j <= n; j ++) map[i][j] = min(map[i][j], map[i][k]+map[k][j]); } int main(){ while(scanf("%d%d", &n, &m), n||m){ int i, j, a, b, c; for(i = 0; i <= n; i ++){ for(j = 0; j <= n; j ++) map[i][j] = INF; } for(i = 0; i < m; i ++){ scanf("%d%d%d", &a, &b, &c); if(map[a][b] > c){ map[a][b] = map[b][a] = c; } } floyd(); printf("%d\n", map[1][n]); } return 0; }
代码2:(spfa)0ms
#include <stdio.h> #include <string.h> #include <queue> #define M 105 #define INF 0x3f3f3f3f using std::queue; int map[M][M], dis[M], n, m; bool vis[M]; int min(int a, int b){ return a<b?a:b; } void spfa(){ int i, j, pos; for(i = 1; i <= n; i++){ dis[i] = INF; vis[i] = 0; } dis[1] = 0; vis[1] = 1; queue<int >q; q.push(1); while(!q.empty()){ int temp = q.front(); q.pop(); vis[temp] = 0; for(i = 1; i <= n; i ++){ if(dis[i] > dis[temp]+map[temp][i]){ dis[i] = dis[temp]+map[temp][i]; if(!vis[i]){ vis[i] = 1; q.push(i); } } } } } int main(){ while(scanf("%d%d", &n, &m), n||m){ int i, j, a, b, c; for(i = 0; i <= n; i ++) for(j = 0; j <= n; j ++) map[i][j] = INF; for(i = 0; i < m; i ++){ scanf("%d%d%d", &a, &b, &c); if(map[a][b] > c){ map[a][b] = map[b][a] = c; } } spfa(); printf("%d\n", dis[n]); } return 0; }
代码3:(dijstra) 15ms
#include <stdio.h> #include <string.h> #define M 105 #define INF 0x3f3f3f3f int map[M][M], low[M], n, m; bool vis[M]; int dijstra(){ int ans = 0, pos, min, i, j; for(i = 1; i <= n; i ++){ low[i] = map[1][i]; vis[i] = 0; } vis[1] = 0; pos = 1; for(i = 1; i < n; i ++){ min = INF; for(j = 1; j <= n; j ++){ if(!vis[j]&&low[j]<min){ min = low[j]; pos = j; } } ans += min; vis[pos] = 1; for(j = 1; j <= n; j ++){ if(!vis[j]&&low[j] > low[pos]+map[pos][j]) low[j] = low[pos]+map[pos][j]; } } return low[n]; } int main(){ while(scanf("%d%d", &n, &m), n||m){ int i, j, a, b, c; for(i = 0; i <= n; i ++){ for(j = 0; j <= n; j ++) map[i][j] = INF; } for(i = 0; i < m; i ++){ scanf("%d%d%d", &a, &b, &c); if(map[a][b] > c){ map[a][b] = map[b][a] = c; } } printf("%d\n", dijstra()); } return 0; }
时间: 2024-10-13 20:07:01