可以用floyd 直接记录相应路径
太棒了!
http://blog.csdn.net/ice_crazy/article/details/7785111
#include"stdio.h" #include"string.h" int n; int tax[111]; int map[111][111]; int path[111][111]; void floyd() { int temp; int k,i,l; for(i=1;i<=n;i++) for(l=1;l<=n;l++) path[i][l]=l; for(k=1;k<=n;k++) { for(i=1;i<=n;i++) { for(l=1;l<=n;l++) { temp=map[i][k]+map[k][l]+tax[k]; if(temp<map[i][l]) { map[i][l]=temp; path[i][l]=path[i][k]; } else if(temp==map[i][l]) { if(path[i][l]>path[i][k]) path[i][l]=path[i][k]; } } } } } int main() { int i,l; int temp; int s,e; while(scanf("%d",&n),n) { for(i=1;i<=n;i++) for(l=1;l<=n;l++) { scanf("%d",&temp); if(temp==-1) map[i][l]=11111111; else map[i][l]=temp; } for(i=1;i<=n;i++) scanf("%d",&tax[i]); floyd(); while(scanf("%d%d",&s,&e)!=-1) { if(s==-1 && e==-1) break; printf("From %d to %d : ",s,e); printf("Path: %d",s); temp=s; while(temp!=e) { printf("-->%d",path[temp][e]); temp=path[temp][e]; } printf(" "); printf("Total cost : %d ",map[s][e]); } } return 0; }