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 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 300Sample Output 1:
749.17Sample Input 2:
50 1300 12 2 7.10 0 7.00 600Sample Output 2:
The maximum travel distance = 1200.00
这道题主要考验贪心算法,首先根据油箱总容量和每公里耗油量可计算出汽车单次行驶的最大range,然后策略如下:
若在当前点的range内,不存在加油站,那么在当前点+range就是最大行驶距离,程序结束。
若在当前点的range内,存在加油站,然而其他加油站的价格都贵于当前点,那么在当前点加满油,然后行驶到range内最便宜的加油站。
若在当前点的range内,存在加油站,并且存在加油站的价格比当前点便宜,那么选择离当前点最近且比当前点便宜的加油站,在当前点加到刚好能行驶到这个加油站的油即可。
若在当前点的range内,包含了目的地,且距离目的地之间没有其他比当前点便宜的加油站,则在当前点加到能够行驶到目的地的油,程序结束。
分析完毕,另外要注意目的地即出发地的特殊情况。
代码如下
#include <iostream>
#include <string>
#include <iomanip>
#include <cstring>
using namespace std;
int main(void)
{
int Cmax,D,Davg,N;
cin>>Cmax>>D>>Davg>>N;
double price[30001];
memset(price,0,sizeof(price));
while(N--)
{
double p;
int dis;
cin>>p>>dis;
price[dis]=p;
}
cout.setf(ios::fixed);
cout.precision(2);
if(D==0)
{
cout<<0.0;
return 0;
}
if(price[0]==0)
{
cout<<"The maximum travel distance = "<<0.0;
return 0;
}
int pos=0,range=Cmax*Davg;
double totalCost=0,rem=0;
while(true)
{
double minPrice=99999,cost,gas;
int minPos=-1,flag=0;
for(int i=pos+1;i<=pos+range;i++)
{
if(price[i]>0 && (price[i]<minPrice||price[i]<price[pos]))
{
minPrice=price[i];
minPos=i;
if(price[i]<price[pos])
{
flag=1;
break;
}
}
if(i>=D)
{
minPos=D;
flag=2;
break;
}
}
if(flag!=2)
gas=(minPos-pos)*1.0/Davg;
else
gas=(D-pos)*1.0/Davg;
if(minPos==-1)
{
cout<<"The maximum travel distance = "<<(pos+range)*1.0;
return 0;
}
if(flag==0)
{
cost=(Cmax-rem)*price[pos];
rem=Cmax-gas;
}
else
{
cost=(gas-rem)*price[pos];
if(cost<0)
{
cost=0;
rem-=gas;
}
else
rem=0;
flag=0;
}
totalCost+=cost;
pos=minPos;
if(pos==D)
break;
}
cout<<totalCost;
}