旅游规划 (25分)

有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。

dijkstra算法:

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int INF = 1e9;
const int maxn = 510;

struct edge{
	int from,to,w,l;
	edge(int a,int b, int c,int d){
		from = a;
		to = b;
		w = c;
		l = d;
	}
};

vector<edge> e[maxn];

struct node{
	int id;
	int n_dis;
	int n_f;
	node(int a,int b,int c){
		id = a;
		n_dis = b;
		n_f = c;
	}
	bool operator < (const node & a) const {
		if(n_dis == a.n_dis) return n_f > a.n_f ;
		else return n_dis > a.n_dis ;
	}
}; 

int n,m,s,d;
int dis[maxn];
int f[maxn];

void dijkstra(){
	bool done[maxn];
	for(int i = 0;i<n;i++){
		dis[i] = INF;
		f[i] = INF;
		done[i] = false;
	}
	dis[s] = 0;
	f[s] = 0;
	priority_queue<node> q;
	q.push(node(s,dis[s],f[s]));
	while(!q.empty() ){
		node u = q.top() ;
		q.pop() ;
		if(done[u.id]) continue;
		done[u.id] = true;
		for(int i = 0;i<e[u.id].size() ;i++){
			edge y = e[u.id][i];
			if(done[y.to]) continue;
			if(dis[y.to] > y.w+u.n_dis){
				dis[y.to] = y.w+u.n_dis;
				f[y.to] = y.l+u.n_f;
				q.push(node(y.to,dis[y.to],f[y.to])) ;
			}
			else if(dis[y.to] == y.w+u.n_dis){  //核心代码 
				if(f[y.to] > y.l+u.n_f){
					dis[y.to] = y.w+u.n_dis;
					f[y.to] = y.l+u.n_f;
					q.push(node(y.to,dis[y.to],f[y.to])) ;
				}
			}
		}
	}
}

int main(){
	cin >> n >> m >> s >> d;
	int x,y,sv,len;
	for(int i = 0;i<m;i++){
		cin >> x >> y >> sv >> len;
		e[x].push_back(edge(x,y,sv,len)) ;
		e[y].push_back(edge(y,x,sv,len)) ;
	}
	dijkstra() ;
	cout << dis[d] << " " << f[d] << endl;
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值