forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
network-delay-time.cpp
42 lines (40 loc) · 1.33 KB
/
network-delay-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
41
42
// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|)
// Space: O(|E| + |V|) = O(|E|)
// Dijkstra's algorithm
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
using P = pair<int, int>;
vector<vector<P>> adj(N);
for (const auto& time : times) {
int u, v, w;
tie(u, v, w) = make_tuple(time[0] - 1, time[1] - 1, time[2]);
adj[u].emplace_back(v, w);
}
int result = 0;
unordered_set<int> lookup;
unordered_map<int, int> best;
priority_queue<P, vector<P>, greater<P>> min_heap;
min_heap.emplace(0, K - 1);
while (!min_heap.empty() && lookup.size() != N) {
int u;
tie(result, u) = min_heap.top(); min_heap.pop();
lookup.emplace(u);
if (best.count(u) &&
best[u] < result) {
continue;
}
for (const auto& kvp : adj[u]) {
int v, w;
tie(v, w) = kvp;
if (lookup.count(v)) continue;
if (!best.count(v) ||
result + w < best[v]) {
best[v] = result + w;
min_heap.emplace(result + w, v);
}
}
}
return lookup.size() == N ? result : -1;
}
};