- 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
- 51 lines of C++ from the credited upstream file 1786.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 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 countRestrictedPaths(int n, vector<vector<int>>& edges) {4 vector<vector<pair<int, int>>> graph(n);5 6 for (const vector<int>& edge : edges) {7 const int u = edge[0] - 1;8 const int v = edge[1] - 1;9 const int w = edge[2];10 graph[u].emplace_back(v, w);11 graph[v].emplace_back(u, w);12 }13 14 return dijkstra(graph, 0, n - 1);15 }16 17 private:18 int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst) {19 constexpr int kMod = 1'000'000'007;20 21 vector<long> ways(graph.size());22 23 vector<long> dist(graph.size(), LONG_MAX);24 25 ways[dst] = 1;26 dist[dst] = 0;27 using P = pair<long, int>; 28 priority_queue<P, vector<P>, greater<>> minHeap;29 minHeap.emplace(dist[dst], dst);30 31 while (!minHeap.empty()) {32 const auto [d, u] = minHeap.top();33 minHeap.pop();34 if (d > dist[u])35 continue;36 for (const auto& [v, w] : graph[u]) {37 if (d + w < dist[v]) {38 dist[v] = d + w;39 minHeap.emplace(dist[v], v);40 }41 if (dist[v] < dist[u]) {42 ways[u] += ways[v];43 ways[u] %= kMod;44 }45 }46 }47 48 return ways[src];49 }50};51