- 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
- 77 lines of C++ from the credited upstream file 2699.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 6 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 vector<vector<int>> modifiedGraphEdges(int n, vector<vector<int>>& edges,4 int source, int destination,5 int target) {6 constexpr int kMax = 2'000'000'000;7 vector<vector<pair<int, int>>> graph(n);8 9 for (const vector<int>& edge : edges) {10 const int u = edge[0];11 const int v = edge[1];12 const int w = edge[2];13 if (w == -1)14 continue;15 graph[u].emplace_back(v, w);16 graph[v].emplace_back(u, w);17 }18 19 int distToDestination = dijkstra(graph, source, destination);20 if (distToDestination < target)21 return {};22 if (distToDestination == target) {23 24 for (vector<int>& edge : edges)25 if (edge[2] == -1)26 edge[2] = kMax;27 return edges;28 }29 30 for (int i = 0; i < edges.size(); ++i) {31 const int u = edges[i][0];32 const int v = edges[i][1];33 int& w = edges[i][2];34 if (w != -1)35 continue;36 w = 1;37 graph[u].emplace_back(v, 1);38 graph[v].emplace_back(u, 1);39 distToDestination = dijkstra(graph, source, destination);40 if (distToDestination <= target) {41 w += target - distToDestination;42 43 for (int j = i + 1; j < edges.size(); ++j)44 if (edges[j][2] == -1)45 edges[j][2] = kMax;46 return edges;47 }48 }49 50 return {};51 }52 53 private:54 int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst) {55 vector<int> dist(graph.size(), INT_MAX);56 57 dist[src] = 0;58 using P = pair<int, int>; 59 priority_queue<P, vector<P>, greater<>> minHeap;60 minHeap.emplace(dist[src], src);61 62 while (!minHeap.empty()) {63 const auto [d, u] = minHeap.top();64 minHeap.pop();65 if (d > dist[u])66 continue;67 for (const auto& [v, w] : graph[u])68 if (d + w < dist[v]) {69 dist[v] = d + w;70 minHeap.emplace(dist[v], v);71 }72 }73 74 return dist[dst];75 }76};77