- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 58 lines of C++ from the credited upstream file 882.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int reachableNodes(vector<vector<int>>& edges, int maxMoves, int n) {4 vector<vector<pair<int, int>>> graph(n);5 vector<int> dist(graph.size(), maxMoves + 1);6 7 for (const vector<int>& edge : edges) {8 const int u = edge[0];9 const int v = edge[1];10 const int cnt = edge[2];11 graph[u].emplace_back(v, cnt);12 graph[v].emplace_back(u, cnt);13 }14 15 const int reachableNodes = dijkstra(graph, 0, maxMoves, dist);16 int reachableSubnodes = 0;17 18 for (const vector<int>& edge : edges) {19 const int u = edge[0];20 const int v = edge[1];21 const int cnt = edge[2];22 23 const int a = dist[u] > maxMoves ? 0 : min(maxMoves - dist[u], cnt);24 25 const int b = dist[v] > maxMoves ? 0 : min(maxMoves - dist[v], cnt);26 reachableSubnodes += min(a + b, cnt);27 }28 29 return reachableNodes + reachableSubnodes;30 }31 32 private:33 int dijkstra(const vector<vector<pair<int, int>>>& graph, int src,34 int maxMoves, vector<int>& dist) {35 dist[src] = 0;36 using P = pair<int, int>; 37 priority_queue<P, vector<P>, greater<>> minHeap;38 minHeap.emplace(dist[src], src);39 40 while (!minHeap.empty()) {41 const auto [d, u] = minHeap.top();42 minHeap.pop();43 44 if (d >= maxMoves)45 break;46 if (d > dist[u])47 continue;48 for (const auto& [v, w] : graph[u])49 if (d + w + 1 < dist[v]) {50 dist[v] = d + w + 1;51 minHeap.emplace(dist[v], v);52 }53 }54 55 return ranges::count_if(dist, [&](int d) { return d <= maxMoves; });56 }57};58