hdu 1385 Minimum Transport Cost(floyd打印最小字典序的最短路径)

题目地址

题目大意:以矩阵的形式输入点边关系,-1代表没边,且通过点需要交费,求总花销最小,如果有多种最短路,打印字典序最小的那种

解题思路:floyd,path[i][j]表示i到j的最短路在i之后的最小字典序的点编号,更新的时候加上边相等的时候再更新一下点的字典序

#include <iostream>
#include <cstdio>
using namespace std;

const int INF = 0xfffffff;
const int maxn = 105;
int n;
int edge[maxn][maxn];
int path[maxn][maxn];///path[i][j]表示从i到j的最短路径的i点之后的点
int charge[maxn];

void floyd()
{
    for(int k = 1; k <= n; k++)
    {
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++)
            {
               if(edge[i][j] > edge[i][k]+edge[k][j]+charge[k])
               {
                   edge[i][j] = edge[i][k]+edge[k][j]+charge[k];
                   path[i][j] = path[i][k];
               }
               else if(edge[i][j] == edge[i][k]+edge[k][j]+charge[k] && path[i][j]>path[i][k])
                path[i][j] = path[i][k];
            }
        }
    }
}

int main()
{
    while(scanf("%d",&n),n)
    {
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++)
            {
                scanf("%d",&edge[i][j]);
                if(edge[i][j] == -1)
                    edge[i][j] = INF;
                path[i][j] = j;
            }
        }
        for(int i = 1; i <= n; i++)
            scanf("%d",&charge[i]);

        floyd();
        int from,to;
        while(scanf("%d%d",&from,&to))
        {
            if(from == -1 && to == -1)  break;
            printf("From %d to %d :\n",from,to);
            printf("Path: ");
            int cur = from;
            printf("%d",cur);
            while(cur != to)
            {
                printf("-->%d",path[cur][to]);
                cur = path[cur][to];
            }
            puts("");
            printf("Total cost : %d\n\n", edge[from][to]);
        }
    }
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值