最短路径问题(Dijkstra板子,多加了一个成本的属性)_07

题目描述
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。

输入描述:
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点t。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
输出描述:
输出 一行有两个数, 最短距离及其花费。
输入样例
3 2
1 2 5 6
2 3 4 5
1 3
0 0
输出样例
9 11

#include<bits/stdc++.h>
using namespace std;
const int MAXN=1001;
const int INF=INT_MAX;
struct Edge{
	int to;
	int length;
	int price;
	Edge(int t,int d,int p):to(t),length(d),price(p){}
};
struct Point{
	int num;
	int dis;
	Point(int n,int d):num(n),dis(d){}
	bool operator< (const Point& p) const{
		return dis>p.dis;
	}
};
//在找最短路径的基础上加了花费 
vector<Edge> graph[MAXN];
int dis[MAXN];
int cost[MAXN];
//迪杰斯特拉 
void Dijkstra(int s){
	dis[s]=0;
	cost[s]=0;
	priority_queue<Point> pq;
	pq.push(Point(s,dis[s]));
	while(!pq.empty()){
		int u = pq.top().num;
		pq.pop();//差点忘了
		for(int j=0;j<graph[u].size();j++){
			int v = graph[u][j].to;
			int d = graph[u][j].length;
			int p = graph[u][j].price;
			if(dis[v]>dis[u]+d || (dis[v]==dis[u]+d && cost[v]>cost[u]+p)){
				cost[v]=cost[u]+p;
				dis[v]=dis[u]+d;
				pq.push(Point(v,dis[v]));
			}
		}
	}
}
int main(){
	int n,m,s,t;
	while(cin>>n>>m){
		if(n==0 && m==0){
			break;
		}
		memset(graph,0,sizeof(graph));
		fill(dis,dis+n+1,INF);
		fill(cost,cost+n+1,INF);
		int from,to,d,p;
		for(int i=0;i<m;i++){
			cin>>from>>to>>d>>p;
			graph[from].push_back(Edge(to,d,p));
			graph[to].push_back(Edge(from,d,p));
		}
		cin>>s>>t;
		Dijkstra(s);
		cout<<dis[t]<<" "<<cost[t]<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天都要学算法(努力版)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值