hdu 1385 Minimum Transport Cost 最短路径floyd算法+路径记录 模板题

#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF=100000000;
const int maxn=101;
int e[maxn][maxn],path[maxn][maxn],n,m,s;
int b[maxn];
void floyd()
{
    int i,j,k;
    for(k=1;k<=n;k++)
        for(i=1;i<=n;i++)
            for(j=1;j<=n;j++)
            {
                s=e[i][k]+e[k][j]+b[k];
                if(e[i][j]>s)
                {
                    e[i][j]=s;
                    path[i][j]=path[i][k];
                }
                else if(e[i][j]==s)
                {
                    if(path[i][j]>path[i][k])
                        path[i][j]=path[i][k];
                }
            }
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0)break;
        int i,j,k,a;
        for(i=1;i<=n;i++)
            for(j=1;j<=n;j++)
            if(i==j)e[i][j]=0;
            else e[i][j]=INF;
        for(i=1;i<=n;i++)
            for(j=1;j<=n;j++)
            {
                scanf("%d",&a);
                if(a!=-1)e[i][j]=a;
                path[i][j]=j;
            }
        for(i=1;i<=n;i++)
            scanf("%d",&b[i]);
        floyd();
        int x,y;
        while(scanf("%d%d",&x,&y))
        {
            if(x==-1&&y==-1)break;
            printf("From %d to %d :\n",x,y);
            printf("Path: %d",x);
            k=x;
            while(k!=y)
            {
                printf("-->%d",path[k][y]);
                k=path[k][y];
            }
            printf("\n");
            printf("Total cost : %d\n\n",e[x][y]);
        }
    }
    return 0;
}
/*
    最短路径floyd算法+记录路径
    
*/

你可能感兴趣的:(最短路径)