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算法求最短路径;
- 用DFS求路径,并计算代价;
- 按题目要求选取路径并输出,返回0值。
代码
#include<stdio.h>
#define maxn 510
#define INF 10000000
struct Node{
int v;
int dis;
int cost;
};
struct Node Adj[maxn][maxn];//距离
int num[maxn];//邻接表
int d[maxn];//距离
int vis[maxn];//遍历数组
int N,M,S,D;
int pre[maxn][maxn];//前置数组
int prenum[maxn];
int temp[maxn];
int shortest[maxn];
int mindepth,mincost=INF;
void Init(){
int i;
int a1,a2,a3,a4;
scanf("%d%d%d%d",&N,&M,&S,&D);
for(i=0;i<N;i++){
num[i]=0;
prenum[i]=0;
d[i]=INF;
vis[i]=0;
}
for(i=0;i<M;i++){
scanf("%d%d%d%d",&a1,&a2,&a3,&a4);
Adj[a1][num[a1]].v=a2;
Adj[a1][num[a1]].dis=a3;
Adj[a1][num[a1]++].cost=a4;
Adj[a2][num[a2]].v=a1;
Adj[a2][num[a2]].dis=a3;
Adj[a2][num[a2]++].cost=a4;
}
}
void Dijkstra(){
int i,j;
int u,v,min;
d[S]=0;
for(i=0;i<N;i++){
u=-1;min=INF;
for(j=0;j<N;j++){
if(vis[j]==0&&d[j]<min){
u=j;
min=d[u];
}
}
if(u==-1){
break;
}
vis[u]=1;
for(j=0;j<num[u];j++){
v=Adj[u][j].v;
if(vis[v]==0){
if(d[u]+Adj[u][j].dis<d[v]){
prenum[v]=0;
pre[v][prenum[v]++]=u;
d[v]=d[u]+Adj[u][j].dis;
}else if(d[v]==d[u]+Adj[u][j].dis){
pre[v][prenum[v]++]=u;
}
}
}
if(u==D){
break;
}
}
return;
}
void DFS(int u,int depth,int cost){
int i,j;
int v,c;
temp[depth]=u;
if(u==S){
if(cost<mincost){
mindepth=depth;
mincost=cost;
for(j=0;j<=mindepth;j++){
shortest[j]=temp[j];
}
}
return;
}else{
for(i=0;i<prenum[u];i++){
v=pre[u][i];
for(j=0;j<num[u];j++){
if(v==Adj[u][j].v){
break;
}
}
c=Adj[u][j].cost;
DFS(v,depth+1,cost+c);
}
}
return;
}
int main(){
int i;
Init();
Dijkstra();
DFS(D,0,0);
for(i=mindepth;i>=0;i--){
printf("%d ",shortest[i]);
}
printf("%d %d\n",d[D],mincost);
return 0;
}
运行结果