题目描述
分析:
运用贪心策略,每一步尽可能用最便宜的油价。
- 先按距离进行排序,假如起始位置也就是距离最近的加油站的距离不是0,那么直接输出最远行驶距离为0;
- 从当前加油站出发,在满油状态下能到达的所有加油站中寻找距离当前加油站最近且油价低于当前油价的加油站(优先前往油价更低油价的加油站)
- 如果找不到油价低于当前油价的加油站,则寻找油价最低的加油站
- 满油下找不到能到达的加油站,则说明不能到达目的地
#include<iostream>
#include<algorithm>
using namespace std;
struct station{
double price,dis;
}st[505];
bool cmp(station a,station b){
return a.dis<b.dis;
}
int main(){
int n;
double Cmax,D,Davg;
cin>>Cmax>>D>>Davg>>n;
for(int i=0;i<n;i++){
cin>>st[i].price>>st[i].dis;
}
st[n].price=0;
st[n].dis=D;
sort(st,st+n,cmp);
if(st[0].dis!=0){
cout<<"The maximum travel distance = 0.00"<<endl;
}
else{
int now=0;
double ans=0;
double nowTank=0;
double maxdis=Cmax*Davg;
while(now<n){
int k=-1;
double priceMin=1e9;
for(int i=now+1;i<=n&&st[i].dis-st[now].dis<=maxdis;i++){
if(st[i].price<priceMin){
priceMin=st[i].price;
k=i;
if(priceMin<st[now].price){
break;
}
}
}
if(k==-1) break;
double need=(st[k].dis-st[now].dis)/Davg;
if(priceMin<st[now].price){
if(nowTank<need){
ans+=(need-nowTank)*st[now].price;
nowTank=0;
}
else{
nowTank-=need;
}
}
else{
ans+=(Cmax-nowTank)*st[now].price;
nowTank=Cmax-need;
}
now =k;
}
if(now==n){
printf("%.2f\n",ans);
}
else{
printf("The maximum travel distance = %.2f\n",st[now].dis+maxdis);
}
}
return 0;
}