贪心 1033 To Fill or Not to Fill (25 分) (******)

想了很久都想不出来
借鉴算法笔记
还是按照距离排序
把终点看作一个价格为0,距离为终点距离的加油站
当下一个加油站价格比当前便宜
只需要购买刚好到下一个站点的油量,然后去下一个站加油
当下面几个可以到达的加油站但是价格更贵
找到最便宜那个站去加满油,再去下一个

如果第一个加油站距离不为0,则直接结束

#include <cstdio>
#include <algorithm>
using namespace std;


typedef struct node
{
	double price;
	double distance;
}stations;

bool cmp(stations a,stations b)
{
	if(a.distance != b.distance)
		return a.distance < b.distance;
}

int main()
{
	double c,d,dv;
	int n;
	double ans=0;
	scanf("%lf %lf %lf %d",&c,&d,&dv,&n);
	stations s[n+10];
	
		
	for(int i = 0;i<n;i++)
	{
		scanf("%lf %lf",&s[i].price,&s[i].distance);	
	}
	s[n].distance = d;
	s[n].price = 0;		
	sort(s,s+n,cmp);
	
	int now = 0,k=-1;
	double pmin=99999,nowt=0,max = dv*c;
	
	if(s[0].distance != 0)
		printf("The maximum travel distance = 0.00");
	else
	{
		while(now<n)
		{
			k = -1;
			pmin = 99999;
			for(int i = now + 1;i<=n && s[i].distance - s[now].distance <= max;i++)
			{
				if(s[i].price < pmin)
				{
					pmin = s[i].price;
					k=i;
					if(pmin < s[now].price)
					{
						break;
					}
				}
			}
			
			if(k==-1)
				break;
			else
			{
				double need = (s[k].distance - s[now].distance) / dv;
				if(s[k].price < s[now].price)
				{
					if(nowt < need)
					{
						ans += s[now].price * (need - nowt);
						nowt = 0; 
					}
					else
					{
						nowt -= need;
					}
						
				}
				else
				{
					ans += s[now].price * (c - nowt);
					nowt = c - need;
				}
			}
			now = k;
			
		}
		if(k == -1)
			printf("The maximum travel distance = %.2lf",s[now].distance + max);
		else
			printf("%.2lf",ans);
		
	}
		

	return 0;
} 
在这里插入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值