local ioread = io.read('*a'):gmatch('%d+%p?%d*')
local function read_number()
return tonumber(ioread())
end
local Cmax = read_number() D = read_number() Davg = read_number() N = read_number() Dmax = Cmax*Davg
local stations = {}
local C = 0 cost = 0 Dis = 0 current_station = 1
function getNextStation()
local current_price = stations[current_station].price
local found_station = nil found_index = 0
for index = current_station + 1, N do
local station = stations[index]
if station.distance - Dis > Dmax then
break;
end
if station.price < current_price then
return index;
end
if not found_station or station.price < found_station.price then
found_station = station
found_index = index
end
end
if Dis + Dmax >= D or not found_station then
return nil
end
return found_index
end
function update(station_index, is_better)
local station = stations[station_index]
local Ctarget = is_better and ((station.distance - Dis) / Davg) or Cmax
cost = cost + (Ctarget - C) * stations[current_station].price
C = Ctarget
C = C - (station.distance - Dis) / Davg
Dis = station.distance
current_station = station_index
end
for _ = 1, N do
local price = read_number()
local distance = read_number()
if distance >= 0 and distance <= D then
table.insert(stations, {price = price, distance = distance})
end
end
table.sort(stations, function(a, b) return a.distance < b.distance end)
if stations[1].distance > 0 then
print("The maximum travel distance = 0.00")
return
end
for next_station in getNextStation do
update(next_station, stations[next_station].price < stations[current_station].price)
end
if Dis + Dmax >= D then
Clack = (D - Dis) / Davg - C
cost = cost + Clack * stations[current_station].price
print(string.format("%.2f", cost))
else
print("The maximum travel distance = " .. string.format("%.2f", Dis + Dmax))
end
|