http://acm.hdu.edu.cn/showproblem.php?pid=1874
这题坑在于会出现重边,必须保留小的那个
#include<stdio.h> #include<string.h> #define MAX 9999999 int map[1000][1000]; int vertex,edge; void init() { int i,j; for(i=0;i<vertex;i++) for(j=0;j<vertex;j++) if(i==j)map[i][j]=0; else map[i][j]=MAX;//起点跟终点一致,说明可以0费用,否则就先初始化为最大 } int floyd() { int i,j,k,sum; for(k=0;k<vertex;++k) for(i=0;i<vertex;++i) for(j=0;j<vertex;++j) { sum=map[i][k]+map[k][j]; if(sum<map[i][j]) { map[i][j]=sum;//如果存在k点使得ij路径可松弛,那么就更新这条路径上的数据 } } } int main() { int i,j,x,y,w; while(scanf("%d%d",&vertex,&edge)!=EOF) { init(); for(i=0;i<edge;i++) { scanf("%d%d%d",&x,&y,&w); if(map[x][y]>w) map[x][y]=map[y][x]=w; } floyd(); scanf("%d%d",&x,&y); if(map[x][y]>=MAX)printf("-1 "); else printf("%d ",map[x][y]); } return 0; }