- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 77 lines of Python from the credited upstream file minimum-distance-excluding-one-maximum-weighted-edge.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import heapq5 6 78class Solution(object):9 def minCostExcludingMax(self, n, edges):10 """11 :type n: int12 :type edges: List[List[int]]13 :rtype: int14 """15 INF = float("inf")16 L = 117 def dijkstra(src, dst):18 dist = [[INF]*len(adj) for _ in xrange(L+1)]19 excl = 020 dist[excl][src] = 021 min_heap = [(dist[excl][src], src, excl)]22 while min_heap:23 curr, u, excl = heapq.heappop(min_heap)24 if curr > dist[excl][u]:25 continue26 if u == dst:27 break28 for v, w in adj[u]:29 if excl+1 < len(dist) and curr < dist[excl+1][v]:30 dist[1][v] = curr31 heapq.heappush(min_heap, (dist[excl+1][v], v, 1))32 if curr+w < dist[excl][v]:33 dist[excl][v] = curr+w34 heapq.heappush(min_heap, (dist[excl][v], v, excl))35 return dist[L][dst]36 37 adj = [[] for _ in xrange(n)]38 for u, v, w in edges:39 adj[u].append((v, w))40 adj[v].append((u, w))41 return dijkstra(0, n-1)42 43 44454647class Solution2(object):48 def minCostExcludingMax(self, n, edges):49 """50 :type n: int51 :type edges: List[List[int]]52 :rtype: int53 """54 INF = float("inf")55 def dijkstra(u):56 dist = [INF]*len(adj)57 dist[u] = 058 min_heap = [(dist[u], u)]59 while min_heap:60 curr, u = heapq.heappop(min_heap)61 if curr > dist[u]:62 continue63 for v, w in adj[u]:64 if not curr+w < dist[v]:65 continue66 dist[v] = curr+w67 heapq.heappush(min_heap, (dist[v], v))68 return dist69 70 adj = [[] for _ in xrange(n)]71 for u, v, w in edges:72 adj[u].append((v, w))73 adj[v].append((u, w))74 dist1 = dijkstra(0)75 dist2 = dijkstra(n-1)76 return min(dist1[i]+dist2[j] for u, v, _ in edges for i, j in ((u, v), (v, u)))77