算法训练 旅行家的预算(贪心和双端队列)

9 篇文章 0 订阅
6 篇文章 0 订阅

题目链接:http://lx.lanqiao.cn/problem.page?gpid=T75

//本题的思路就是每次假装在加油点把油全部加上,到最后在把油还了

#include <bits/stdc++.h>

typedef long double ld;
typedef long long ll;

using namespace std;
const ld pi = acos(-1.0);
const ll maxn = 2e5;

ld a[maxn],b[maxn];
struct node
{
	ld cost;//花费
	ld oil;//油的数量
	node(ld c,ld o)
	{
		cost = c;
		oil = o;
	}
};

deque<node>q;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);

    ld d1,c,d2,p;
    ll n;
    cin >> d1 >> c >> d2 >> p >> n;

    //a[i]是距离,b[i]是油价
    for(int i = 1; i <= n; i ++)
    {
    	cin >> a[i] >> b[i];
	}

	a[0] = 0.0;
	a[n + 1] = d1;
	//先检查是否有解
	ll flag = 0;//标记是否有解。
	for(int i = 1; i <= n; i ++)
	{
		if(a[i - 1] + c * d2 < a[i])
		{
			flag = 1;
			break;
		}
	}
	if(a[n] + c * d2 < a[n + 1])
	{
		flag = 1;
	}
	if(flag == 1)cout << "No Solution" << endl;
	else
	{
		q.push_front(node(p,c));
		//在路上的油nc;
		ld nc = c;
		ld sum = c * p;
		for(int i = 1; i <= n + 1; i ++)
		{
			//行驶两地距离需要多少油
			ld xu = (a[i] - a[i - 1]) / d2;
			while(!q.empty() && xu > 0)
			{
				node po = q.front();
				q.pop_front();
				//车内剩余的油足够多
				if(po.oil > xu)
				{
				    nc -= xu;
					q.push_front(node(po.cost,po.oil - xu));
					break;
				}
				nc -= po.oil;
				xu -= po.oil;
			}
			//到达终点把所有的油全部退了
			if(i == n + 1)
			{
				while(!q.empty())
				{
					sum -= q.front().oil * q.front().cost;
					q.pop_front();
				}
				break;
			}
			//看此地的油价是否比车内的油价便宜;
			while(!q.empty() && q.back().cost > b[i])
			{
				sum -= q.back().oil * q.back().cost;
				nc -= q.back().oil;
				q.pop_back();
			}
			sum += (c - nc) * b[i];
			q.push_back(node(b[i],c - nc));
			nc = c;
		}
		cout << fixed << setprecision(2) << sum << endl;

	}


	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值