1030 Travel Plan (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算法就可以解决,输出路径的时候用一个递归函数即可。
参考代码:
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
int e[501][501], weight[501][501], w[501], dis[501], path[501];
bool vis[501];
const int inf = 0x7fffffff;
int st, ed, n, m;
void show(int v){
if(v == st){
printf("%d ", v);
return;
}
show(path[v]);
printf("%d ", v);
}
void dijkstra(int start){
fill(dis, dis + 501, inf);
fill(w, w + 501, inf);
dis[start] = 0, w[start] = 0;
for(int i = 0; i < n; ++i){
int u = -1, min = inf;
for(int j = 0; j < n; ++j)
if(!vis[j] && dis[j] < min) min = dis[j], u = j;
if(u == -1) break;
vis[u] = true;
for(int v = 0; v < n; ++v)
if(!vis[v] && e[u][v]){
if(dis[u] + e[u][v] < dis[v]){
dis[v] = dis[u] + e[u][v];
w[v] = weight[u][v] + w[u];
path[v] = u;
} else if(dis[u] + e[u][v] == dis[v] && w[u] + weight[u][v] < w[v]){
w[v] = w[u] + weight[u][v];
path[v] = u;
}
}
}
}
int main(){
scanf("%d%d%d%d", &n, &m, &st, &ed);
for(int i = 0 ; i < m; ++i){
int a, b;
scanf("%d%d", &a, &b);
scanf("%d%d", &e[a][b], &weight[a][b]);
weight[b][a] = weight[a][b];
e[b][a] = e[a][b];
}
dijkstra(st);
show(ed);
printf("%d %d", dis[ed], w[ed]);
return 0;
}