- 思路:关键在于贪心策略的选取
如果把终点也当做一个加油站处理,则代码可以简化很多 - 贪心策略详细描述,遍历在当前站点所能达到的所有站点,分两种情况讨论:
0.寻找比自己距离远的,到能够到达的最大距离之间的加油站,看他们的油价。如果找到了更低价格的油价,就加油到刚好能到达那个加油站的距离的油,然后去那个更低价格的加油站(有更低的我一分都不想多花在别的距离上,只加到刚好满足更低价格的加油站的距离就行,那样以后的路程我就可以以更低的价格行驶啦)
1.如果找不到更低的,就找尽可能低的油价的加油站,在当前加油站加满油之后过去。因为想要让路程上使用的尽可能是低价的油,既然没有比当前更低价格的了,就让油箱加到最大值,这样能保证利益最大化,保证最大的距离使用的是便宜的油。
from:柳婼
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct node{
double dist,price;
bool operator<(node& b){
return dist<b.dist;
}
};
int main(){
int N;
double Cmax,D,Davg;
scanf("%lf %lf %lf %d",&Cmax,&D,&Davg,&N);
vector<node> vec(N+1);
for(int i=0;i<N;i++)
scanf("%lf %lf",&vec[i].price,&vec[i].dist);
vec[N].price=-1;vec[N].dist=D;
sort(vec.begin(),vec.end());
int curG=0;
double curC=0;
if(vec[0].dist!=0){printf("The maximum travel distance = 0.00");return 0;}
double lowestP;
int lowestG;
double sumprice=0;
while(vec[curG].dist<D){
int hi=curG+1;
lowestP=100;
while(hi<=N&&vec[hi].dist<=vec[curG].dist+Davg*Cmax&&vec[hi].dist<=D){
if(vec[hi].dist==D){
if(lowestP>=vec[curG].price)
{lowestP=0;lowestG=hi;}
}else{
if(vec[hi].price<vec[curG].price){
lowestP=vec[hi].price;
lowestG=hi;
break;
}else if(vec[hi].price<lowestP){
lowestP=vec[hi].price;
lowestG=hi;
}
}
hi++;
}
if(lowestP==100){
printf("The maximum travel distance = %.2lf\n",vec[curG].dist+Davg*Cmax);
return 0;
}
if(lowestP>=vec[curG].price){
sumprice+=(Cmax-curC)*vec[curG].price;
curC=Cmax-(vec[lowestG].dist-vec[curG].dist)/Davg;
curG=lowestG;
}else{
sumprice+=((vec[lowestG].dist-vec[curG].dist)/Davg-curC)*vec[curG].price;
curC=0;
curG=lowestG;
}
}
printf("%.2lf\n",sumprice);
return 0;
}