有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。
输入格式:
输入说明:输入数据的第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
#include <iostream>
#include <algorithm>
using namespace std;
int N, M, S, D;
int totLen[500] = { 0 }, totCost[500] = { 0 }, Len[500][500], Cost[500][500], vis[500] = { 0 };
//len:存城市之间的道路长度;
//cost:存城市之间道路的费用;
//totalLen存出发城市到每个城市的距离;
//totalCost存出发城市到每个城市的收费额
//vis标记数组
void dijkstra() {
vis[S] = 1; //标记走过的点
for (int i = 0; i < N - 1; ++i) {
int minLen = 99999, pass;
for (int j = 0; j < N; ++j) //求离当前城市最近的城市:pass
if (!vis[j] && totLen[j] < minLen) {
minLen = totLen[j];
pass = j;
}
vis[pass] = 1; //标记走过的点
for (int to = 0; to < N; ++to)
if (!vis[to] && (totLen[to] > totLen[pass] + Len[pass][to] || totLen[to] == totLen[pass] + Len[pass][to] && totCost[to] > totCost[pass] + Cost[pass][to])) {
totLen[to] = totLen[pass] + Len[pass][to];
totCost[to] = totCost[pass] + Cost[pass][to];
}
}
}
int main() {
cin >> N >> M >> S >> D;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
if (i != j)
Len[i][j] = Cost[i][j] = 500; //初始化各个城市之间不可达;
for (int i = 0; i < M; ++i) {
int c1, c2, len, cost;
cin >> c1 >> c2 >> len >> cost; //构建可达城市之间的联系
Len[c1][c2] = Len[c2][c1] = min(Len[c1][c2], len);
Cost[c1][c2] = Cost[c2][c1] = min(Cost[c1][c2], cost);
}
for (int i = 0; i < N; ++i) { //构建出发地与各个城市之间的联系:可达/不可达
totLen[i] = Len[S][i];
totCost[i] = Cost[S][i];
}
dijkstra();
cout << totLen[D] << " " << totCost[D];
return 0;
}