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
作者
CHEN, Yue
单位
浙江大学
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
代码:
#include <bits/stdc++.h>
using namespace std;
const int INF = (1)<<31-1;
const int maxn = 501;
int n, m, s, z;
int shortdis[maxn];
int edge[maxn][maxn];
int cost[maxn][maxn];
vector<int> pre[maxn];
bool visit[maxn] = {false};
void DIJ(int s){
fill(shortdis, shortdis+maxn, INF);
shortdis[s] = 0;
for(int i=0; i<n; i++){
int u = -1, minx = INF;
for(int j=0; j<n; j++){
if(visit[j]==false&&shortdis[j]<minx){
u = j;
minx = shortdis[j];
}
}
if(u==-1) return;
visit[u] = true;
for(int v=0; v<n; v++){
if(visit[v]==false&&edge[u][v]!=INF){
if(shortdis[u] + edge[u][v] < shortdis[v]){
shortdis[v] = shortdis[u] + edge[u][v];
pre[v].clear();
pre[v].push_back(u);
}
else if(shortdis[v] == shortdis[u] + edge[u][v]){
pre[v].push_back(u);
}
}
}
}
}
int optvalue = INF;
vector<int> path, tempPath;
void DFS(int v){
if(v==s){
tempPath.push_back(v);
int value = 0;
for(int i=tempPath.size()-1; i>0; i--){
int id = tempPath[i], idNext = tempPath[i-1];
value += cost[id][idNext];
}
if(value<optvalue){
optvalue = value;
path = tempPath;
}
tempPath.pop_back();
return;
}
tempPath.push_back(v);
for(int i=0; i<pre[v].size(); i++){
DFS(pre[v][i]);
}
tempPath.pop_back();
}
int main(){
scanf("%d%d%d%d", &n, &m, &s, &z);
fill(edge[0], edge[0]+maxn*maxn, INF);
fill(cost[0], cost[0]+maxn*maxn, INF);
for(int i=0; i<m; i++){
int c1, c2, dis, cos;
scanf("%d%d%d%d", &c1, &c2, &dis, &cos);
edge[c1][c2] = dis;
edge[c2][c1] = dis;
cost[c1][c2] = cos;
cost[c2][c1] = cos;
}
DIJ(s);
DFS(z);
for(int i=path.size()-1; i>=0; i--){
printf("%d ", path[i]);
}
printf("%d %d\n", shortdis[z], optvalue);
return 0;
}