2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
3 2
直接就是一个Dijkstra的裸模板而已
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int inf = 1<<30; int n,m; int map[105][105]; int vis[105],cast[105]; void Dijkstra(int s,int e) { int i,j,min,pos; memset(vis,0,sizeof(vis)); cast[s] = 0; vis[s] = 1; for(i = 0; i<n; i++) cast[i] = map[s][i]; for(i = 1; i<n; i++) { min = inf; for(j = 0; j<n; j++) { if(cast[j]<min && !vis[j]) { pos = j; min = cast[j]; } } vis[pos] = 1; for(j = 0; j<n; j++) { if(cast[pos]+map[pos][j]<cast[j] && !vis[j]) cast[j] = cast[pos]+map[pos][j]; } } } int main() { int i,j,x,y,z,start,end; while(~scanf("%d%d",&n,&m),n+m) { for(i = 0; i<105; i++) { for(j = 0; j<105; j++) map[i][j] = inf; map[i][i] = 0; } while(m--) { scanf("%d%d%d",&x,&y,&z); x--; y--; if(z<map[x][y]) map[x][y] = map[y][x] = z; } start = 0; end = n-1; Dijkstra(start,end); printf("%d\n",cast[end]==inf?-1:cast[end]); } return 0; }