|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + vector<vector<int>> modifiedGraphEdges(int n, vector<vector<int>>& edges, int source, int destination, int target) { |
| 4 | + constexpr int kMax = 2'000'000'000; |
| 5 | + vector<vector<pair<int, int>>> graph(n); |
| 6 | + |
| 7 | + for (const vector<int>& edge : edges) { |
| 8 | + const int u = edge[0]; |
| 9 | + const int v = edge[1]; |
| 10 | + const int w = edge[2]; |
| 11 | + if (w == -1) |
| 12 | + continue; |
| 13 | + graph[u].emplace_back(v, w); |
| 14 | + graph[v].emplace_back(u, w); |
| 15 | + } |
| 16 | + |
| 17 | + int distToDestination = dijkstra(graph, source, destination); |
| 18 | + if (distToDestination < target) |
| 19 | + return {}; |
| 20 | + if (distToDestination == target) { |
| 21 | + // Change the weights of negative edges to an impossible value. |
| 22 | + for (vector<int>& edge : edges) |
| 23 | + if (edge[2] == -1) |
| 24 | + edge[2] = kMax; |
| 25 | + return edges; |
| 26 | + } |
| 27 | + |
| 28 | + for (int i = 0; i < edges.size(); ++i) { |
| 29 | + const int u = edges[i][0]; |
| 30 | + const int v = edges[i][1]; |
| 31 | + int& w = edges[i][2]; |
| 32 | + if (w != -1) |
| 33 | + continue; |
| 34 | + w = 1; |
| 35 | + graph[u].emplace_back(v, 1); |
| 36 | + graph[v].emplace_back(u, 1); |
| 37 | + distToDestination = dijkstra(graph, source, destination); |
| 38 | + if (distToDestination <= target) { |
| 39 | + w += target - distToDestination; |
| 40 | + // Change the weights of negative edges to an impossible value. |
| 41 | + for (int j = i + 1; j < edges.size(); ++j) |
| 42 | + if (edges[j][2] == -1) |
| 43 | + edges[j][2] = kMax; |
| 44 | + return edges; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return {}; |
| 49 | + } |
| 50 | + |
| 51 | + private: |
| 52 | + int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst) { |
| 53 | + vector<int> dist(graph.size(), INT_MAX); |
| 54 | + using P = pair<int, int>; // (d, u) |
| 55 | + priority_queue<P, vector<P>, greater<>> minHeap; |
| 56 | + |
| 57 | + dist[src] = 0; |
| 58 | + minHeap.emplace(dist[src], src); |
| 59 | + |
| 60 | + while (!minHeap.empty()) { |
| 61 | + const auto [d, u] = minHeap.top(); |
| 62 | + minHeap.pop(); |
| 63 | + if (d > dist[u]) |
| 64 | + continue; |
| 65 | + for (const auto& [v, w] : graph[u]) |
| 66 | + if (d + w < dist[v]) { |
| 67 | + dist[v] = d + w; |
| 68 | + minHeap.emplace(dist[v], v); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return dist[dst]; |
| 73 | + } |
| 74 | +}; |
0 commit comments