dijkstra+二分答案【洛谷P1462】

传送门:https://www.luogu.org/problemnew/show/P1462

第一次做了这种求最短路而且要二分答案的。

比较困难吧,但是做了以后也基本领会了其中的道理。

首先二分答案开始写炸了,

这里放上一个模板吧!:

int ans = 0;
	while(l<=r)
	{
		int mid = (l+r)/2;
		if(dijkstra(mid))
		{
			ans = mid;
			r = mid-1;
		}
		else
		{
			l = mid+1;
		}
	}
	cout<<ans<<endl;

这样子的二分答案应该是可以的吧!

然后这个题目直接二分金钱就可以了。

每一次判断加边的时候判断一下该边的金额,小于等于mid就可以。

挺简单的啊!

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5+7;
const int INF = 1e9+7;
int d[maxn];
int f[maxn];
int n,m,b;
struct node
{
	int now;
	ll cost;
	bool operator<(const node &a)const
	{
		return cost>a.cost;
	}
};
struct edge
{
	int to;
	ll cost;
};
vector<edge> G[maxn];
bool dijkstra(int x)
{
	fill(d,d+maxn,INF);
	priority_queue<node> q;
	d[1] = 0;
	q.push((node){1,d[1]});
	while(!q.empty())
	{
		node tmp = q.top();
		q.pop();
		if(d[tmp.now]<tmp.cost) continue;
		for(int i=0;i<G[tmp.now].size();i++)
		{
			int v = G[tmp.now][i].to;
			if(d[v]>d[tmp.now]+G[tmp.now][i].cost && f[v]<=x)
			{
				d[v] = d[tmp.now]+G[tmp.now][i].cost;
				q.push((node){v,d[v]});
			}
		}
	}
	return d[n]<=b;
}
void init()
{
	fill(d,d+maxn,INF);
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin>>n>>m>>b;
	init();
	int l = INF;
	int r = -INF;
	for(int i=1;i<=n;i++)
	{
		cin>>f[i];
		l = min(l,f[i]);
		r = max(r,f[i]);
	}
	for(int i=0;i<m;i++)
	{
		int x,y,z;
		cin>>x>>y>>z;
		if(x==y) continue;
		G[x].push_back((edge){y,z});
		G[y].push_back((edge){x,z});
	}
	if(!dijkstra(INF+1))
	{
		cout<<"AFK"<<endl;
		return 0;
	}
	int ans = 0;
	while(l<=r)
	{
		int mid = (l+r)/2;
		if(dijkstra(mid))
		{
			ans = mid;
			r = mid-1;
		}
		else
		{
			l = mid+1;
		}
	}
	cout<<ans<<endl;
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值