PTA 7-10(图) 旅游规划 最短路问题

7-10(图) 旅游规划 (25 分)

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

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

3 40

思路:简单的最短路问题,dijkstra算法稍加修改就可以过掉

AC代码:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstdio>
#include <malloc.h>

#define INF 0x3f3f3f3f
#define FRER() freopen("in.txt", "r", stdin)
#define FREW() freopen("out.txt", "w", stdout)

using namespace std;

const int maxn = 500 + 5;

struct edge{
    int v, l, w;
    edge(int v, int l, int w):v(v), l(l), w(w) {}
    friend bool operator < (edge a, edge b) {
        return a.l > b.l;
    }
};

vector<edge> g[maxn];
int n, m, s, d, u, v, l, w, vis[maxn], len[maxn], price[maxn];

void dijkstra() {
    memset(len, INF, sizeof(len));
    priority_queue<edge> q;
    q.push(edge(s, 0, 0));
    while(!q.empty()) {
        edge tmp = q.top(); q.pop();
        if(vis[tmp.v]) {
            if(tmp.l > len[tmp.v] || (tmp.l == len[tmp.v] && tmp.w >= price[tmp.v]))
                continue;
        }
        len[tmp.v] = tmp.l;
        price[tmp.v] = tmp.w;
        vis[tmp.v] = true;
        for(int i = 0; i < g[tmp.v].size(); ++i) {
            if(tmp.l + g[tmp.v][i].l < len[g[tmp.v][i].v] || (tmp.l + g[tmp.v][i].l == len[g[tmp.v][i].v] && tmp.w + g[tmp.v][i].w < price[g[tmp.v][i].v]))
            q.push(edge(g[tmp.v][i].v, tmp.l + g[tmp.v][i].l, tmp.w + g[tmp.v][i].w));
        }
    }
}

int main()
{
    cin >> n >> m >> s >> d;
    while(m--) {
        cin >> u >> v >> l >> w;
        g[u].push_back(edge(v, l, w));
        g[v].push_back(edge(u, l, w));
    }
    dijkstra();
    cout << len[d] << ' ' << price[d] << endl;
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/fan-jiaming/p/10086619.html