diff --git a/CMakeLists.txt b/CMakeLists.txt index 219c62da..5753f81d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -75,6 +75,7 @@ add_task(can-place-flowers) add_task(candy) add_task(capacity-to-ship-packages-within-d-days) add_task(champagne-tower) +add_task(cheapest-flights-within-k-stops) add_task(check-completeness-of-a-binary-tree) add_task(check-if-array-is-sorted-and-rotated) add_task(check-if-it-is-a-straight-line) diff --git a/solutions/cheapest-flights-within-k-stops/CMakeLists.txt b/solutions/cheapest-flights-within-k-stops/CMakeLists.txt new file mode 100644 index 00000000..8b8493a7 --- /dev/null +++ b/solutions/cheapest-flights-within-k-stops/CMakeLists.txt @@ -0,0 +1 @@ +add_catch(test_cheapest_flights_within_k_stops test.cpp) diff --git a/solutions/cheapest-flights-within-k-stops/solution.hpp b/solutions/cheapest-flights-within-k-stops/solution.hpp new file mode 100644 index 00000000..d8da7a0e --- /dev/null +++ b/solutions/cheapest-flights-within-k-stops/solution.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include + +class Solution { +public: + static int findCheapestPrice(int n, + const std::vector> &flights, + int src, int dst, int k) { + std::vector>> graph(n); + for (const auto &edge : flights) { + const auto from = edge[0], to = edge[1], price = edge[2]; + graph[from].push_back({to, price}); + } + + std::vector distances(n, INT_MAX); + distances[src] = 0; + + std::queue> queue; + queue.push({src, 0}); + + for (int stops = 0; !queue.empty() && stops <= k; ++stops) { + for (int sz = queue.size(); sz; --sz) { + const auto [u, distance] = queue.front(); + queue.pop(); + + for (const auto &[v, w] : graph[u]) { + if (distances[v] > distance + w) { + distances[v] = distance + w; + queue.push({v, distance + w}); + } + } + } + } + + return distances[dst] == INT_MAX ? -1 : distances[dst]; + } +}; diff --git a/solutions/cheapest-flights-within-k-stops/test.cpp b/solutions/cheapest-flights-within-k-stops/test.cpp new file mode 100644 index 00000000..3a67f885 --- /dev/null +++ b/solutions/cheapest-flights-within-k-stops/test.cpp @@ -0,0 +1,27 @@ +#include + +#include + +TEST_CASE("Simple") { + { + int n = 4; + std::vector> flights{ + {0, 1, 100}, {1, 2, 100}, {2, 0, 100}, {1, 3, 600}, {2, 3, 200}}; + int src = 0, dst = 3, k = 1; + REQUIRE(700 == Solution::findCheapestPrice(n, flights, src, dst, k)); + } + { + int n = 3; + std::vector> flights{ + {0, 1, 100}, {1, 2, 100}, {0, 2, 500}}; + int src = 0, dst = 2, k = 1; + REQUIRE(200 == Solution::findCheapestPrice(n, flights, src, dst, k)); + } + { + int n = 3; + std::vector> flights{ + {0, 1, 100}, {1, 2, 100}, {0, 2, 500}}; + int src = 0, dst = 2, k = 0; + REQUIRE(500 == Solution::findCheapestPrice(n, flights, src, dst, k)); + } +}