Skip to content

Commit 85a7950

Browse files
authored
Create minimum-time-to-visit-disappearing-nodes.cpp
1 parent b49e820 commit 85a7950

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) by using binary heap,
2+
// if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)
3+
// Space: O(|E| + |V|) = O(|E|)
4+
5+
// dijkstra's algorithm
6+
class Solution {
7+
public:
8+
vector<int> minimumTime(int n, vector<vector<int>>& edges, vector<int>& disappear) {
9+
static const int INF = numeric_limits<int>::max();
10+
11+
vector<vector<pair<int, int>>> adj(n);
12+
for (const auto& e : edges) {
13+
adj[e[0]].emplace_back(e[1], e[2]);
14+
adj[e[1]].emplace_back(e[0], e[2]);
15+
}
16+
const auto& modified_dijkstra = [&](int start) {
17+
vector<int> best(n, -1);
18+
best[start] = 0;
19+
priority_queue<pair<int64_t, int>, vector<pair<int64_t, int>>, greater<pair<int64_t, int>>> min_heap;
20+
min_heap.emplace(best[start], start);
21+
while (!empty(min_heap)) {
22+
const auto [curr, u] = min_heap.top(); min_heap.pop();
23+
if (curr != best[u]) {
24+
continue;
25+
}
26+
for (auto [v, w] : adj[u]) {
27+
if (!(w < min(best[v] != -1 ? best[v] : INF, disappear[v]) - curr)) { // modified
28+
continue;
29+
}
30+
best[v] = curr + w;
31+
min_heap.emplace(best[v], v);
32+
}
33+
}
34+
return best;
35+
};
36+
37+
return modified_dijkstra(0);
38+
}
39+
};

0 commit comments

Comments
 (0)