nikunjsoni

787

May 26th, 2021 (edited)
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.33 KB | None | 0 0
  1. #define TUP tuple<int, int, int>
  2. class Solution {
  3. public:
  4.     int findCheapestPrice(int N, vector<vector<int>>& flights, int src, int dst, int k) {
  5.         //make a graph out of the input
  6.         vector<pair<int, int>> graph[N+1];
  7.         for(vector<int> vc : flights){
  8.             graph[vc[0]].push_back({vc[1], vc[2]});
  9.         }
  10.         //use a dist array can also be used for other destinations(Solutions like this Helpful in interviews)
  11.         vector<int> dist(N, INT_MAX);
  12.         //define a queue and intiallize with src, 0 stops and 0 dist to source itself
  13.         queue<TUP> q;
  14.         q.push({src, 0, 0});
  15.        
  16.         while(!q.empty()){
  17.             //destructure values this is similar to -> int start = q.front().first, stops = q.front().second
  18.             auto [start, stops, cost] = q.front();          
  19.             q.pop();
  20.             //crucial work take the min
  21.             dist[start] = min(dist[start], cost);
  22.            
  23.             //edge cases to break
  24.             if(start == dst)
  25.                 continue;
  26.             if(stops > k)
  27.                 continue;
  28.             //traverse adjacent nodes
  29.             for(auto u : graph[start]){
  30.                 auto [node, weight] = u;
  31.                 //only push if giving better results
  32.                 if(cost+weight < dist[node]){
  33.                     q.push({node, stops+1, cost+weight});
  34.                 }
  35.             }
  36.         }
  37.         //check if not path found
  38.         return dist[dst] == INT_MAX ? -1 : dist[dst];
  39.     }
  40. };
  41.  
  42. ----------------------------------------------
  43.  
  44. class Solution {
  45. public:
  46.     int findCheapestPrice(int N, vector<vector<int>>& flights, int src, int dst, int k) {
  47.         k++;
  48.         const int INF = int(1e9);
  49.         vector<vector<int>> dist(N, vector<int>(k+1, INF));
  50.        
  51.         dist[src][0] = 0;
  52.         for(int i=0; i<k; i++){
  53.             if(i>0){
  54.                 for(int j=0; j<N; j++)
  55.                     dist[j][i] = min(dist[j][i], dist[j][i-1]);
  56.             }
  57.             for(auto e: flights){
  58.                 int from = e[0], to=e[1], cost=e[2];
  59.                 if(dist[from][i] == INF) continue;
  60.                 if(dist[from][i]+cost < dist[to][i+1])
  61.                     dist[to][i+1] = dist[from][i]+cost;
  62.             }
  63.         }
  64.         return dist[dst][k] == INF ? -1 : dist[dst][k];
  65.     }
  66. };
  67.  
Add Comment
Please, Sign In to add comment