7-9 旅游规划(25 分)
有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。
输入格式:
输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2≤N≤500)是城市的个数,顺便假设城市的编号为0~(N−1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。
输出格式:
在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。
输入样例:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
输出样例:
3 40
#include<iostream>
#include<stdio.h>
#include<vector>
#include<queue>
using namespace std;
int Nv,Ne,S,D;
vector<int>G[505];//邻接表
int DIST[505][505];//邻接矩阵
int COST[505][505];//路的花费
int dis[505];//起点到其他所有点的最短路径
int Scos[505];//起点到其他所有点的花费
int path[505];//存放上一个点
bool Visited[505];//标志是否访问过
void Read(){
for(int i=0;i<Nv;i++)
for(int j=0;j<Nv;j++){
DIST[i][j]=250005;
COST[i][j]=250005;
}
int a,b,c,d;
for(int i=0;i<Ne;i++){
cin>>a>>b>>c>>d;
DIST[a][b]=DIST[b][a]=c;
COST[a][b]=COST[b][a]=d;
G[a].push_back(b);
G[b].push_back(a);
}
}
struct HeapNode{
int n;//节点编号
int l;//里程长度
int c;//里程花费
bool operator <(const HeapNode &rhs) const{
if(l==rhs.l)
return c>rhs.c;
return l>rhs.l;
}
};
void Dijkstra(int s){
priority_queue<HeapNode>Q;
for(int i=0;i<Nv;i++){
dis[i]=250005;
path[i]=-1;
Scos[i]=250005;
}
HeapNode H1;
H1.n=s;
dis[s]=H1.c=H1.l=0;
Scos[s]=0;
Q.push(H1);
while(Q.size()>0){
HeapNode H2=Q.top();
Q.pop();
if(Visited[H2.n]==true) continue;
Visited[H2.n]=true;
int hn=H2.n;
for(int i=0;i<G[hn].size();i++){
int hni=G[hn][i];
if(Visited[hni]==false){
if(dis[hni]>dis[hn]+DIST[hn][hni]){
dis[hni]=dis[hn]+DIST[hn][hni];
Scos[hni]=Scos[hn]+COST[hn][hni];
path[hni]=hn;
HeapNode H3;
H3.n=hni;
H3.l=dis[hni];
H3.c=Scos[hni];
Q.push(H3);
}
else if(dis[hni]==dis[hn]+DIST[hn][hni]){
if(Scos[hni]>Scos[hn]+COST[hn][hni]){
Scos[hni]=Scos[hn]+COST[hn][hni];
path[hni]=hn;
HeapNode H3;
H3.n=hni;
H3.l=dis[hni];
H3.c=Scos[hni];
Q.push(H3);
}
}else
continue;
}
}
}
}
int main(){
freopen("in.txt","r",stdin);
cin>>Nv>>Ne>>S>>D;
Read();
Dijkstra(S);
cout<<dis[D]<<" "<<Scos[D]<<endl;
fclose(stdin);
return 0;
}