标签:最短路
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
3 2
#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; }
#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; }
#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; }
标签:最短路
原文地址:http://blog.csdn.net/shengweisong/article/details/41013987