forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modify-graph-edge-weights.cpp
53 lines (51 loc) · 1.88 KB
/
modify-graph-edge-weights.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) by using binary heap,
// if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)
// Space: O(|E| + |V|) = O(|E|)
// dijkstra's algorithm
class Solution {
public:
vector<vector<int>> modifiedGraphEdges(int n, vector<vector<int>>& edges, int source, int destination, int target) {
vector<vector<pair<int, int>>> adj(n);
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1], e[2]);
adj[e[1]].emplace_back(e[0], e[2]);
}
const auto& dijkstra = [&](int start, int x) {
vector<int> best(size(adj), target + 1);
best[start] = 0;
priority_queue<pair<int64_t, int>, vector<pair<int64_t, int>>, greater<pair<int64_t, int>>> min_heap;
min_heap.emplace(0, start);
while (!empty(min_heap)) {
const auto [curr, u] = min_heap.top(); min_heap.pop();
if (curr > best[u]) {
continue;
}
for (auto [v, w] : adj[u]) {
if (w == -1) {
w = x;
}
if (best[v] - curr <= w) {
continue;
}
best[v] = curr + w;
min_heap.emplace(curr + w, v);
}
}
return best;
};
const auto& left = dijkstra(source, 1);
if (!(left[destination] <= target)) {
return {};
}
const auto& right = dijkstra(destination, target + 1);
if (!(right[source] >= target)) {
return {};
}
for (auto& e : edges) {
if (e[2] == -1) {
e[2] = max({target - left[e[0]] - right[e[1]], target - left[e[1]] - right[e[0]], 1});
}
}
return edges;
}
};