Skip to content

2699. Modify Graph Edge Weights 👍

  • Time: $O((|V| + |E|)\log |V|)$
  • Space: $O(|E| + |V|)$
 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class Solution {
 public:
  vector<vector<int>> modifiedGraphEdges(int n, vector<vector<int>>& edges,
                                         int source, int destination,
                                         int target) {
    constexpr int kMax = 2'000'000'000;
    vector<vector<pair<int, int>>> graph(n);

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      const int w = edge[2];
      if (w == -1)
        continue;
      graph[u].emplace_back(v, w);
      graph[v].emplace_back(u, w);
    }

    int distToDestination = dijkstra(graph, source, destination);
    if (distToDestination < target)
      return {};
    if (distToDestination == target) {
      // Change the weights of negative edges to an impossible value.
      for (vector<int>& edge : edges)
        if (edge[2] == -1)
          edge[2] = kMax;
      return edges;
    }

    for (int i = 0; i < edges.size(); ++i) {
      const int u = edges[i][0];
      const int v = edges[i][1];
      int& w = edges[i][2];
      if (w != -1)
        continue;
      w = 1;
      graph[u].emplace_back(v, 1);
      graph[v].emplace_back(u, 1);
      distToDestination = dijkstra(graph, source, destination);
      if (distToDestination <= target) {
        w += target - distToDestination;
        // Change the weights of negative edges to an impossible value.
        for (int j = i + 1; j < edges.size(); ++j)
          if (edges[j][2] == -1)
            edges[j][2] = kMax;
        return edges;
      }
    }

    return {};
  }

 private:
  int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst) {
    vector<int> dist(graph.size(), INT_MAX);

    dist[src] = 0;
    using P = pair<int, int>;  // (d, u)
    priority_queue<P, vector<P>, greater<>> minHeap;
    minHeap.emplace(dist[src], src);

    while (!minHeap.empty()) {
      const auto [d, u] = minHeap.top();
      minHeap.pop();
      if (d > dist[u])
        continue;
      for (const auto& [v, w] : graph[u])
        if (d + w < dist[v]) {
          dist[v] = d + w;
          minHeap.emplace(dist[v], v);
        }
    }

    return dist[dst];
  }
};
 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Solution {
  public int[][] modifiedGraphEdges(int n, int[][] edges, int source, int destination, int target) {
    final int kMax = 2_000_000_000;
    List<Pair<Integer, Integer>>[] graph = new List[n];

    for (int i = 0; i < n; i++)
      graph[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      final int w = edge[2];
      if (w == -1)
        continue;
      graph[u].add(new Pair<>(v, w));
      graph[v].add(new Pair<>(u, w));
    }

    int distToDestination = dijkstra(graph, source, destination);
    if (distToDestination < target)
      return new int[0][];
    if (distToDestination == target) {
      // Change the weights of negative edges to an impossible value.
      for (int[] edge : edges)
        if (edge[2] == -1)
          edge[2] = kMax;
      return edges;
    }

    for (int i = 0; i < edges.length; ++i) {
      final int u = edges[i][0];
      final int v = edges[i][1];
      final int w = edges[i][2];
      if (w != -1)
        continue;
      edges[i][2] = 1;
      graph[u].add(new Pair<>(v, 1));
      graph[v].add(new Pair<>(u, 1));
      distToDestination = dijkstra(graph, source, destination);
      if (distToDestination <= target) {
        edges[i][2] += target - distToDestination;
        // Change the weights of negative edges to an impossible value.
        for (int j = i + 1; j < edges.length; ++j)
          if (edges[j][2] == -1)
            edges[j][2] = kMax;
        return edges;
      }
    }

    return new int[0][];
  }

  private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst) {
    int[] dist = new int[graph.length];
    Arrays.fill(dist, Integer.MAX_VALUE);

    dist[src] = 0;
    Queue<Pair<Integer, Integer>> minHeap =
        new PriorityQueue<>((a, b) -> a.getKey().compareTo(b.getKey())) {
          { offer(new Pair<>(dist[src], src)); } // (d, u)
        };

    while (!minHeap.isEmpty()) {
      final int d = minHeap.peek().getKey();
      final int u = minHeap.poll().getValue();
      if (d > dist[u])
        continue;
      for (Pair<Integer, Integer> pair : graph[u]) {
        final int v = pair.getKey();
        final int w = pair.getValue();
        if (d + w < dist[v]) {
          dist[v] = d + w;
          minHeap.offer(new Pair<>(dist[v], v));
        }
      }
    }

    return dist[dst];
  }
}
 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
54
class Solution:
  def modifiedGraphEdges(self, n: int, edges: list[list[int]], source: int, destination: int, target: int) -> list[list[int]]:
    kMax = 2_000_000_000
    graph = [[] for _ in range(n)]

    for u, v, w in edges:
      if w == -1:
        continue
      graph[u].append((v, w))
      graph[v].append((u, w))

    distToDestination = self._dijkstra(graph, source, destination)
    if distToDestination < target:
      return []
    if distToDestination == target:
      # Change the weights of negative edges to an impossible value.
      for edge in edges:
        if edge[2] == -1:
          edge[2] = kMax
      return edges

    for i, (u, v, w) in enumerate(edges):
      if w != -1:
        continue
      edges[i][2] = 1
      graph[u].append((v, 1))
      graph[v].append((u, 1))
      distToDestination = self._dijkstra(graph, source, destination)
      if distToDestination <= target:
        edges[i][2] += target - distToDestination
        # Change the weights of negative edges to an impossible value.
        for j in range(i + 1, len(edges)):
          if edges[j][2] == -1:
            edges[j][2] = kMax
        return edges

    return []

  def _dijkstra(self, graph: list[list[int]], src: int, dst: int) -> int:
    dist = [math.inf] * len(graph)

    dist[src] = 0
    minHeap = [(dist[src], src)]  # (d, u)

    while minHeap:
      d, u = heapq.heappop(minHeap)
      if d > dist[u]:
        continue
      for v, w in graph[u]:
        if d + w < dist[v]:
          dist[v] = d + w
          heapq.heappush(minHeap, (dist[v], v))

    return dist[dst]