想了很久都想不出来
借鉴算法笔记
还是按照距离排序
把终点看作一个价格为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;
}
在这里插入代码片