Ideas
After entering the data, there is no guarantee that the gas stations are entered in the order from Hangzhou to the destination, so you need to sort the station first.
- Ensure that the starting station has a station, otherwise it will not be possible to start, output "The maximum travel distance = 0.00"
- When reaching a station, traverse backward, there are several situations:
- Find a station2 that is cheaper than the current station1, and directly add a suitable amount of oil from the current station1 to station2. Note ⚠️, which may produce residual oil, which will be explained in the next tips.
The amount of fuel needed: station[next].Di-station[now].Di)/Davg-gasleft
- Did not find a cheaper station2, then find a station3 with the lowest oil price on the way through the road with full gas. Fill up station1 and head to station3 (because the price of station1 is still cheaper in nature), then station1 has some gas left.
Refueling amount: C-gasleft
reaches station3 and remaining oil amount: C-(station[next].Di-station[now].Di)/Davg
- To reach the end point, considering that the situation of reaching the end point is very similar to the first case, so directly add the end point to the station list, Pi is 0, and Di is D.
Note ⚠️: output format
- Find a station2 that is cheaper than the current station1, and directly add a suitable amount of oil from the current station1 to station2. Note ⚠️, which may produce residual oil, which will be explained in the next tips.
Code
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
struct Gas{
double Pi;
double Di;
};
bool cmp(Gas a,Gas b){
return a.Di<b.Di;
}
int main(){
double C,D,Davg;
int N;
scanf("%lf%lf%lf%d",&C,&D,&Davg,&N);
vector<Gas> station(N+1);
for(int i=0;i<N;i++){
scanf("%lf%lf",&station[i].Pi,&station[i].Di);
}
station[N].Pi=0;
station[N].Di=D;
sort(station.begin(),station.end(),cmp);
if(station[0].Di!=0){
printf("The maximum travel distance = 0.00\n");
return 0;
}
int now=0;
double mintot=0;
double gasleft=0;
bool unreach=false;
while(now<N){
double minP=INT_MAX;
int next=-1;//代表下一站点
bool found=false;
for(int i=now+1;station[i].Di<=station[now].Di+C*Davg;i++){
if(minP>station[i].Pi){
//就算不比now小也要找到最便宜的
next=i;
minP=station[i].Pi;
}
if(station[now].Pi>station[i].Pi){
next=i;
found=true;
break;
}
}
if(next==-1){
//判断是否无法到达终点
unreach=true;
break;
}
if(found==true){
mintot+=((station[next].Di-station[now].Di)/Davg-gasleft)*station[now].Pi;
gasleft=0;//不必剩油
}
else{
//在最便宜的这里直接加满
mintot+=(C-gasleft)*station[now].Pi;
gasleft=C-(station[next].Di-station[now].Di)/Davg;//剩下油
}
now=next;
}
if(!unreach)
printf("%02.2lf\n",mintot);
else
printf("The maximum travel distance = %02.2lf\n",station[now].Di+C*Davg);
return 0;
}