【最短路径-Floyd+路径】hdu 1385

来源:互联网 发布:cms采集电影采集 编辑:程序博客网 时间:2024/05/19 23:16

http://acm.hdu.edu.cn/showproblem.php?pid=1385

#include<iostream>#include<cstdio>using namespace std;const int NM=1005;const int MAX=0x3fffffff;int tax[NM],a[NM][NM],path[NM][NM],n;void Floyd(){int i,j,k,t;for(i=1;i<=n;i++)  for(j=1;j<=n;j++)path[i][j]=j;   //保存最近的路径for(k=1;k<=n;k++)for(i=1;i<=j;i++)if(a[i][k]!=MAX){for(j=1;j<=n;j++){t=a[i][k]+a[k][j]+tax[k];if(t<a[i][j]){a[i][j]=t;path[i][j]=path[i][k];}else if(t==a[i][j])  //{if(path[i][k]<path[i][j])path[i][j]=path[i][k];}}}}int main(){int i,j,x,y,k;while(scanf("%d",&n)&&n){for(i=1;i<=n;i++){for(j=1;j<=n;j++){scanf("%d",&a[i][j]);if(a[i][j]==-1)a[i][j]=MAX;}}for(i=1;i<=n;i++)scanf("%d",&tax[i]);Floyd();while(scanf("%d%d",&x,&y)&&x>-1&&y>-1){printf("From %d to %d :\n",x,y);printf("Path: %d",x);  //注意到自身的路径k=x;while(k!=y){k=path[k][y];printf("-->%d",k);}printf("\nTotal cost : %d\n\n",a[x][y]);}}return 0;}

缺点:求单对源结点效率太低,为O(n^3)