-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution2.cpp
33 lines (30 loc) · 910 Bytes
/
Solution2.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
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
const int inf = 1 << 29;
using pii = pair<int, int>;
vector<vector<pii>> g(n);
for (auto& edge : times) {
g[edge[0] - 1].emplace_back(edge[1] - 1, edge[2]);
}
vector<int> dist(n, inf);
dist[k - 1] = 0;
priority_queue<pii, vector<pii>, greater<>> pq;
pq.emplace(0, k - 1);
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
if (d > dist[u]) {
continue;
}
for (auto& [v, w] : g[u]) {
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.emplace(dist[v], v);
}
}
}
int ans = ranges::max(dist);
return ans == inf ? -1 : ans;
}
};