Djstra:
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
思路:题目大意:求起点到终点的最短路径最短距离和花费,要求首先路径最短,其次花费最少,要输出完整路径
分析:Dijksta + DFS。 Dijkstra记录路径pre数组,然后用dfs求最短的
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN= 1000;
const int INF =100000000;
int map[MAXN][MAXN];//存入地图
int cost[MAXN][MAXN],d[MAXN],c[MAXN];//最少花费与最短距离
int pre[MAXN];//路径
bool vis[MAXN];//标记数组
int n,m,st,ed; //n个顶点,m条边,起点,终点
void Djstra(int s)//输入起点
{
fill(d,d+MAXN,INF);
fill(c,c+MAXN,INF);
for(int i=0;i<n;i++) pre[i]=i;//初始化
d[s]=0;
c[s]=0;
for(int i=0;i<n;i++){
int u=-1,MIN=INF;
for(int j=0;j<n;j++){
if(!vis[j]&&d[j]<MIN){
u=j;
MIN=d[j];
}
}
if(u==-1) return ;
vis[u]=true;
for(int v=0;v<n;v++){
if(!vis[v]&&map[u][v]!=INF){
if(d[u]+map[u][v]<d[v]){
d[v]=d[u]+map[u][v];//优化最短路径
c[v]=c[u]+cost[u][v];//优化花费
pre[v]=u; //记录
}else if(d[u]+map[u][v]==d[v]){//若找到相同路径长的就比较花费
if(c[u]+cost[u][v]<c[v]){//小于更新
c[v]=c[u]+cost[u][v];
pre[v]=u;//记录
}
}
}
}
}
}
void dfs(int v)//打印路径
{
if(v==st){
cout<<v<<" ";
return ;
}
dfs(pre[v]);
cout<<v<<" ";
}
int main()
{
cin>>n>>m>>st>>ed;
int id1,id2,weight,cs;
fill(map[0],map[0]+MAXN*MAXN,INF);
for(int i=0;i<m;i++){
cin>>id1>>id2>>weight>>cs;
map[id1][id2]=map[id2][id1]=weight;
cost[id1][id2]=cost[id2][id1]=cs;
}
Djstra(st);
dfs(ed);
cout<<d[ed]<<" "<<c[ed];
return 0;
}