PAT甲级 1030. Travel Plan (30)

来源:互联网 发布:自己实现数据库 编辑:程序博客网 时间:2024/05/18 01:42

题目:

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 30 1 1 201 3 2 300 3 4 100 2 2 202 3 1 20
Sample 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 resultint 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;}elsereturn;}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(){//inputint 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);        //outputfor (i = 0; i < final_r.size(); ++i){cout << final_r[i] << " ";}cout << final_d << " " << final_c << endl;system("pause");return 0;}



原创粉丝点击