1030 Travel Plan (30 point(s))
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
题目大意:
有 N 个城市,M 条路,S 是起点,D 是终点,根据输入的路径信息,求起点到终点的最短路径,若有多条最短路径,则选择花费最少(保证唯一)的路径
设计思路:
Dijksta 和 DFS
- Dijksta 求得 pre[] 数组
- DFS 遍历输出最短路径
编译器:C (gcc)
#include <stdio.h>
#include <limits.h>
int dfs(int d, int s, int pre[])
{
if (d == s) {
printf("%d", d);
return 0;
} else {
dfs(pre[d], s, pre);
printf(" %d", d);
}
return 0;
}
int main(void)
{
int n, m, s, d;
int gdis[505][505], gcost[505][505];
int dis[505], cost[505], pre[505] = {0}, visit[505] = {0};
int i, j, u, v, minn;
for (i = 0; i < 505; i++)
dis[i] = INT_MAX;
for (i = 0; i < 505; i++)
cost[i] = INT_MAX;
for (i = 0; i < 505; i++)
for (j = 0; j < 505; j++)
gdis[i][j] = INT_MAX;
scanf("%d %d %d %d", &n, &m, &s, &d);
for (i = 0; i < m; i++) {
int a, b, e, f;
scanf("%d %d %d %d", &a, &b, &e, &f);
gdis[a][b] = gdis[b][a] = e;
gcost[a][b] = gcost[b][a] = f;
}
dis[s] = 0;
cost[s] = 0;
for (i = 0; i < n; i++) {
u = -1, minn = INT_MAX;
for (j = 0; j < n; j++) {
if (visit[j] == 0 && dis[j] < minn) {
u = j;
minn = dis[j];
}
}
if (u == -1)
break;
visit[u] = 1;
for (v = 0; v < n; v++) {
if (visit[v] == 0 && gdis[u][v] != INT_MAX) {
if (dis[v] > dis[u] + gdis[u][v]) {
dis[v] = dis[u] + gdis[u][v];
cost[v] = cost[u] + gcost[u][v];
pre[v] = u;
} else if (dis[v] == dis[u] + gdis[u][v] && cost[v] > cost[u] + gcost[u][v]) {
cost[v] = cost[u] + gcost[u][v];
pre[v] = u;
}
}
}
}
dfs(d, s, pre);
printf(" %d %d", dis[d], cost[d]);
return 0;
}