- 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 2203.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 long long minimumWeight(int n, vector<vector<int>>& edges, int src1, int src2,4 int dest) {5 vector<vector<pair<int, int>>> graph(n);6 vector<vector<pair<int, int>>> reversedGraph(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 reversedGraph[v].emplace_back(u, w);14 }15 16 const vector<long> fromSrc1 = dijkstra(graph, src1);17 const vector<long> fromSrc2 = dijkstra(graph, src2);18 const vector<long> fromDest = dijkstra(reversedGraph, dest);19 long ans = kMax;20 21 for (int i = 0; i < n; ++i) {22 if (fromSrc1[i] == kMax || fromSrc2[i] == kMax || fromDest[i] == kMax)23 continue;24 ans = min(ans, fromSrc1[i] + fromSrc2[i] + fromDest[i]);25 }26 27 return ans == kMax ? -1 : ans;28 }29 30 private:31 static constexpr long kMax = 10'000'000'000;32 33 vector<long> dijkstra(const vector<vector<pair<int, int>>>& graph, int src) {34 vector<long> dist(graph.size(), kMax);35 36 dist[src] = 0;37 using P = pair<long, 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