|
| 1 | +// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|), |
| 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 | +class Solution { |
| 6 | +public: |
| 7 | + int reachableNodes(vector<vector<int>>& edges, int M, int N) { |
| 8 | + using P = pair<int, int>; |
| 9 | + vector<vector<P>> adj(N); |
| 10 | + for (const auto& edge: edges) { |
| 11 | + int u = edge[0], v = edge[1], w = edge[2]; |
| 12 | + adj[u].emplace_back(v, w); |
| 13 | + adj[v].emplace_back(u, w); |
| 14 | + } |
| 15 | + unordered_map<int, int> best; |
| 16 | + best[0] = 0; |
| 17 | + unordered_map<int, unordered_map<int, int>> count; |
| 18 | + int result = 0; |
| 19 | + priority_queue<P, vector<P>, greater<P>> min_heap; |
| 20 | + min_heap.emplace(0, 0); |
| 21 | + while (!min_heap.empty()) { |
| 22 | + int curr_total, u; |
| 23 | + tie(curr_total, u) = min_heap.top(); min_heap.pop(); |
| 24 | + if (best.count(u) && best[u] < curr_total) { |
| 25 | + continue; |
| 26 | + } |
| 27 | + ++result; |
| 28 | + for (const auto& kvp: adj[u]) { |
| 29 | + int v, w; |
| 30 | + tie(v, w) = kvp; |
| 31 | + count[u][v] = min(w, M - curr_total); |
| 32 | + int next_total = curr_total + w + 1; |
| 33 | + if (next_total <= M && |
| 34 | + (!best.count(v) || next_total < best[v])) { |
| 35 | + best[v] = next_total; |
| 36 | + min_heap.emplace(next_total, v); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + for (const auto& edge: edges) { |
| 41 | + int u = edge[0], v = edge[1], w = edge[2]; |
| 42 | + result += min(w, count[u][v] + count[v][u]); |
| 43 | + } |
| 44 | + return result; |
| 45 | + } |
| 46 | +}; |
0 commit comments