Paste: Code

Author: Ming Cheng
Mode: c++
Date: Fri, 22 Apr 2022 16:20:55
Plain Text |
typedef pair<int, pair<int, int> > PI; 
class Solution {
public:
    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
        priority_queue<PI, vector<PI>, comp> pq;
        unordered_map <int, vector<vector<int> > > hash; 
        for (auto flight : flights) {
            int s = flight[0], d = flight[1], cost = flight[2]; 
            hash[s].push_back({d, cost}); 
        }
        pq.push({src, {0, -1}}); 
        while (pq.size()) {
            auto top = pq.top(); pq.pop(); 
            int node = top.first, dist = top.second.first, level = top.second.second; 
            if (level < k) {
                for (auto nei : hash[node]) {
                    pq.push({nei[0], {nei[1] + dist, level + 1}}); 
                }
            }
            if (node == dst) 
                return dist; 
        }
        return -1; 
    }
    struct comp {
       bool operator() (PI p1, PI p2) {
           return p1.second.first > p2.second.first; 
       } 
    }; 
};

New Annotation

Summary:
Author:
Mode:
Body: