PAT (Advanced Level) Practise 1030 Travel Plan (30)

来源:互联网 发布:linux部署环境 编辑:程序博客网 时间:2024/06/02 00:12

1030. Travel Plan (30)

时间限制
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 30 1 1 201 3 2 300 3 4 100 2 2 202 3 1 20
Sample Output
0 2 3 3 40
找最短路,如果有多条找最小消耗的,相当于找两次最短路,可以直接dfs,数据小不会超时。
#include<cstdio>#include<string>#include<cstring>#include<vector>#include<iostream>#include<queue>#include<bitset>#include<algorithm>using namespace std;typedef long long LL;const int INF = 0x7FFFFFFF;const int mod = 1e9 + 7;const int maxn = 5e2 + 10;int n, m, s, t, map[maxn][maxn], cost[maxn][maxn], x, y, z, c;int dis[maxn], v[maxn];void dfs(int x){if (x == t) return;for (int i = 0; i < n; i++){if (map[x][i]){if (dis[i]>dis[x] + map[x][i]){dis[i] = dis[x] + map[x][i];v[i] = v[x] + cost[x][i];dfs(i);}else if (dis[i] == dis[x] + map[x][i] && v[i] > v[x] + cost[x][i]){v[i] = v[x] + cost[x][i];dfs(i);}}}}bool Dfs(int x){if (x == s) { printf("%d ", s); return true; }for (int i = 0; i < n; i++){if (map[x][i] && dis[x] == dis[i] + map[x][i] && v[x] == v[i] + cost[x][i]){if (Dfs(i)) { printf("%d ", x); return true; }}}return false;}int main(){scanf("%d%d%d%d", &n, &m, &s, &t);while (m--){scanf("%d%d%d%d", &x, &y, &z, &c);if (!map[x][y] || map[x][y] > z){map[x][y] = map[y][x] = z;cost[x][y] = cost[y][x] = c;}else if (map[x][y] == z) cost[x][y] = cost[y][x] = min(z, cost[x][y]); }for (int i = 0; i < n; i++) dis[i] = v[i] = INF;dis[s] = v[s] = 0;dfs(s);Dfs(t);printf("%d %d\n", dis[t], v[t]);return 0;}


0 0
原创粉丝点击