- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 65 lines of Python from the credited upstream file network-recovery-pathways.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def findMaxPathScore(self, edges, online, k):7 """8 :type edges: List[List[int]]9 :type online: List[bool]10 :type k: int11 :rtype: int12 """13 INF = float("inf")14 def binary_search_right(left, right, check):15 while left <= right:16 mid = left+(right-left)217 if not check(mid):18 right = mid-119 else:20 left = mid+121 return right22 23 def topological_sort():24 in_degree = [0]*len(adj)25 for u in xrange(len(adj)):26 for v, _ in adj[u]:27 in_degree[v] += 128 result = []29 q = [u for u in xrange(len(adj)) if not in_degree[u]]30 while q:31 new_q = []32 for u in q:33 result.append(u)34 for v, _ in adj[u]:35 in_degree[v] -= 136 if in_degree[v]:37 continue38 new_q.append(v)39 q = new_q40 return result41 42 def check(x):43 dist = [INF]*len(adj)44 dist[0] = 045 for u in order:46 if dist[u] == INF:47 continue48 for v, c in adj[u]:49 if not (c >= x and online[v]):50 continue51 dist[v] = min(dist[v], dist[u]+c)52 return dist[-1] <= k53 54 adj = [[] for _ in xrange(len(online))]55 for u, v, c in edges:56 adj[u].append((v, c))57 order = topological_sort()58 left, right = INF, 059 for u in xrange(len(adj)):60 for _, c in adj[u]:61 left = min(left, c)62 right = max(right, c)63 result = binary_search_right(left, right, check)64 return result if result >= left else -165