diff --git a/cpp/2207/220702-CN.cpp b/cpp/2207/220702-CN.cpp new file mode 100644 index 0000000..18eb433 --- /dev/null +++ b/cpp/2207/220702-CN.cpp @@ -0,0 +1,43 @@ +#include +#include + +/** + * 871. Minimum Number of Refueling Stops + * A car travels from a starting position to a destination which is target miles east of the starting position. + * There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas. + * The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. + * Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1. + * Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived. + */ + +class Solution { +public: + static int minRefuelStops(int target, int startFuel, const std::vector>& stations) { + int f = startFuel, pos = 0; + std::priority_queue q; + for (const auto& x : stations) { + f -= x[0] - pos; + pos = x[0]; + while (f < 0 && !q.empty()) { + f += q.top(); + q.pop(); + } + if (f < 0 && q.empty()) + return -1; + q.push(x[1]); + } + f -= target - pos; + while (f < 0 && !q.empty()) { + f += q.top(); + q.pop(); + } + if (f < 0 && q.empty()) + return -1; + return stations.size() - q.size(); + } +}; + +int main() { + Solution::minRefuelStops(100, 10, {{10,60},{20,30},{30,30},{60,40}}); + return 0; +} diff --git a/cpp/2207/CMakeLists.txt b/cpp/2207/CMakeLists.txt new file mode 100644 index 0000000..6b6a64c --- /dev/null +++ b/cpp/2207/CMakeLists.txt @@ -0,0 +1,6 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 3.23) +PROJECT(2207) + +SET(CMAKE_CXX_STANDARD 23) + +ADD_EXECUTABLE(2207 220702-CN.cpp) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 1dd5d79..c10d537 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -23,6 +23,7 @@ ADD_EXECUTABLE(leetcode-cpp main.cpp) # ADD_SUBDIRECTORY(2202) # ADD_SUBDIRECTORY(2203) # ADD_SUBDIRECTORY(2204) -#ADD_SUBDIRECTORY(2205) -ADD_SUBDIRECTORY(2206) +# ADD_SUBDIRECTORY(2205) +# ADD_SUBDIRECTORY(2206) +ADD_SUBDIRECTORY(2207) ADD_SUBDIRECTORY(more)