Advertisement
goodwish

629. Minimum Spanning Tree - Prim

Nov 15th, 2019
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. way 2. Min heap, Prim 方法, 从某点出发. O(V log V)
  2. 思路:
  3. 从每一个顶点开始, 把它的所有边加进 min heap. heap node: (weight, city1, city2, vertex),
  4. 循环, while h:
  5. - 弹出最小边的另一个顶点,
  6. - 跳过 used 顶点,
  7. - 最短边加进结果集,
  8.  -- 子循环, 把此顶点的所有边加进 min heap, 跳过 used 顶点,
  9. - 直到加满树的边数, if len(res) == len(V) - 1: 边数等于顶点数减一, 是一棵树.
  10.  
  11. Note, 此题需要保留 city1, city2 的顺序, 并且 heap 按照 (cost, city1, city2) 排序,
  12.  
  13. '''
  14. Definition for a Connection
  15. class Connection:
  16.  
  17.    def __init__(self, city1, city2, cost):
  18.        self.city1, self.city2, self.cost = city1, city2, cost
  19. '''
  20. import heapq, collections
  21. class Solution:
  22.     def lowestCost(self, C):
  23.         # init
  24.         graph = collections.defaultdict(list)
  25.         for c in C:
  26.             graph[c.city1].append((c.city2, c))
  27.             graph[c.city2].append((c.city1, c))
  28.         h, res = [], []
  29.         n = len(graph)
  30.         # used = set([C[0].city1])
  31.         used = set()
  32.         heapq.heappush(h, (-1, "", "", C[0].city1))
  33.        
  34.         while h: # and len(res) < n - 1:
  35.             cost, c1, c2, u = heapq.heappop(h)
  36.             if u in used:
  37.                 continue
  38.             if c1 != "":
  39.                 res.append(Connection(c1, c2, cost))
  40.             used.add(u)
  41.             # print(u, c1, c2, cost)
  42.             for v, c in graph[u]:
  43.                 if v in used:
  44.                     continue
  45.                 heapq.heappush(h, (c.cost, c.city1, c.city2, v))
  46.         if len(res) != n - 1:
  47.             return []
  48.         res.sort(key = lambda x: (x.cost, x.city1, x.city2))
  49.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement