题目链接:
题目描述:
A traveler's map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (≤500) is the number of cities (and hence the cities are numbered from 0 to N−1); M is the number of highways; S and D are the starting and the destination cities, respectively. Then M lines follow, each provides the information of a highway, in the format:
City1 City2 Distance Cost
where the numbers are all integers no more than 500, and are separated by a space.
Output Specification:
For each test case, print in one line the cities along the shortest path from the starting point to the destination, followed by the total distance and the total cost of the path. The numbers must be separated by a space and there must be no extra space at the end of output.
Sample 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
Sample Output:
0 2 3 3 40
样例说明:
思路:
1. 最短路径的一道题,要输出最短路径,Dijkstra+DFS, Dijkstra求最短路,DFS打印最短路。
2. 因为同时还要求最小花费,所以如果最短路条数不唯一,则还需要看当前路径是否花费更小。
3. 因为要打印出最短路径,所以要将S到达D点的前序路径都保存下来,再通过DFS深度遍历输出路径。
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 505, inf = 0x3f3f3f3f;
int G[maxn][maxn], d[maxn], c[maxn], cost[maxn][maxn], pre[maxn], minCost; // G邻接矩阵,d最短距离,cost花费,pre保存前序路径
int n, m, S, D;
bool vis[maxn]; // vis当前城市是否访问过
void Dijkstra(int s)
{
// 初始化d,c
fill(d, d + maxn, inf);
fill(c, c + maxn, inf);
d[s] = 0; // 到自身的距离为0
c[s] = 0; // 到自身的花费为0
for (int i = 0; i < n; i++) { // 对每个城市都进行一次dijkstra
int MIN = inf, u = -1;
for (int j = 0; j < n; j++) { // 查找未访问过的城市中距离最小的
if (!vis[j] && d[j] < MIN) {
MIN = d[j];
u = j;
}
}
if (u == -1) // 未找到直接返回
return;
vis[u] = true; // 标记当前城市已访问
for (int j = 0; j < n; j++) { // 遍历n个城市
if (!vis[j] && G[u][j] != inf) { // 能直接到达且未访问过的城市
if (d[u] + G[u][j] < d[j]) { // 如果当前路径到达的距离比之前的小
d[j] = d[u] + G[u][j]; // 更新最短路径
c[j] = c[u] + cost[u][j]; // 更新花费
pre[j] = u; // 更新前序路径
} else if (d[u] + G[u][j] == d[j]) { // 如果最短路不唯一
if (c[j] > c[u] + cost[u][j]) { // 如果当前路径花费比之前的小
c[j] = c[u] + cost[u][j]; // 更新花费
pre[j] = u; // 更新前序路径
}
}
}
}
}
}
void DFS(int u) // 从终点开始递归打印路径
{
if (u == S) { // 如果到达起点, 输出起点城市并返回
printf("%d ", u);
return;
}
DFS(pre[u]); // 否则递归查找前序路径
printf("%d ", u); // 输出经过的城市
}
int main()
{
fill(G[0], G[0] + maxn * maxn, inf);
cin >> n >> m >> S >> D;
for (int i = 0; i < m; i++) {
int a, b, dis, w;
cin >> a >> b >> dis >> w;
G[a][b] = G[b][a] = dis; // 距离赋值
cost[a][b] = cost[b][a] = w; // 花费赋值
}
Dijkstra(S);
DFS(D); // 打印路径
printf("%d %d\n", d[D], c[D]); // 输出最短距离和最小花费
return 0;
}
总结:
最短路题目的模板了,同时考虑最短路和最小花费,不管怎么样都先Dijkstra求最短路,然后求最短路的过程中保存最小花费的路径,最后递归打印出来。