1033 To Fill or Not to Fill (25 分)
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 Nlines 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
题目大意:
给定汽缸最大容量Cmax,目的地的距离,每单位汽油可行驶的距离,以及n个加油站的信息:给出每个加油站的单位油价与加油站的距离。要求最便宜的旅行方式
思路:
贪心算法:选择第一个距离最近的比当前油站还便宜的油站。那么加到刚好能到的油量即可。如果均比现油站的油价要高则在当前油站加满油然后去到那个较低油价(但高于先油价)的加油站。只需要遍历一次即可
参考代码:
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
struct st{double price, dis;};
double Cmax, d, davg;
int n;
bool cmp(st a, st b){return a.dis < b.dis;}
vector<st> station;
int main(){
scanf("%lf %lf %lf %d", &Cmax, &d, &davg, &n);
station.resize(n + 1);
station[0] = {0.0, d};
for(int i = 1; i <= n; ++i) scanf("%lf%lf", &station[i].price, &station[i].dis);
sort(station.begin(), station.end(), cmp);
if(station[0].dis != 0){
printf("The maximum travel distance = 0.00");
return 0;
}
int now = 0;
double tankremain = 0.0, maxdrv = Cmax * davg, total = 0.0, minprice;
while(now < n){
int k = -1;
minprice = 0x7fffffff;
for(int i = now + 1; i <= n && station[i].dis - station[now].dis <= maxdrv; ++i){
if(station[i].price < minprice){
k = i;
minprice = station[i].price;
}
if(minprice < station[now].price) break;
}
if(k == -1) break;
double need = (station[k].dis - station[now].dis) / davg;
if(minprice < station[now].price){
if(tankremain < need){
total += (need - tankremain) * station[now].price;
tankremain = 0.0;
}else tankremain -= need;
}else{
total +=(Cmax - tankremain) * station[now].price;
tankremain = Cmax - need;
}
now = k;
}
if(now < n) printf("The maximum travel distance = %.2f\n", station[now].dis + maxdrv);
else printf("%.2f", total);
return 0;
}