HDU 3790 最短路径最小花费

17 篇文章 0 订阅

迪杰斯特拉总结

相比于普通迪杰斯特拉,我们要做的变动是:

优先队列排序

	friend bool operator < (const node &f1, const node &f2) {
		if(f1.w!=f2.w)
			return f1.w > f2.w;
		else
			return f1.p>f2.p;
	}

迪杰斯特拉节点更新

if (dis[end] > dis[start] + edge[i].w) {
	dis[end] = dis[start] + edge[i].w;
	cost[end]=cost[start]+edge[i].p;
	Q.push(edge[i]);
} else if(dis[end]==dis[start]+edge[i].w && cost[end]>cost[start]+edge[i].p) {
	cost[end]=cost[start]+edge[i].p;
	Q.push(edge[i]);
}

距离更小就更新距离和花费,距离相等就比较花费

#include<cstdio>
#include<iostream>//数组从1开始而不是0 
#include<cstring>
#include<queue>
using namespace std;
const int INF=0x3f3f3f3f,N=1e5+10;
struct node {
	int  to,next,w,p;
	friend bool operator < (const node &f1, const node &f2) {
		if(f1.w!=f2.w)
			return f1.w > f2.w;
		else
			return f1.p>f2.p;
	}
} edge[N];
int n,m,cnt,s,t;
int head[N],dis[N],cost[N];
bool vis[N];
priority_queue<node> Q;
inline void addedge(int from, int to, int w,int p) {
	edge[cnt].to = to;
	edge[cnt].next = head[from];
	edge[cnt].w = w;
	edge[cnt].p=p;
	head[from] = cnt++;
}
inline void init() {
	cnt = 0;
	memset(head, -1, sizeof(head));
	memset(edge, 0, sizeof(edge));
	memset(dis, 0x3f, sizeof(dis));
	memset(cost,0x3f,sizeof(cost));
}
void dijkstra(int s,int t) { //s为源点
	node z;
	z.to=s,z.next=0,z.w=0,z.p=0;
	Q.push(z);
	dis[s] = 0;
	cost[s]=0;
	while (Q.size()) {
		z = Q.top();
		Q.pop();
		int start = z.to;
		for (int i = head[start]; ~i; i = edge[i].next) {
			int end = edge[i].to;
			if (dis[end] > dis[start] + edge[i].w) {
				dis[end] = dis[start] + edge[i].w;
				cost[end]=cost[start]+edge[i].p;
				Q.push(edge[i]);
			}
			else if(dis[end]==dis[start]+edge[i].w && cost[end]>cost[start]+edge[i].p){
				cost[end]=cost[start]+edge[i].p;
				Q.push(edge[i]);
			}
		}
	}
	printf("%d %d\n",dis[t],cost[t]);
}
int main() {
	while(~scanf("%d%d",&n,&m)) {
		if(n==0 && m==0) return 0;
		init();
		for (int i = 0; i < m; i++) {
			int from, to, w,p;
			scanf("%d%d%d%d", &from, &to, &w,&p);
			addedge(from, to, w,p);
			addedge(to, from, w,p);
		}
		scanf("%d%d",&s,&t);
		dijkstra(s,t);
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值