forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-cost-to-reach-destination-in-time.cpp
40 lines (38 loc) · 1.48 KB
/
minimum-cost-to-reach-destination-in-time.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
// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|),
// if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)
// Space: O(|E| + |V|) = O(|E|)
// Dijkstra's algorithm
class Solution {
public:
int minCost(int maxTime, vector<vector<int>>& edges, vector<int>& passingFees) {
using P = pair<int, int>;
unordered_map<int, vector<P>> adj;
for (const auto& edge : edges) {
int u, v, w;
tie(u, v, w) = make_tuple(edge[0], edge[1],edge[2]);
adj[u].emplace_back(v, w);
adj[v].emplace_back(u, w);
}
unordered_map<int, int> best;
best[0] = 0;
using T = tuple<int, int, int>;
priority_queue<T, vector<T>, greater<T>> min_heap;
min_heap.emplace(passingFees[0], 0, 0);
while (!empty(min_heap)) {
const auto [result, u, w] = min_heap.top(); min_heap.pop();
if (w > maxTime) { // state with best[u] < w can't be filtered, which may have less cost
continue;
}
if (u == size(passingFees) - 1) {
return result;
}
for (const auto& [v, nw] : adj[u]) {
if (!best.count(v) || w + nw < best[v]) { // from less cost to more cost, only need to check state with less time
best[v] = w + nw;
min_heap.emplace(result + passingFees[v], v, w + nw);
}
}
}
return -1;
}
};