题目:
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 Input4 5 0 3 0 1 1 20 1 3 2 30 0 3 4 10 0 2 2 20 2 3 1 20Sample Output
0 2 3 3 40
这道题思路挺简单的,就是一个深度优先遍历,查找从起始点到目的地的最短路径,长度相同时比较其花费。
代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int Max = 500;
int map[Max][Max] = { 0 };
int cost[Max][Max] = { 0 };
bool visit[Max] = { 0 };
//final result
int final_c = Max;
int final_d = Max;
vector<int> final_r;
vector<int> r;
void findpath(int s, int d, int N, int C, int D)
{
int i = 0;
visit[s] = 1;
r.push_back(s);
if (s == d) //到达终点
{
if ((D < final_d) || ((D == final_d) && (C < final_c)))
{
final_c = C;
final_d = D;
final_r.clear();
final_r = r;
}
else
return;
}
else //未到达终点
{
for (i = 0; i < N; ++i)
{
if (map[s][i] && (!visit[i])) //有路,且未被访问
{
findpath(i, d, N, C + cost[s][i], D + map[s][i]);
visit[i] = 0;
r.pop_back();
}
}
}
}
int main()
{
//input
int N, M, S, D;
cin >> N >> M >> S >> D;
int i,c1,c2;
for (i = 0; i < M; ++i)
{
cin >> c1 >> c2;
cin >> map[c1][c2] >> cost[c1][c2];
map[c2][c1] = map[c1][c2];
cost[c2][c1] = cost[c1][c2];
}
//find the shortest path;
findpath(S, D,N,0,0);
//output
for (i = 0; i < final_r.size(); ++i)
{
cout << final_r[i] << " ";
}
cout << final_d << " " << final_c << endl;
system("pause");
return 0;
}
本文介绍了一种通过深度优先搜索算法来寻找两个城市间最短路径的方法,并在路径长度相同的情况下选择成本最低的路径。该算法能够确保找到的路径不仅距离最短,而且花费最小。
371

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



