A 1030 Travel Plan(模板题)
Problem Description
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
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
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
AC代码
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int maxn = 505;
int G[maxn][maxn],B[maxn][maxn],dij[maxn],vis[maxn],cost[maxn],path[maxn],n,m,s,d,City1,City2,Dist,Cos;
vector<int>graph[maxn];
void Dijsktra(int x){
dij[x]=0;
while(1){
int minl=INF,minn=-1;
for(int j=0;j<n;j++){
if(!vis[j] && dij[j]<minl){
minl=dij[j];
minn=j;
}
}
if(minn==-1){
break;
}
vis[minn]=1;
for(int j=0,limit=graph[minn].size();j<limit;j++){
int now=graph[minn][j];
if(dij[minn]+G[minn][now]<dij[now]){
dij[now]=dij[minn]+G[minn][now];
cost[now]=cost[minn]+B[minn][now];
path[now]=minn;
}else if(dij[minn]+G[minn][now]==dij[now]){
if(cost[now]>cost[minn]+B[minn][now]){
cost[now]=cost[minn]+B[minn][now];
path[now]=minn;
}
}
}
}
return ;
}
int main(){
scanf("%d%d%d%d",&n,&m,&s,&d);
fill(dij,dij+n,INF);
fill(vis,vis+n,0);
fill(cost,cost+n,0);
fill(path,path+n,0);
while(m--){
scanf("%d%d%d%d",&City1,&City2,&Dist,&Cos);
G[City1][City2]=G[City2][City1]=Dist;
B[City1][City2]=B[City2][City1]=Cos;
graph[City1].emplace_back(City2);
graph[City2].emplace_back(City1);
}
Dijsktra(s);
vector<int>ans;
ans.emplace_back(d);
int k=d;
while(k!=s){
ans.emplace_back(path[k]);
k=path[k];
}
for(auto it=ans.rbegin();it!=ans.rend();it++){
printf("%d ",*it);
}
printf("%d %d",dij[d],cost[d]);
return 0;
}