PTA-1030 Travel Plan (30 分)
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
思路
这是一道最短路径+最小边权+打印路径的题,这道题和PTA-1003 Emergency都是最短路径+xxx的组合问题,各有千秋吧。
path数组存储该结点的前驱结点,path更新的是最短路径的同时满足最小边权的最优路径,我们应该从终点开始dfs往回找,直到找到起点,然后reverse翻转一下再输出的就是正序的路径了。
ps:一开始wa了最后一个测试点,以为是数组开小了,结果并不是。看了很多dalao的代码发现,因为习惯于用cost[e.to]=min(cost[e.to],cost[v]+e.cost);
来代替if判断了,然而只有cost[e.to]=cost[v]+e.cost;
这样更新后的情况才改变结点前驱,否则就不满足最小边权,不是最优解。容易大意,引以为戒…
解决代码
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int maxx=505;
struct edge
{
int to,dis,cost;
edge(int _to,int _dis,int _cost){to=_to,dis=_dis,cost=_cost;}
};
vector<edge> a[maxx];
typedef pair<int,int> P;
int d[maxx];
int cost[maxx];
int path[maxx];
void dijkstra(int s)
{
memset(d,INF,sizeof(d));
d[s]=0;
priority_queue<P,vector<P>,greater<P> > que;
que.push(P(0,s));
while(!que.empty())
{
P p=que.top();
que.pop();
int v=p.second;
if(d[v]<p.first) continue;
for(int i=0;i<a[v].size();i++)
{
edge e=a[v][i];
if(d[e.to]>=d[v]+e.dis)
{
if(d[e.to]==d[v]+e.dis)
{
if(cost[e.to]>cost[v]+e.cost)
{
cost[e.to]=cost[v]+e.cost;
path[e.to]=v;
}//!!!!别忘了只有更新了最小花费才能更新路径
//cout<<v<<"的后继为"<<e.to<<endl;
}
else
{
path[e.to]=v;
//cout<<v<<"的后继为"<<e.to<<endl;
cost[e.to]=cost[v]+e.cost;
d[e.to]=d[v]+e.dis;
que.push(P(d[e.to],e.to));
}
}
}
}
}
int main()
{
int n,m,s,e;
cin>>n>>m>>s>>e;
while(m--)
{
int x,y,dis,cost;
cin>>x>>y>>dis>>cost;
a[x].push_back(edge(y,dis,cost));
a[y].push_back(edge(x,dis,cost));
path[x]=y;
path[y]=x;
}
dijkstra(s);
vector<int> way;
way.push_back(e);
int x=path[e];//x为前驱
way.push_back(x);
while(x!=s)
{
x=path[x];
way.push_back(x);
}
reverse(way.begin(),way.end());
for(int i=0;i<way.size();i++)
{
cout<<way[i]<<' ';
}
cout<<d[e]<<' '<<cost[e];
return 0;
}