1030 Travel Plan (30)(30 分)
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
思路:
用dijkstra求S到D的最短路径,需要注意的是要同时维护两个量,一个是最短距离,一个是最小代价。
代码:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <climits>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define INF 0x3f3f3f3f
int d[500][500], c[500][500], dis[500], cost[500], vis[500], pre[500];
int n, m, a, b;
void dijkstra(int a, int b)
{
for (int i = 0; i < n; i++)
{
dis[i] = d[a][i];
cost[i] = c[a][i];
pre[i] = -1;
}
dis[a] = 0;
cost[a] = 0;
for (int i = 0; i < n; i++)
{
int min = INF, k = 0;
for (int j = 0; j < n; j++)
{
if (!vis[j] && dis[j] < min)
{
min = dis[j];
k = j;
}
}
vis[k] = 1;
for (int j = 0; j < n; j++)
{
if (!vis[j] && d[k][j] != INF)
{
if (dis[k] + d[k][j] < dis[j])
{
dis[j] = dis[k] + d[k][j];
cost[j] = cost[k] + c[k][j];
pre[j] = k;
}
else if (dis[k] + d[k][j] == dis[j] && cost[k] + c[k][j] < cost[j])
{
cost[j] = cost[k] + c[k][j];
pre[j] = k;
}
}
}
}
}
void print_path(int x)
{
if (x == -1)
return;
print_path(pre[x]);
cout << x << " ";
}
int main()
{
cin >> n >> m >> a >> b;
memset(vis, 0, sizeof(vis));
memset(d, INF, sizeof(d));
memset(c, INF, sizeof(c));
for (int i = 0; i < m; i++)
{
int city1, city2, distance, cost;
cin >> city1 >> city2 >> distance >> cost;
d[city1][city2] = d[city2][city1] = distance;
c[city1][city2] = c[city2][city1] = cost;
}
dijkstra(a, b);
cout << a << " ";
print_path(b);
cout << dis[b] << " " << cost[b] << endl;
return 0;
}