一、技术总结

  1. 是贪心算法的题目,题目主要考虑的问题有几个,是否会在第一个加油站的最近距离大于0,如果是这样那么直接输出答案,因为初始油箱没有汽油;

    第二个是如何选定加油站,如果在可到达距离范围类,我们优先考虑比当前加油站价格更低的,然后如果有,就直接到达这里,如果没有那也要选出这里面价格最低的那个加油站,

    然后在当前加油站,加满油箱。这样可以更加的省钱,那么油箱会多出油行驶距离(leftdis = Cmax*Davg -(minPriceDis - nowdis))。
  2. 可以开始判断最后结局了,如果到达最后一个加油站,并且加上最大行驶距离还是没有到达,那么便输出答案,无法到达。
  3. 这里可以提供一个巧妙的方法,就是在把当前目的地距离,当成一个加油站,然后判断条件是while(nowdis < D),这样就无需纠结目的地如果在加油站中间该如何计算距离的尴尬局面

    并且不好想通。
  4. for循环的时候,注意几个点,也就是小于等于,i<=N && sta[i]<=maxdis

二、参考代码

#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
const int inf = 999999;
struct station{
double price, dis;
};
bool cmp1(station a, station b){
return a.dis < b.dis;
}
int main(){
double Cmax, D, Davg;
int N;
scanf("%lf%lf%lf%d", &Cmax, &D, &Davg, &N);
vector<station> sta(N+1);
sta[0] = {0.0, D};
for(int i = 1; i <= N; i++){
scanf("%lf%lf", &sta[i].price, &sta[i].dis);
}
sort(sta.begin(), sta.end(), cmp1);
double nowdis = 0.0, maxdis = 0.0, nowPrice = 0.0, totalPrice = 0.0, leftdis = 0.0;
if(sta[0].dis != 0){
printf("The maximum travel distance = 0.00");
return 0;
}else{
nowPrice = sta[0].price;
}
while(nowdis < D){
maxdis = nowdis + Cmax*Davg;
double minPrice = inf, minPriceDis = 0;
int flag = 0;
for(int i = 1; i <= N && sta[i].dis <= maxdis; i++){
if(sta[i].dis <= nowdis) continue;
if(sta[i].price < nowPrice){
totalPrice += (sta[i].dis - nowdis - leftdis) * nowPrice / Davg;
leftdis = 0.0;
nowPrice = sta[i].price;
nowdis = sta[i].dis;
flag = 1;
break;
}
if(sta[i].price < minPrice){
minPrice = sta[i].price;
minPriceDis = sta[i].dis;
}
}
if(flag == 0 && minPrice != inf){
totalPrice += (Cmax - leftdis/Davg) * nowPrice;
leftdis = maxdis - minPriceDis;//(Cmax*Davg - (minPriceDis - nowdis));
nowPrice = minPrice;
nowdis = minPriceDis;
}
if(flag == 0 && minPrice == inf){
//nowdis += Cmax * Davg;
printf("The maximum travel distance = %.2f", maxdis);
return 0;
}
}
printf("%.2f", totalPrice);
return 0;
}
05-11 03:40