Advertisement
lichenran1234

numMinSpanTrees

Apr 13th, 2021
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. from Queue import PriorityQueue
  2.  
  3. def peekQueue(queue):
  4.     result = queue.get()
  5.     queue.put(result)
  6.     return result
  7.  
  8. def numMinSpanningTrees(edges):
  9.     if edges is None or not edges:
  10.         return 0
  11.    
  12.     vertex_set = set()
  13.    
  14.     pq = PriorityQueue()
  15.     for v1, v2, w in edges:
  16.         pq.put((w, v1, v2))
  17.         vertex_set.add(v1)
  18.         vertex_set.add(v2)
  19.    
  20.     tree_set = range(len(vertex_set))
  21.    
  22.     def findRoot(v, tree_set):
  23.         root = v
  24.         while tree_set[root] != root:
  25.             root = tree_set[root]
  26.         return root
  27.    
  28.     def numMst(tree_set, num_trees, queue):
  29.         if queue.empty():
  30.             if num_trees == 1:
  31.                 print temp_result
  32.                 return 1
  33.             return 0
  34.        
  35.         next_edges = [queue.get()]
  36.         if not queue.empty():
  37.             while not queue.empty() and peekQueue(queue)[0] == next_edges[0][0]:
  38.                 next_edges.append(queue.get())
  39.        
  40.         result = 0
  41.         found_valid_edge = False
  42.         for i in range(len(next_edges)):
  43.             w, v1, v2 = next_edges[i]
  44.             v1_root = findRoot(v1, tree_set)
  45.             v2_root = findRoot(v2, tree_set)
  46.             if v1_root != v2_root:
  47.                 found_valid_edge = True
  48.                 if num_trees == 2:
  49.                     result += 1
  50.                 else:
  51.                     tree_set[v1_root] = v2_root
  52.                     for j in range(i + 1, len(next_edges)):
  53.                         queue.put(next_edges[j])
  54.                     result += numMst(tree_set, num_trees - 1, queue)
  55.                     for j in range(i + 1, len(next_edges)):
  56.                         queue.get()
  57.                     tree_set[v1_root] = v1_root
  58.        
  59.         if not found_valid_edge:
  60.             result = numMst(tree_set, num_trees, queue)
  61.         for edge in next_edges:
  62.             queue.put(edge)
  63.         return result
  64.    
  65.     return numMst(tree_set, len(tree_set), pq)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement