With highways available, driving a car from Hangzhou to any other city is easy. But since the tank capacity of a car is limited, we have to find gas stations on the way from time to time. Different gas station may give different price. You are asked to carefully design the cheapest route to go.
Each input file contains one test case. For each case, the first line contains 4 positive numbers: C max (≤ 100), the maximum capacity of the tank; D (≤30000), the distance between Hangzhou and the destination city; D avg (≤20), the average distance per unit gas that the car can run; and N (≤ 500), the total number of gas stations. Then N lines follow, each contains a pair of non-negative numbers: P i , the unit gas price, and D i (≤D), the distance between this station and Hangzhou, for i=1,⋯,N. All the numbers in a line are separated by a space.
For each test case, print the cheapest price in a line, accurate up to 2 decimal places. It is assumed that the tank is empty at the beginning. If it is impossible to reach the destination, print The maximum travel distance = X where X is the maximum possible distance the car can run, accurate up to 2 decimal places.
50 1300 12 8
6.00 1250
7.00 600
7.00 150
7.10 0
7.20 200
7.50 400
7.30 1000
6.85 300
749.17
50 1300 12 2
7.10 0
7.00 600
The maximum travel distance = 1200.00
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int inf=99999999;
struct station{
double price,dis;
};
bool cmp(station a,station b){
return a.dis<b.dis;
}
int main(){
double cmax,d,davg;
int n;
cin>>cmax>>d>>davg>>n;
vector<station> sta(n+1);
//sta[0]={0.0,d};//目的地
sta[0].price=0.0;
sta[0].dis=d;
for(int i=1;i<=n;i++)
cin>>sta[i].price>>sta[i].dis;
sort(sta.begin(),sta.end(),cmp);
double nowdis=0.0,maxdis=0.0,nowprice=0.0,totalprice=0.0,leftdis=0.0;
if(sta[0].dis!=0){
cout<<"The maximum travel distance = 0.00";
return 0;
}
else{
nowprice=sta[0].price;
}
while(nowdis<d){
maxdis=nowdis+cmax*davg;
double minPriceDis=0,minPrice=inf;
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+=(nowprice*(cmax-leftdis/davg));
leftdis=cmax*davg-(minPriceDis-nowdis);
nowprice=minPrice;
nowdis=minPriceDis;
}
if(flag==0&&minPrice==inf){
nowdis+=cmax*davg;
printf("The maximum travel distance = %.2f", nowdis);
return 0;
}
}
printf("%.2f", totalprice);
return 0;
}