forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cheapest-flights-within-k-stops.cpp
42 lines (40 loc) · 1.41 KB
/
cheapest-flights-within-k-stops.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|)
// Space: O(|E| + |V|) = O(|E|)
class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
using P = pair<int, int>;
unordered_map<int, vector<P>> adj;
for (const auto& flight : flights) {
int u, v, w;
tie(u, v, w) = make_tuple(flight[0], flight[1], flight[2]);
adj[u].emplace_back(v, w);
}
unordered_map<int, unordered_map<int, int>> best;
using T = tuple<int, int, int>;
priority_queue<T, vector<T>, greater<T>> min_heap;
min_heap.emplace(0, src, K + 1);
while (!min_heap.empty()) {
int result, u, k;
tie(result, u, k) = min_heap.top(); min_heap.pop();
if (k < 0 ||
(best.count(u) && best[u].count(k) && best[u][k] < result)) {
continue;
}
if (u == dst) {
return result;
}
for (const auto& kvp : adj[u]) {
int v, w;
tie(v, w) = kvp;
if (!best.count(v) ||
!best[v].count(k - 1) ||
result + w < best[v][k - 1]) {
best[v][k - 1] = result + w;
min_heap.emplace(result + w, v, k - 1);
}
}
}
return -1;
}
};