寒假Day35:HDU1385-Minimum Transport Cost -Floyd路径输出(输出字典序小的)

题意:

给出一个N;

接下去给出一幅N*N的图,代表每两个城市需要的税费,

接下去再给出每一个城市的税费,

之后给出x和y,求出x到y的最小税费和经过的城市(即输出路径)

样例:

Sample Input
5
0 3 22 -1 4
3 0 5 -1 -1
22 5 0 9 20
-1 -1 9 0 4
4 -1 20 4 0
5 17 8 3 1
1 3
3 5
2 4
-1 -1
0

Sample Output From 1 to 3 : Path: 1-->5-->4-->3 Total cost : 21 From 3 to 5 : Path: 3-->4-->5 Total cost : 16 From 2 to 4 : Path: 2-->1-->5-->4 Total cost : 17

AC代码:

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
#define inf 0x3f3f3f3f

int e[1100][1100],b[1100],path[1100][1100],n;

void floyd()
{
    for(int k=1; k<=n; k++)
    {
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=n; j++)
            {
                int sum=e[i][k]+e[k][j]+b[k];
                if(e[i][j]==sum)
                {
                    if(path[i][j]>path[i][k])//相同路径输出字典序小的
                        path[i][j]=path[i][k];
                }
                else if(e[i][j]>sum)//否则找到更小的就更新权值
                {
                    e[i][j]=sum;
                    path[i][j]=path[i][k];
                }
            }
        }
    }
}

int main()
{
    while(~scanf("%d",&n)&&n)
    {
        memset(path,-1,sizeof(path));//路径的话最好清空为-1
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=n; j++)
            {
                scanf("%d",&e[i][j]);
                if(e[i][j]==-1)
                    e[i][j]=inf;
                else
                    path[i][j]=j;
            }
        }
        for(int 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);
            if(x==y)//询问本身:输出 Path: a\n
                printf("Path: %d\n",x);
            else
            {
                printf("Path: %d-->",x);
                int w=path[x][y];
                while(w!=y)
                {
                    printf("%d-->",w);
                    w=path[w][y];
                }
                printf("%d\n",w);
            }
            printf("Total cost : %d\n\n",e[x][y]);
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/OFSHK/p/12374084.html