-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathminimum-cost-to-repair-edges-to-traverse-a-graph.py
More file actions
50 lines (47 loc) · 1.43 KB
/
minimum-cost-to-repair-edges-to-traverse-a-graph.py
File metadata and controls
50 lines (47 loc) · 1.43 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
# Time: O((n + m) * logr)
# Space: O(n + m)
# binary search, bfs
class Solution(object):
def minCost(self, n, edges, k):
"""
:type n: int
:type edges: List[List[int]]
:type k: int
:rtype: int
"""
def binary_search(left, right, check):
while left <= right:
mid = left+(right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left
def bfs(x):
lookup = [False]*len(adj)
lookup[0] = True
q = [0]
d = 0
while q:
if d == k+1:
break
new_q = []
for u in q:
if u == n-1:
return True
for v, w in adj[u]:
if w > x or lookup[v]:
continue
lookup[v] = True
new_q.append(v)
q = new_q
d += 1
return False
adj = [[] for _ in xrange(n)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
left = min(w for _, _, w in edges)
right = max(w for _, _, w in edges)
result = binary_search(left, right, bfs)
return result if result != right+1 else -1