【BZOJ】1975 [Sdoi2010]魔法猪学院 k短路(最短路径+A*)

80 篇文章 1 订阅
4 篇文章 0 订阅

题目传送门

这题的正解——k短路还是挺好想到的,只不过题目告诉你的是路径长度总和,叫你求k的值。其他的和k短路的思想一模一样。

不过据说这题卡stl中的priority_queue,那么把priority_queue换成push_heap和pop_heap函数就好了。

关于push_heap等函数的介绍,看这里就行了,该博主讲的已经很详细了。

附上AC代码:

#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;

struct note{
	int d;
	double w;
};
vector <note> z[5010],f[5010];
struct node{
	int d;
	double g,f;
	bool operator < (const node lyf) const {
		return f==lyf.f?g>lyf.g:f>lyf.f;
	}
}h[2000010];
queue <int> que;
double sum,w,dis[5010];
int n,m,x,y,len;
bool b[5010];

void spfa(){
	for (int i=1; i<=n; ++i) dis[i]=2e9;
	que.push(n),dis[n]=0,b[n]=1;
	while (!que.empty()){
		int p=que.front();que.pop(),b[p]=0;
		for (int i=0; i<f[p].size(); ++i){
			note q=f[p][i];
			if (dis[q.d]>dis[p]+q.w){
				dis[q.d]=dis[p]+q.w;
				if (!b[q.d]){
					b[q.d]=1;
					que.push(q.d);
				}
			}
		}
	}
	return;
}

int astar(){
	if (dis[1]==2e9) return -1;
	int c=0;
	h[len=1]=(node){1,0,dis[1]};
	while (len){
		pop_heap(h+1,h+1+len);
		node p=h[len--];
		if (p.d==n) {
			sum-=p.g,++c;
			if (sum<=0) return c-1;
		}
		for (int i=0; i<z[p.d].size(); ++i){
			note q=z[p.d][i];
			h[++len]=(node){q.d,p.g+q.w,p.g+q.w+dis[q.d]};
			push_heap(h+1,h+1+len);
		}
	}
	return -1;
}

int main(void){
	scanf("%d%d%lf",&n,&m,&sum);
	for (int i=1; i<=m; ++i){
		scanf("%d%d%lf",&x,&y,&w);
		z[x].push_back((note){y,w});
		f[y].push_back((note){x,w});
	}
	spfa();
	printf("%d",astar());
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值