-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2699-modify-graph-edge-weights.py
More file actions
74 lines (63 loc) · 2.04 KB
/
2699-modify-graph-edge-weights.py
File metadata and controls
74 lines (63 loc) · 2.04 KB
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
# time complexity: O(e*(v+e)logv)
# space complexity: O(e + v)
import heapq
import math
from typing import List, Tuple
class Solution:
def modifiedGraphEdges(
self,
n: int,
edges: List[List[int]],
source: int,
destination: int,
target: int,
) -> List[List[int]]:
INF = int(2e9)
graph = [[] for _ in range(n)]
for u, v, w in edges:
if w != -1:
graph[u].append((v, w))
graph[v].append((u, w))
currentShortestDistance = self.dijkstra(graph, source, destination)
if currentShortestDistance < target:
return []
if currentShortestDistance == target:
for edge in edges:
if edge[2] == -1:
edge[2] = INF
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))
newDistance = self.dijkstra(graph, source, destination)
if newDistance <= target:
edges[i][2] += target - newDistance
for j in range(i + 1, len(edges)):
if edges[j][2] == -1:
edges[j][2] = INF
return edges
return []
def dijkstra(
self, graph: List[List[Tuple[int, int]]], src: int, destination: int
) -> int:
minDistance = [math.inf] * len(graph)
minDistance[src] = 0
minHeap = [(0, src)]
while minHeap:
d, u = heapq.heappop(minHeap)
if d > minDistance[u]:
continue
for v, w in graph[u]:
if d + w < minDistance[v]:
minDistance[v] = d + w
heapq.heappush(minHeap, (minDistance[v], v))
return minDistance[destination]
n = 3
edges = [[0, 1, -1], [0, 2, 5]]
source = 0
destination = 2
target = 6
print(Solution().modifiedGraphEdges(n, edges, source, destination, target))