您的位置:首页 > 其它

1030. Travel Plan (30)

2015-12-06 10:35 316 查看
dfs使用vector保存最短路径

时间限制400 ms
内存限制65536 kB
代码长度限制16000 B
判题程序Standard作者CHEN, Yue
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
来源: <http://www.patest.cn/contests/pat-a-practise/1030>
#include <iostream>

#include <vector>


using namespace std;


int map[501][501] = { 0 };

int cost[501][501] = { 0 };

int mark[501] = { 0 };

int n, m, s, d;

int minDistance=999999;

int minCost = 999999;

vector<int> road, roadtemp;


void dfs(int i, int distNow, int costNow, vector<int> roadNow) {


roadNow.push_back(i);


if (i == d&&distNow < minDistance) {

minDistance = distNow;

minCost = costNow;

road.clear();

for (int j = 0; j < roadNow.size(); j++)

road.push_back(roadNow[j]);

}

else if (i == d&&distNow == minDistance&&costNow < minCost) {

minDistance = distNow;//same as before

minCost = costNow;

road.clear();

for (int j = 0; j < roadNow.size(); j++)

road.push_back(roadNow[j]);

}

else if (i == d||distNow>minDistance||costNow>minCost)

return;


for (int j = 0; j < n; j++) {

if (map[i][j] != 0 && mark[j] == 0) {

mark[j] = 1;

dfs(j, distNow + map[i][j], costNow + cost[i][j], roadNow);

mark[j] = 0;

}

}

}


int main(void) {


cin >> n >> m >> s >> d;

if (s == d) {

cout << s << " " << s << " 0 0";

return 0;

}

for (int i = 0; i < m; i++) {

int st, dt, dist, costt;

cin >> st >> dt >> dist >> costt;

map[st][dt] = map[dt][st] = dist;

cost[st][dt] = cost[dt][st] = costt;

}


mark[s] = 1;

dfs(s, 0, 0, roadtemp);


for (int i = 0; i < road.size(); i++) {

cout << road[i] << " ";

}

cout << minDistance << " " << minCost;


return 0;

}

[/code]

来自为知笔记(Wiz)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: