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
解题思路:
dijkstra+dfs的套路,设计最短路径以及最小边权,注意打印最短路径时,从后往前。
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=510;
const int inf=1e8;
int G[maxn][maxn],d[maxn];
bool vis[maxn]={false};
int cost[maxn][maxn];
int n,m,st,ed,optvalue=inf;
vector<int>path,temppath;
vector<int>pre[maxn];
void dijkstra(int s){
fill(d,d+maxn,inf);
d[s]=0;
for(int i=0;i<n;i++){
int u=-1,minn=inf;
for(int j=0;j<n;j++){
if(vis[j]==false&&d[j]<minn){
u=j;
minn=d[j];
}
}
if(u==-1) return ;
vis[u]=true;
for(int v=0;v<n;v++){
if(vis[v]==false&&G[u][v]!=inf){
if(d[v]>d[u]+G[u][v]){
d[v]=d[u]+G[u][v];
pre[v].clear() ;
pre[v].push_back(u) ;
}else if(d[v]==d[u]+G[u][v]){
pre[v].push_back(u) ;
}
}
}
}
}
void dfs(int v){
if(v==st){
temppath.push_back(v) ;
int tempvalue=0;
for(int i=temppath.size() -1;i>0;i--){
int id=temppath[i],nextid=temppath[i-1];
tempvalue+=cost[id][nextid];
}
if(tempvalue<optvalue){
path=temppath;
optvalue=tempvalue;
}
temppath.pop_back() ;
return ;
}
temppath.push_back(v) ;
for(int i=0;i<pre[v].size() ;i++){
dfs(pre[v][i]);
}
temppath.pop_back() ;
}
int main(){
int c1,c2;
scanf("%d%d%d%d",&n,&m,&st,&ed);
fill(G[0],G[0]+maxn*maxn,inf);
fill(cost[0],cost[0]+maxn*maxn,inf);
for(int i=0;i<m;i++){
scanf("%d%d",&c1,&c2);
scanf("%d%d",&G[c1][c2],&cost[c1][c2]);
G[c2][c1]=G[c1][c2];
cost[c2][c1]=cost[c1][c2];
}
dijkstra(st);
dfs(ed);
for(int i=path.size() -1;i>=0;i--)
printf("%d ",path[i]);
printf("%d %d\n",d[ed],optvalue);
return 0;
}
本文介绍了一种结合Dijkstra算法和DFS的策略,用于解决旅行者寻找从起点到终点最短且成本最低的路径问题。输入包括城市数量、高速公路数量及各路段的距离和成本等信息,输出则是最短路径及其总距离和成本。
1002

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



