取消注释, 看跑路过程!
贪心思路:
1. 优先前往油价比当前油价更低的油站,为了前往这个油站,油箱里的油要加最少(即跑到下一站油量恰好为0),为了能去那里加更便宜的油
2. 没有比当前油价低的油站时,则在能跑到的油站里寻找价格最低的油站,但是这个最低的油站也比当前油站的价格高,所以要在当前油站把油加满。
3. 如果满油都到不了任意一个油站,那就说明到不了目的地,最远到达当前油站坐标+满油箱能跑的距离
#include <iostream>
#include <algorithm>
using namespace std;
struct Station{
double price;
double dis;
};
bool cmp(Station a, Station b){
return a.dis < b.dis;
}
int main(){
double cap;
double dis;
double per;
int n;
scanf("%lf %lf %lf %d", &cap, &dis, &per, &n);
struct Station sta[n+1];
for(int i=0; i<n; ++i){
scanf("%lf %lf", &sta[i].price, &sta[i].dis);
}
sta[n].price = 0;
sta[n].dis = dis;
n++;
sort(sta, sta+n, cmp);
//printf("\n");for(int i=0; i<n; ++i){printf("%d %.2f %.2f\n",i,sta[i].dis, sta[i].price);}printf("\n");
if(sta[0].dis!=0){
printf("The maximum travel distance = 0.00\n");
return 0;
}
int now_sta = 0;
int next_sta = 0;
double V=0;
double money=0;
while(now_sta<n-1){
for(int i=now_sta; i!=n; ++i){
if(sta[i].dis-sta[now_sta].dis<=per*cap){
if(sta[i].price<sta[now_sta].price){
next_sta = i;
if( (sta[i].dis - sta[now_sta].dis)/per >= V){
//printf("当前车站%d 油箱剩余油量%.3f 前往车站%d 油不够,加油%.3f\n",now_sta,V,next_sta,(sta[i].dis - sta[now_sta].dis)/per - V);
money += ((sta[i].dis - sta[now_sta].dis)/per - V) * sta[now_sta].price;
V=0;
break;
}else{
//printf("当前车站%d 油箱剩余油量%.3f 前往车站%d 油够,要耗油%.3f\n",now_sta,V,next_sta,(sta[i].dis - sta[now_sta].dis)/per - V);
V -= (sta[i].dis - sta[now_sta].dis)/per;
break;
}
}
}else{
break;
}
}
if(next_sta == now_sta){
double min_price = std::numeric_limits<double>::max();
for(int i=now_sta+1; i<n; ++i){
if(sta[i].dis-sta[now_sta].dis<=per*cap){
if(sta[i].price < min_price){
next_sta = i;
min_price = sta[i].price;
}
}else{
break;
}
}
if(next_sta == now_sta){
printf("The maximum travel distance = %.2f\n", sta[now_sta].dis+per*cap);
return 0;
}else{
//printf("当前车站%d 油箱剩余油量%.3f 前往车站%d 要加满,加了:%.3f\n",now_sta,V,next_sta,50-(sta[next_sta].dis - sta[now_sta].dis)/per);
money += (cap - V) * sta[now_sta].price;
V = 50 - (sta[next_sta].dis - sta[now_sta].dis)/per;
}
}
//printf("%d %d\n",now_sta,next_sta);
now_sta = next_sta;
}
printf("%.2f\n",money);
return 0;
}