1030 Travel Plan (30 point(s))
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
思路和1087 All Roads Lead to Rome基本一致,属于PAT常见题型。考点:Dijkstra算法灵活应用。
注意点:
1. DFS回溯路径的方法,深刻理解递归。
2. 注意构造函数定义。
#include<iostream>
#include<vector>
#include<cstring>
#define MAX 0x3f3f3f3f
using namespace std;
int N,M,S,D;
const int LEN = 505;
struct Edge{
int next;int weight;int cost;//下一个结点、距离、花销
Edge(int n,int w,int c):next(n),weight(w),cost(c){ }
};
vector<Edge>graph [LEN];
int dis[LEN];//记录距离
int sumCost[LEN];//当前总花销
int last[LEN];//记录上一个城市
bool visit[LEN]={false};
void dfs(int x){
if(x==S){
cout<<x;return;
}
dfs(last[x]);
cout<<" "<<x;
}
int main(void){
cin>>N>>M>>S>>D;
int a,b,w,c;
for(int i=0;i<M;i++){
cin>>a>>b>>w>>c;
graph[a].push_back(Edge(b,w,c));
graph[b].push_back(Edge(a,w,c));
}
memset(dis,-1,sizeof(dis));
int newP = S;
visit[newP] = true;
dis[newP] = 0;
while(!visit[D]){
for(int i=0;i<graph[newP].size();i++){
int v = graph[newP][i].next;
int w = graph[newP][i].weight;
int c = graph[newP][i].cost;
if(visit[v]) continue;
if(dis[v]==-1||dis[newP]+w<dis[v]){//不可达或者有更近的路径
dis[v] = dis[newP]+w;//更新距离
sumCost[v] = sumCost[newP]+c;//更新消耗
last[v] = newP;//更新前驱城市
}
else if(dis[newP]+w==dis[v]&&sumCost[newP]+c<sumCost[v]){//距离相等但是有更小的消耗
sumCost[v] = sumCost[newP]+c;//更新消耗
last[v] = newP;//更新前驱城市
}
}
int min = MAX;
for(int i=0;i<N;i++){
if(dis[i]==-1) continue;
if(visit[i]) continue;
if(dis[i]<min){
min = dis[i];
newP = i;
}
}
visit[newP] = true;
}
dfs(D);
cout<<" "<<dis[D]<<" "<<sumCost[D]<<endl;
return 0;
}
本文介绍了一道PAT竞赛题目“旅行计划”的解决方案,该题要求找出从起点到终点的最短路径,并在路径不唯一时选择成本最低的路径。文章详细解析了Dijkstra算法在解决此类问题中的应用,包括如何回溯路径、定义构造函数以及实现关键步骤。
124

被折叠的 条评论
为什么被折叠?



