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
题目要求:
N个城市,M条路,每条路有距离和花费,求城市S到城市D的最短路径,对于相同的路径,找出花费最小的一条,该路径唯一,输出这条路径以及最短距离和最小花费。
解题思路:
同1018,只是dfs的条件变成了最小花费
完整代码:
#include<bits/stdc++.h>
using namespace std;
const int inf = 9999999;
int N,M,S,D;
int edge[510][510];
int cost[510][510];
int dst[510];
bool used[510];
vector<int> pre[510];
vector<int> path,temppath;
int minc = inf;
void dfs(int x){
int i,j,u,v,tempc;
temppath.push_back(x);
if(x == S){
tempc = 0;
for(i = temppath.size() - 1; i > 0; i--){
u = temppath[i];
v = temppath[i-1];
tempc += cost[u][v];
}
if(tempc < minc){
path = temppath;
minc = tempc;
}
temppath.pop_back();
return;
}
for(i = 0; i < pre[x].size(); i++){
dfs(pre[x][i]);
}
temppath.pop_back();
}
int main(){
int i,u,v,j,k,d,c,min;
fill(dst, dst + 510, inf);
fill(edge[0], edge[0] + 510 * 510, inf);
memset(used, 0, sizeof(used));
cin >> N >> M >> S >> D;
for(i = 1; i <= M; i++){
scanf("%d %d %d %d", &u, &v, &d, &c);
edge[u][v] = edge[v][u] = d;
cost[u][v] = cost[v][u] = c;
}
for(i = 0; i < N; i++){
dst[i] = edge[S][i];
if(edge[S][i] != inf){
pre[i].push_back(S);
}
}
used[S] = true;
for(i = 0; i < N; i++){
min = inf;
u = -1;
for(j = 0; j < N; j++){
if(used[j] == false && dst[j] < min){
min = dst[j];
u = j;
}
}
if(u == -1) break;
used[u] = true;
for(k = 0; k < N; k++){
if(used[k] == false && edge[u][k] < inf){
if(dst[k] > dst[u] + edge[u][k]){
dst[k] = dst[u] + edge[u][k];
pre[k].clear();
pre[k].push_back(u);
}else if(dst[k] == dst[u] + edge[u][k]){
pre[k].push_back(u);
}
}
}
}
dfs(D);
for(i = path.size() - 1; i >= 0; i--){
cout << path[i] << " ";
}
cout<<dst[D]<<" "<<minc;
return 0;
}