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.
輸入:
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.
輸出:
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.
樣例輸入:
59 525 19 2 3.00 314 3.00 0
樣例輸出:
82.89
提示:
該題目所要解決的問題是:給定若干加油站資訊,問能否駕駛汽車行駛一定的距離。如果能夠行駛完全程,則計算最小花費。若不能行駛完全程,則最遠能夠行駛多長距離。
拿到這一題,首先判斷汽車是否能夠行駛到終點。什麼情況下汽車無法行駛到終點呢?兩種情況:起點根本就沒有加油站,汽車無法啟動;或者中途兩個加油站之間的距離大於加滿油後汽車能夠行駛的最大距離。前者汽車行駛的最大距離為0.00,而後者最大距離為當前加油站的距離加上在這個加油站加滿油後能夠行駛的最大距離。在這裡,需要將加油站按到杭州的距離從小到大排序。
接下來在能夠行駛到終點的情況下計算最小花費。我們首先從路程來考慮,如果在路上,我們能夠使用最便宜的汽油,當然就在那個加油站加油了。所以從起點開始遍歷每個加油站。假設遍歷到了第i個加油站,我們現在來判斷在加油站i應該加多少油。設當前汽車離杭州的距離為curLen,當前加油站離杭州的距離為nodes[i].dis,加滿油以後汽車能夠行駛的最大距離為(dis=cmax*len)。這樣就有node[i].dis <= curLen <= nodes[i].dis+dis,否則的話第i個加油站的油是不起作用的。於是在第i個加油站的作用範圍內尋找有沒有更為便宜的加油站,如果有,則下次使用這個加油站的油(j),這次汽車應該行駛到這個加油站,即touch=nodes[j].dis。如果沒有找到更為便宜的加油站則可以在第i個加油站加滿油,即touch=nodes[i].dis+dis。然後判斷下次應該行駛到的距離與當前距離的關係,如果下次應當行駛到的距離大於當前距離,則汽車行駛,否則不動(也就是說上個加油站的油更便宜,後一個加油站也便宜,根本就不需要在當前加油站加油)。