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
题目大意
某游客手中有一张旅游地图,想从起点城市S到达目标城市D,题目给出图中任意两个连通城市的路程及花费,求出该旅客从S到D的最短路径及花费,如果最短路径不止一条,则选择花费最小的路径
解题思路
废话不多说,直接使用Dijkstra算法求最短路径及最小花费即可,代码如下
代码
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <utility>
using namespace std;
const int maxn = 510, INF = 0x3fffffff;//最大结点数,无穷大
int G[maxn][maxn], cost[maxn][maxn];//分别代表路程和花费
int visit[maxn] = { 0 };
int dis[maxn] = { 0 };
int Pre[maxn], c[maxn];//分别代表前驱结点,最小花费
int n;//代表总结点数
void Dijkstra(int s) {
fill(dis, dis + maxn, INF);//距离初始化为无穷大
dis[s] = 0;
for (int i = 0; i < n; ++i) Pre[i] = i;
for (int i = 0; i < n; ++i) {
int u = -1, MIN = INF;
for (int v = 0; v < n; ++v) {
if (visit[v] == 0 && dis[v] < MIN) {//找到最小距离对应的结点
u = v;
MIN = dis[v];
}
}
if (u == -1) return;
visit[u] = 1;
for (int v = 0; v < n; ++v) {
if (visit[v] == 0 && G[u][v] != INF) {
if (dis[v] > dis[u] + G[u][v]) {
Pre[v] = u;//前一结点
dis[v] = dis[u] + G[u][v];
c[v] = c[u] + cost[u][v];
}
else if (dis[v] == dis[u] + G[u][v] && c[u] + cost[u][v] < c[v]) {
Pre[v] = u;
c[v] = c[u] + cost[u][v];
}
}
}
}
}
void DFS(int s, int v) {//打印最短路径
if (s == v) {
printf("%d ", s);
return;
}
DFS(s, Pre[v]);
printf("%d ", v);
}
int main()
{
int m, s, d, c1, c2, distance, spends;
int ret = scanf("%d %d %d %d", &n, &m, &s, &d);
fill(G[0], G[0] + maxn * maxn, INF);
for (int i = 0; i < m; ++i) {
ret = scanf("%d %d %d %d", &c1, &c2, &distance, &spends);
G[c1][c2] = G[c2][c1] = distance;
cost[c1][c2] = cost[c2][c1] = spends;
}
Dijkstra(s);
DFS(s, d);
printf("%d %d", dis[d], c[d]);
return 0;
}