题目
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算法即可,与1003题基本一样:
PAT甲级真题 1003 Emergency (25分) C++实现(基于Dijkstra算法)
注意对比不满足最优子结构的1018题:
PAT甲级真题 1018 Public Bike Management (30分) C++实现(基于Dijkstra算法暴力存储所有最短路径;测试点5、7大坑)
需要记录所有路径(也可以只记录前导节点,再从t执行dfs)。
用了邻接表存储图(节约空间),应用Dijkstra算法。额外用vector<int> weight(n)
记录沿最短路径到某节点的最小费用;若新的最短路径与原最短路径相等,则取费用较小的路径。
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
struct Node{
int v; //index
int d; //dist
int w; //weight
};
int main(){
int n, m, s, t;
cin >> n >> m >> s >> t;
vector<vector<Node> > E(n); //邻接表
for (int i=0; i<m; i++){
int u, v, d, w;
cin >> u >> v >> d >> w;
E[u].push_back({v, d, w});
E[v].push_back({u, d, w});
}
vector<int> dist(n, INT_MAX);
vector<bool> visited(n);
vector<int> pre(n, -1);
vector<int> weight(n);
dist[s] = 0;
for (int i=0; i<n; i++){
int minDist = INT_MAX;
int k = -1;
for (int j=0; j<n; j++){
if (!visited[j] && dist[j]<minDist){
minDist = dist[j];
k = j;
}
}
visited[k] = true;
for (int j=0; j<E[k].size(); j++){
Node cur = E[k][j];
if (!visited[cur.v]){
if (minDist + cur.d < dist[cur.v]){
dist[cur.v] = minDist + cur.d;
weight[cur.v] = weight[k] + cur.w;
pre[cur.v] = k;
}
else if(minDist + cur.d == dist[cur.v]){
if (weight[k]+cur.w < weight[cur.v]){
weight[cur.v] = weight[k] + cur.w;
pre[cur.v] = k;
}
}
}
}
}
vector<int> path;
for (int i=t; i!=-1; i=pre[i]){
path.push_back(i);
}
for (int i=path.size()-1; i>=0; i--){
cout << path[i] << " ";
}
cout << dist[t] << " " << weight[t] << endl;
}