EOJ 139 旅游规划 最短路径算法

题目描述

有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。

输入格式

输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2⩽N⩽500)是城市的个数,顺便假设城市的编号为0−(N−1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。

输出格式

在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。

样例

input

4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20

output

3 40

思路:稍稍改进一下Dijkstra算法,更新到源点距离时,若更新值小于旧值,则在更新距离的基础上一并更新累计收费额;若更新值等于旧值,则更新累计收费额为较小的值。代码如下:

#include <iostream>
#define INF 99999

using namespace std;

struct MAT{
    int dist;
    int toll;
    MAT(int a=INF, int b=0): dist(a), toll(b) {}
};

int main()
{
    int N, M, S, D;
    cin>>N>>M>>S>>D;
    MAT mat[500][500];
    MAT cost[500];
    bool visited[500] = {0};
    for(int i=0, u, v, d, t; i<M; ++i){
        cin>>u>>v>>d>>t;
        mat[u][v].dist = d;
        mat[u][v].toll = t;
        mat[v][u].dist = d;
        mat[v][u].toll = t;
    }
    for(int i=0; i<N; ++i){
        mat[i][i].dist = 0;
        cost[i].dist = mat[i][S].dist;
        cost[i].toll = mat[i][S].toll;
    }
    visited[S] = true;
    for(int i=0; i<N-1; ++i){
        int min_d = INF;
        int index;
        for(int j=0; j<N; ++j){
            if(!visited[j] && cost[j].dist<min_d){
                min_d = cost[j].dist;
                index = j;
            }
        }
        visited[index] = true;
        for(int j=0; j<N; ++j){
            if(!visited[j] && mat[index][j].dist<INF){
                if(cost[index].dist+mat[index][j].dist < cost[j].dist){
                    cost[j].dist = cost[index].dist+mat[index][j].dist;
                    cost[j].toll = cost[index].toll+mat[index][j].toll;
                }
                else if(cost[index].dist+mat[index][j].dist == cost[j].dist)
                    if(cost[j].toll > cost[index].toll+mat[index][j].toll)
                        cost[j].toll = cost[index].toll+mat[index][j].toll;
            }
        }
    }
    cout<<cost[D].dist<<' '<<cost[D].toll;
    return 0;
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值