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
题意分析:
题目要求是首先找到最短路径,如果最短路径的解不止一个,就再找到花费代价最小的。
采用了Dijkstra算法和深度优先遍历DFS,用root数组存放从设定的起始点到每个点i的最短路径。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int n, m, s, d;
const int maxn = 510;
int road[maxn][maxn]{ INT_MAX };//记录两个城市之间的通路距离
int cost[maxn][maxn];//记录每条路的花费
int minCost[maxn];//记录最小花费
int minDis[maxn];//记录最短距离
bool visit[maxn]{ false };
int root[maxn];//记录父节点
void dijkstra(int s)
{
fill(minCost, minCost + maxn, INT_MAX);
fill(minDis, minDis + maxn, INT_MAX);
for (int i = 0; i < n; i++)
root[i] = i;
minDis[s] = 0;
minCost[s] = 0;
for (int i = 0; i < n; i++)
{
int u = -1;
int min = INT_MAX;
for (int j = 0; j < n; j++)
{
if (!visit[j] && minDis[j] < min) {
min = minDis[j];
u = j;
}
}
if (u == -1)return;//没有找到更短的路
visit[u] = true;
for (int j = 0; j < n; j++)
{
if (!visit[j] && road[u][j] != INT_MAX) {
if (minDis[j] > road[u][j] + minDis[u]) {
minDis[j] = road[u][j] + minDis[u];
minCost[j] = cost[u][j] + minCost[u];
root[j] = u;
}
else if (minDis[j] == road[u][j] + minDis[u]) {
if (minCost[j] > cost[u][j] + minCost[u]) {
minCost[j] = cost[u][j] + minCost[u];
root[j] = u;
}
}
}
}
}
}
void dfs(int v)
{
if (v == s) {
cout << v << " ";
return;
}
dfs(root[v]);
cout << v << " ";
return;
}
int main()
{
cin >> n >> m >> s >> d;
fill(road[0], road[0] + maxn * maxn, INT_MAX);
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
cin >> road[u][v];
cin >> cost[u][v];
road[v][u] = road[u][v];
cost[v][u] = cost[u][v];
}
dijkstra(s);
dfs(d);
cout << minDis[d] << " " << minCost[d] << endl;
return 0;
}
运行结果如下: