- 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
- 49 lines of C++ from the credited upstream file 1976.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 countPaths(int n, vector<vector<int>>& roads) {4 vector<vector<pair<int, int>>> graph(n);5 6 for (const vector<int>& road : roads) {7 const int u = road[0];8 const int v = road[1];9 const int w = road[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 19 int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst) {20 constexpr int kMod = 1'000'000'007;21 vector<long> ways(graph.size());22 vector<long> dist(graph.size(), LONG_MAX);23 24 ways[src] = 1;25 dist[src] = 0;26 using P = pair<long, int>; 27 priority_queue<P, vector<P>, greater<>> minHeap;28 minHeap.emplace(dist[src], src);29 30 while (!minHeap.empty()) {31 const auto [d, u] = minHeap.top();32 minHeap.pop();33 if (d > dist[u])34 continue;35 for (const auto& [v, w] : graph[u])36 if (d + w < dist[v]) {37 dist[v] = d + w;38 ways[v] = ways[u];39 minHeap.emplace(dist[v], v);40 } else if (d + w == dist[v]) {41 ways[v] += ways[u];42 ways[v] %= kMod;43 }44 }45 46 return ways[dst];47 }48};49