PAT-A 1030 Travel Plan (30)

  使用 Dijkstra 算法解决最短路径问题;使用 DFS 逆推整条路线。

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.

Problem: PAT-A 1030 Travel Plan

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

1
2
3
4
5
6
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

1
0 2 3 3 40

Analysis

  给定起点 S 和终点 D,寻找 S 至 D 的最短路径。两座城市间的信息包括距离和耗费。最短路径不唯一,选择耗费最少的路径。输出路线上的城市序号、最短距离和最小耗费。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;
const int mxN = 505;

int N, M, S, D;
int G[mxN][mxN], d[mxN], cost[mxN][mxN], c[mxN], pas[mxN];
bool vis[mxN] = {false};

void dijkstra(int s) {
fill(d, d + N, INT_MAX);
d[s] = 0;
fill(c, c + N, INT_MAX);
c[s] = 0;
for (int i = 0; i < N; i++) {
int u = -1, MIN = INT_MAX;
for (int j = 0; j < N; j++) {
if (!vis[j] && d[j] < MIN) {
MIN = d[j];
u = j;
}
}
if (u == -1) return;
vis[u] = true;
for (int v = 0; v < N; v++) {
if (!vis[v] && G[u][v]) {
if (d[u] + G[u][v] < d[v]) {
d[v] = d[u] + G[u][v];
c[v] = c[u] + cost[u][v];
pas[v] = u; // 记录前驱结点,即从 u → v
} else if (d[u] + G[u][v] == d[v] && c[u] + cost[u][v] < c[v]) {
c[v] = c[u] + cost[u][v];
pas[v] = u; // 记录前驱结点
}
}
}
}
}

// 通过终点逆向推出路线,并正向输出
void print_path(int v) {
if (v == S) {
cout << v << " ";
return;
}
print_path(pas[v]);
cout << v << " ";
}

int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> N >> M >> S >> D;
for (int i = 0; i < M; i++) {
int c1, c2, dd, cc;
cin >> c1 >> c2 >> dd >> cc;
G[c1][c2] = G[c2][c1] = dd;
cost[c1][c2] = cost[c2][c1] = cc;
}
dijkstra(S);
print_path(D);
cout << d[D] << " " << c[D];
}

Tsukkomi

  回顾 Dijkstra 算法,依然是瞄着模板打的。下次一定自己码出来……


Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×