E - 燃料補給の旅 / Journey of Refueling Editorial by admin Editorial for printing
gemini-3.5-flash-highSummary
This problem asks for the minimum cost to reach a destination in a car with a limited fuel tank capacity, where the gas prices vary at each town.
By simulating a hypothetical refund (greedy approach) where we always keep the tank full during travel and, upon reaching a cheaper gas station, “cancel the expensive gas bought in the past and replace it with the new cheaper gas,” we can solve this problem efficiently in \(O(N)\) time complexity.
Analysis
1. Naive Approach and Its Limitations
A naive greedy approach would be: “Find the cheapest town reachable within the tank capacity \(T\) from the current town, and buy just enough gas to reach it or fill up there.” However, implementing this naively requires lookahead to decide “which town to buy how much gas from next,” leading to a high time complexity like \(O(N^2)\) with brute-force search. Under the constraint \(N \le 5 \times 10^5\), a faster algorithm is required.
2. Thinking Backwards: Allowing “Refunds”
To simplify this problem, let us consider the following hypothetical rule:
“At any time and place, you can return (refund) the gas in your tank at the price you bought it.”
Even with this rule, the final minimum cost does not change. (This is because looking ahead to future prices and “buying more at cheaper places” is equivalent to “returning expensive gas later and replacing it with cheaper gas”).
By introducing this rule, Takahashi can adopt a very simple strategy (greedy approach):
- Always keep the tank full (\(T\) liters) while moving forward.
- When traveling, consume gas starting from the cheapest one currently in possession.
- Upon arriving at a new town \(i\), if there is any gas in the tank bought at a higher price than the current town’s gas price \(C_i\), return all of it and buy gas at price \(C_i\) instead.
- Upon reaching the destination (town \(N\)), return all remaining gas in the tank (effectively paying only for the gas actually consumed).
By taking this strategy, we can proceed while always maintaining the “optimal purchase plan at that point in time.”
Algorithm
To implement this “refund” strategy efficiently, we use a deque (double-ended queue). The deque stores pairs of [unit price of gas, quantity].
The specific steps are as follows:
Step 1: Initialization
- Buy \(T\) liters of gas at price \(C_1\) at town 1 to fill up the tank.
- Add
[C[0], T]to the deque, and set the tentative total expendituretotal_costto \(C_1 \times T\).
Step 2: Traveling and Replacing at Each Town (Repeat for \(i = 1\) to \(N-1\))
- Gas consumption by traveling:
- Consume \(D_i\) liters of gas required to travel to the next town.
- Remove and consume (delete) a total of \(D_i\) liters starting from the front (cheapest gas) of the deque.
- Returning and replacing expensive gas:
- If there is gas at the back of the deque (the most recently bought expensive gas) that is more expensive than the next town’s price \(C_{i+1}\), pop it from the deque to return it.
- Subtract the cost of the returned gas from
total_cost, and record the returned amount (replaced_amt).
- Refilling to full:
- Purchase new gas at the new price \(C_{i+1}\) equal to the sum of “the amount consumed by travel \(D_i\)” and “the returned amount
replaced_amt”. - Add the cost of this purchase to
total_cost, and append[C[i+1], purchase_amount]to the back of the deque. This brings the tank back to full (\(T\) liters).
- Purchase new gas at the new price \(C_{i+1}\) equal to the sum of “the amount consumed by travel \(D_i\)” and “the returned amount
Step 3: Settlement upon reaching the destination
- Upon arriving at town \(N\), the remaining gas in the tank is no longer needed.
- Return all remaining gas in the deque, and subtract its cost from
total_cost. - The final
total_costwill be the answer.
Complexity
Time Complexity: \(O(N)\)
At each town \(i\), adding an element (append) to the deque is performed at most once.
Also, removing elements from the deque (popleft due to consumption, and pop due to refunds) is performed at most once per element.
Therefore, the total number of deque operations throughout the loop of moving between towns is \(O(N)\), resulting in an overall time complexity of \(O(N)\).
Space Complexity: \(O(N)\)
The number of elements stored in the deque is at most \(N\). Since the size of the arrays to store the input data is also \(O(N)\), the space complexity is \(O(N)\).
Key Implementation Details
Unreachability Check: If there is even a single adjacent interval where \(D_i > T\), it is impossible to travel even with a full tank. In this case, immediately output
-1and terminate.Maintaining Deque Monotonicity: In this algorithm, the gas in the deque is always maintained in a state where “the front is the cheapest, and it becomes more expensive towards the back (monotonically non-decreasing)”. Therefore, simply consuming from the front and returning from the back guarantees that the greedy strategy remains correct.
Merging Same Prices: In the implementation, if the price of the gas to be added to the back of the deque is the same as the price of the gas already at the back, you can save the number of elements in the deque by merging the quantities instead of keeping them as separate elements.
Source Code
from collections import deque
import sys
def solve():
# 入力の高速読み込み
input_data = sys.stdin.read().split()
if not input_data:
return
N = int(input_data[0])
T = int(input_data[1])
C = [int(x) for x in input_data[2 : 2 + N]]
D = [int(x) for x in input_data[2 + N : 2 + N + N - 1]]
# 到達可能かどうかの判定
for d in D:
if d > T:
print(-1)
return
# デックの初期化
# 各要素は [価格, ガソリン量]
q = deque()
q.append([C[0], T])
total_cost = C[0] * T
current_volume = T
for i in range(N - 1):
# 1. 移動によるガソリンの消費(最も安いガソリンから優先的に消費する)
d = D[i]
current_volume -= d
while d > 0:
p, amt = q[0]
if amt <= d:
d -= amt
q.popleft()
else:
q[0][1] -= d
d = 0
# 2. 新しい町でのガソリンの置き換えと補給
c_next = C[i + 1]
# 現在のタンク内にある、c_next より高いガソリンをすべてキャンセルする
replaced_amt = 0
while q and q[-1][0] > c_next:
p, amt = q.pop()
total_cost -= p * amt
replaced_amt += amt
# キャンセルした分 + 減った分を c_next で新規購入して満タンにする
buy_amt = (T - current_volume) + replaced_amt
if buy_amt > 0:
total_cost += c_next * buy_amt
if q and q[-1][0] == c_next:
q[-1][1] += buy_amt
else:
q.append([c_next, buy_amt])
current_volume = T
# 3. 目的地に到着した時点で、タンクに残っているガソリンは不要なので返品(返金)する
for p, amt in q:
total_cost -= p * amt
print(total_cost)
if __name__ == "__main__":
solve()
This editorial was generated by gemini-3.5-flash-high.
posted:
last update: