dvjsharma

Untitled

Aug 21st, 2025
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
  5.     const int INF = 1e9;
  6.     vector<int> cost(n, INF);
  7.     cost[src] = 0;
  8.  
  9.     // Relax edges K+1 times (because K stops = K+1 edges)
  10.     for (int i = 0; i <= K; i++) {
  11.         vector<int> temp = cost; // copy previous state
  12.         for (auto& f : flights) {
  13.             int u = f[0], v = f[1], w = f[2];
  14.             if (cost[u] == INF) continue;
  15.             temp[v] = min(temp[v], cost[u] + w);
  16.         }
  17.         cost = temp;
  18.     }
  19.  
  20.     return cost[dst] == INF ? -1 : cost[dst];
  21. }
  22.  
  23. int main() {
  24.     int n = 5;
  25.     vector<vector<int>> flights = {
  26.         {0, 1, 100},
  27.         {1, 2, 100},
  28.         {2, 3, 100},
  29.         {3, 4, 100},
  30.         {0, 2, 500}
  31.     };
  32.     int src = 0, dst = 4;
  33.  
  34.     // Now you can vary K dynamically
  35.     for (int k = 0; k <= 4; k++) {
  36.         cout << "Cheapest with at most " << k << " stops: "
  37.              << findCheapestPrice(n, flights, src, dst, k) << "\n";
  38.     }
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment