- 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
- 56 lines of C++ from the credited upstream file 3123.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 4 vector<bool> findAnswer(int n, vector<vector<int>>& edges) {5 vector<bool> ans;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 graph[v].emplace_back(u, w);14 }15 16 const vector<int> from0 = dijkstra(graph, 0);17 const vector<int> from1 = dijkstra(graph, n - 1);18 19 for (const vector<int>& edge : edges) {20 const int u = edge[0];21 const int v = edge[1];22 const int w = edge[2];23 ans.push_back(from0[u] + w + from1[v] == from0[n - 1] ||24 from0[v] + w + from1[u] == from0[n - 1]);25 }26 27 return ans;28 }29 30 private:31 static constexpr int kMax = 1'000'000'000;32 33 vector<int> dijkstra(const vector<vector<pair<int, int>>>& graph, int src) {34 vector<int> dist(graph.size(), kMax);35 36 dist[src] = 0;37 using P = pair<int, int>; 38 priority_queue<P, vector<P>, greater<>> minHeap;39 minHeap.emplace(dist[src], src);40 41 while (!minHeap.empty()) {42 const auto [d, u] = minHeap.top();43 minHeap.pop();44 if (d > dist[u])45 continue;46 for (const auto& [v, w] : graph[u])47 if (d + w < dist[v]) {48 dist[v] = d + w;49 minHeap.emplace(dist[v], v);50 }51 }52 53 return dist;54 }55};56