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
代码
//DFS回溯+路径查找
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
const int MAX=505;
const int INF=0x7fffff;
int dis[MAX][MAX],mark[MAX],w[MAX][MAX];
int N,M,S,D,minl_way,take;
vector<int> c[MAX];
vector<int> path;
vector<int> shortpath;
void init()
{
for(int i=0;i<N;i++)
{
for(int k=0;k<N;k++)
{
dis[i][k]=INF;
w[i][k]=0;
}
}
}
void DFS(int cur,int l,int pay)
{
if(l>minl_way)
return ;
if(cur==D)
{
if(l<minl_way)
{
minl_way=l;
take=pay;
shortpath=path;
}
else if(l==minl_way&&(pay<take))
{
take=pay;
shortpath=path;
}
}
int len=c[cur].size();
for(int i=0;i<len;i++)
{
int x=c[cur][i];
if(!mark[x]&&dis[cur][x]!=INF)
{
mark[x]=1;
path.push_back(x);
DFS(x,l+dis[cur][x],pay+w[cur][x]);
path.pop_back();
mark[x]=0;
}
}
}
int main()
{
int u,v,distance,cost;
scanf("%d %d %d %d",&N,&M,&S,&D);
init();
while(M--)
{
scanf("%d %d %d %d",&u,&v,&distance,&cost);
dis[u][v]=dis[v][u]=distance;
w[u][v]=w[v][u]=cost;
c[u].push_back(v);
c[v].push_back(u);
}
mark[S]=1;
minl_way=INF;
path.push_back(S);
DFS(S,0,0);
for(int i=0;i<shortpath.size();i++)
printf("%d ",shortpath[i]);
printf("%d %d",minl_way,take);
return 0;
}
本文介绍了一种解决旅行者地图中从起点到目的地最短路径问题的算法,通过深度优先搜索(DFS)结合回溯法,找到总距离最短且成本最低的路径。输入包括城市数量、高速公路数量、起点和终点,以及各高速公路的距离和成本。
960

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



