E - 燃料補給の旅 / Journey of Refueling Editorial by admin Editorial for printing
gemini-3.5-flash-highOverview
This problem asks us to find a route to reach the destination (town \(N\)) with the minimum cost using a car with a fuel tank capacity of \(T\), where the gas prices vary at each town.
By using a greedy approach of “always keeping the tank full, and when finding a cheaper gas station, ‘returning (refunding)’ the expensive gas currently held and replacing it with the cheaper gas” along with a double-ended queue (deque), we can solve this problem efficiently in \(O(N)\) time complexity.
Analysis
1. Determining Reachability
If there is even a single interval between adjacent towns where \(D_i > T\), it is impossible to cross that interval even with a full tank, making the destination unreachable. In this case, we immediately output -1.
If \(D_i \leq T\) for all \(i\), reaching the destination is always possible.
2. Deriving the Greedy Strategy
Optimally, we want to buy gas at the cheapest towns possible. However, due to the tank capacity limit \(T\), there is a limit to how much we can “stockpile gas needed for the future at the cheapest town currently available.”
To handle this constraint simply, we can consider the following “virtual refund” approach:
- Always travel with a full tank: When starting from town \(1\), we temporarily buy \(T\) liters of gas (filling the tank to capacity) at the price \(C_1\).
- Returning expensive gas: Suppose during the journey, we arrive at a cheaper gas station (price \(C_{\text{new}}\)) than the gas currently in the tank. At this point, if we assume we “return the gas bought at a higher price in the past” at its original cost on the spot, and buy back gas at the cheaper price \(C_{\text{new}}\) instead, we can reduce the cost without exceeding the tank capacity \(T\).
- Consumption rule: When moving between towns, we preferentially consume the “oldest gas (i.e., bought earliest)” among the gas currently in the tank.
- Final adjustment: Upon arriving at the destination (town \(N\)), any gas remaining in the tank was not actually needed. We return (refund) all of it at their respective purchase prices to determine the final minimum cost.
By adopting this strategy, we can find the optimal solution simply by simulating the process from left to right, without having to strictly look ahead to see which gas will remain in the future.
Algorithm
We manage the contents of the tank as a list of information: “at which town, at what price, and how many liters of gas were bought.”
This list is managed using a double-ended queue (std::deque) to satisfy the following properties:
- Front: The oldest and cheapest gas (to be consumed)
- Back: The newest and most expensive gas (to be returned or replenished)
The elements of the queue will be pairs of {price, amount}.
Detailed Steps of the Process
Initialization: Buy \(T\) liters of gas at price \(C_1\) in town \(1\).
- Add \(C_1 \times T\) to the cost.
- Push
{C_1, T}to thedeque.
Simulation of each move (from \(i = 1\) to \(N-1\)):
- Consumption: To move from town \(i\) to \(i+1\), we consume \(D_i\) liters of gas.
- Pop or decrease elements from the front of the
dequeuntil a total of \(D_i\) liters is consumed.
- Pop or decrease elements from the front of the
- Arrival: Arrive at town \(i+1\).
- If we have reached the destination (town \(N\)), terminate the loop here.
- Otherwise, check the price \(C_{i+1}\) of the current town.
- Return (Replacement):
- Pop elements from the back of the
dequeas long as their price is greater than or equal to \(C_{i+1}\), and subtract the corresponding amount from the total cost (return process).
- Pop elements from the back of the
- Replenishment:
- To fill the tank (up to \(T\) liters), buy the deficient amount (\(T - \text{current total gas in the tank}\)) of gas at price \(C_{i+1}\), add this to the cost, and push it to the back of the
deque.
- To fill the tank (up to \(T\) liters), buy the deficient amount (\(T - \text{current total gas in the tank}\)) of gas at price \(C_{i+1}\), add this to the cost, and push it to the back of the
- Consumption: To move from town \(i\) to \(i+1\), we consume \(D_i\) liters of gas.
Final Refund: After arriving at town \(N\), return all remaining gas in the
dequeat their respective purchase prices (subtract from the cost).Output: Print the final cost.
Complexity
Time Complexity: \(O(N)\) Gas is added at each town at most once. Furthermore, the number of times an element is removed (consumed or returned) from the
dequeis also at most once per element throughout the entire process. Therefore, by amortized analysis, the total number of operations on thedequeacross the entire loop is \(O(N)\), which runs extremely fast.Space Complexity: \(O(N)\) The number of elements stored in the
dequeis at most \(N\). The size of the arrays required to store the input is also \(O(N)\).
Implementation Points
Preventing Overflow: The unit price of gas \(C_i\) and the tank capacity \(T\) can be up to \(10^9\), and the accumulated cost calculated during the journey can temporarily exceed \(10^{18}\). To compute this safely in C++, we use a 128-bit integer type (
__int128_t) for cost calculations.Outputting
__int128_t: Since__int128_tcannot be directly outputted using standardstd::cout, we implement a helper functionprint128in the code to convert the value into a decimal string for output.Source Code
#include <iostream>
#include <vector>
#include <deque>
#include <string>
#include <algorithm>
using namespace std;
struct Element {
long long price;
long long amount;
};
// Helper function to print __int128_t
void print128(__int128_t x) {
if (x == 0) {
cout << 0 << "\n";
return;
}
string s = "";
while (x > 0) {
s += (char)('0' + (x % 10));
x /= 10;
}
reverse(s.begin(), s.end());
cout << s << "\n";
}
int main() {
// Optimize standard I/O operations for performance
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int N;
long long T;
if (!(cin >> N >> T)) return 0;
vector<long long> C(N);
for (int i = 0; i < N; ++i) {
cin >> C[i];
}
vector<long long> D(N - 1);
bool possible = true;
for (int i = 0; i < N - 1; ++i) {
cin >> D[i];
if (D[i] > T) {
possible = false;
}
}
// If any single distance exceeds the tank capacity, it's impossible to reach the destination
if (!possible) {
cout << -1 << "\n";
return 0;
}
deque<Element> dq;
__int128_t total_cost = 0;
long long current_total_amount = 0;
// Start at Town 1: Fill the tank to capacity T with gas at price C[0]
dq.push_back({C[0], T});
total_cost += (__int128_t)C[0] * T;
current_total_amount = T;
for (int i = 0; i < N - 1; ++i) {
// Move from Town i+1 to Town i+2 (consuming D[i] gas)
long long rem_demand = D[i];
while (rem_demand > 0) {
if (dq.front().amount <= rem_demand) {
rem_demand -= dq.front().amount;
current_total_amount -= dq.front().amount;
dq.pop_front();
} else {
dq.front().amount -= rem_demand;
current_total_amount -= rem_demand;
rem_demand = 0;
}
}
// Arrived at Town i+2
long long next_price = C[i+1];
// If we reached the destination, stop buying/replacing gas
if (i + 1 == N - 1) {
break;
}
// Replace any gasoline that is more expensive than next_price
while (!dq.empty() && dq.back().price >= next_price) {
total_cost -= (__int128_t)dq.back().price * dq.back().amount;
current_total_amount -= dq.back().amount;
dq.pop_back();
}
// Refuel up to capacity T with next_price
long long needed = T - current_total_amount;
if (needed > 0) {
dq.push_back({next_price, needed});
total_cost += (__int128_t)next_price * needed;
current_total_amount += needed;
}
}
// Refund any leftover gasoline in the tank at Town N
while (!dq.empty()) {
total_cost -= (__int128_t)dq.back().price * dq.back().amount;
dq.pop_back();
}
print128(total_cost);
return 0;
}
This editorial was generated by gemini-3.5-flash-high.
posted:
last update: