有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。
输入格式:
输入说明:输入数据的第 1 行给出 4 个正整数 n、m、s、d,其中 n(2≤n≤500)是城市的个数,顺便假设城市的编号为 0~(n−1);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
就是dijk的模板拓展一下:
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
class node {
public:
int y = 0, w = 0, q = 0;
node(int _y, int _w, int _q) :y(_y), w(_w), q(_q) {}//目的地编号,距离,费用
};
vector<node> g[505];
vector<int> vis;
vector<pair<int, int>> dist;
const int INF = 0x3f3f3f3f;
void dijkstra(int s) {
priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<>> q;
dist[s].first = 0;
dist[s].second = 0;
q.push({ dist[s].first, {dist[s].second, s} });
while (q.size()) {
int x = q.top().second.second;
q.pop();
if (vis[x]) continue;
vis[x] = 1;
for (auto to : g[x]) {
int y = to.y;
int w = to.w;
int tq = to.q;
if (dist[y].first > dist[x].first + w) {
dist[y].first = dist[x].first + w;
dist[y].second = dist[x].second + tq;
q.push({ dist[y].first, {dist[y].second, y} });
}
else if (dist[y].first == dist[x].first + w) {
if (dist[y].second > dist[x].second + tq) {
dist[y].second = dist[x].second + tq;
q.push({ dist[y].first, {dist[y].second, y} });
}
}
}
}
}
int main() {
int n, m, s, d;
cin >> n >> m >> s >> d;
dist.assign(505, { INF,INF });
vis.assign(505, 0);
for (int i = 0; i < m; i++) {
int a, b, w, q;
cin >> a >> b >> w >> q;
g[a].push_back(node(b, w, q));
g[b].push_back(node(a, w, q));
}
dijkstra(s);
cout << dist[d].first << " " << dist[d].second << endl;
return 0;
}