- 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
- 47 lines of C++ from the credited upstream file 2737.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 minimumDistance(int n, vector<vector<int>>& edges, int s,4 vector<int>& marked) {5 int ans = INT_MAX;6 vector<vector<pair<int, int>>> graph(n);7 8 for (const vector<int>& edge : edges) {9 const int u = edge[0];10 const int v = edge[1];11 const int w = edge[2];12 graph[u].emplace_back(v, w);13 }14 15 const vector<int> dist = dijkstra(graph, s);16 17 for (const int u : marked)18 ans = min(ans, dist[u]);19 20 return ans == INT_MAX ? -1 : ans;21 }22 23 private:24 vector<int> dijkstra(const vector<vector<pair<int, int>>>& graph, int src) {25 vector<int> dist(graph.size(), INT_MAX);26 27 dist[src] = 0;28 using P = pair<int, int>; 29 priority_queue<P, vector<P>, greater<>> minHeap;30 minHeap.emplace(dist[src], src);31 32 while (!minHeap.empty()) {33 const auto [d, u] = minHeap.top();34 minHeap.pop();35 if (d > dist[u])36 continue;37 for (const auto& [v, w] : graph[u])38 if (d + w < dist[v]) {39 dist[v] = d + w;40 minHeap.emplace(dist[v], v);41 }42 }43 44 return dist;45 }46};47