1033 To Fill or Not to Fill
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.
Input Specification:
Each input file contains one test case. For each case, the first line contains 4 positive numbers: Cmax (≤ 100), the maximum capacity of the tank; D (≤30000), the distance between Hangzhou and the destination city; Davg (≤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: Pi, the unit gas price, and Di (≤D), the distance between this station and Hangzhou, for i=1,⋯,N. All the numbers in a line are separated by a space.
Output Specification:
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.
Sample Input 1:
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
Sample Output 1:
749.17
Sample Input 2:
50 1300 12 2
7.10 0
7.00 600
Sample Output 2:
The maximum travel distance = 1200.00
代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int inf=0x3f3f3f3f;
struct station{
double price,dis;
};
bool cmp(station a,station b){
return a.dis<b.dis;
}
int main(){
int n,cmax,davg,d;
scanf("%d%d%d%d",&cmax,&d,&davg,&n);
vector<station> sta(n+1);
for(int i=1;i<=n;i++)
scanf("%lf%lf",&sta[i].price,&sta[i].dis);
double maxdis=0,nowdis=0,nowprice,minprice,minpricedis,totalprice=0;
sta[0]={0,d};
sort(sta.begin(),sta.end(),cmp);
if(sta[0].dis!=0){
printf("The maximum travel distance = 0.00\n");
return 0;
}
else
nowprice=sta[0].price;
while(nowdis<d){
int flag=0;
minprice=inf,minprcedis=0;
maxdis=nowdis+cmax*davg;
for(int i=0;i<=n && sta[i].dis<=maxdis;i++){
if(nowdis>=sta[i].dis) continue;//已经走过的站
if(nowprice>sta[i].price){//在当前加油站找到后面可以到达区间比当前站价格要低的加油站
//所以采取的策略是,在本站需要加的油的量 == 当前站到比本站价格低的第一站的距离
totalprice+=nowprice*(sta[i].dis-leftdis-nowdis)/davg;
leftdis=0;
flag=1;
nowdis=sta[i].dis;
nowprice=sta[i].price;
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=maxdis-minpricedis;
nowdis=minpricedis;
nowprice=minprice;
}
if(flag==0 && minprice==inf){//在可以到达的区间内,已经没有加油站了
printf("The maximum travel distance = %.2lf\n",maxdis);
return 0;
}
}
printf("%.2lf\n",totalprice);
return 0;
}
好好学习,天天向上!
我要考研!