Advertisement
Guest User

Algoritmo MST(Gasoduto)

a guest
Nov 20th, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1.  
  2. import sys  # Library for INT_MAX
  3.  
  4. class Graph():
  5.  
  6.     def __init__(self, vertices):
  7.         self.V = vertices
  8.         self.graph = [[0 for column in range(vertices)]
  9.                       for row in range(vertices)]
  10.  
  11.     # A utility function to print the constructed MST stored in parent[]
  12.     def printMST(self, parent):
  13.         print "Edge \tWeight"
  14.         for i in range(1,self.V):
  15.             print parent[i],"-",i,"\t",self.graph[i][ parent[i] ]
  16.  
  17.     def minKey(self, key, mstSet):
  18.         min = sys.maxint
  19.  
  20.         for v in range(self.V):
  21.             if key[v] < min and mstSet[v] == False:
  22.                 min = key[v]
  23.                 min_index = v
  24.  
  25.         return min_index
  26.     def primMST(self):
  27.         key = [sys.maxint] * self.V
  28.         parent = [None] * self.V # Array to store constructed MST
  29.         key[0] = 0   # Make key 0 so that this vertex is picked as first vertex
  30.         mstSet = [False] * self.V
  31.  
  32.         parent[0] = -1  # First node is always the root of
  33.  
  34.         for cout in range(self.V):
  35.             u = self.minKey(key, mstSet)
  36.  
  37.             # Put the minimum distance vertex in the shortest path tree
  38.             mstSet[u] = True
  39.  
  40.             for v in range(self.V):
  41.                 if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
  42.                         key[v] = self.graph[u][v]
  43.                         parent[v] = u
  44.  
  45.         self.printMST(parent)
  46.  
  47. g  = Graph(10)
  48. g.graph = [
  49.     [0,4230,4700,4716,4690, 4674, 5070,4880,4280,3880],
  50.     [4230,0,534,682,950, 780, 1110,1190,2700,3100],
  51.     [4700,534,0,190,544, 288, 787,1092,2600,3000],
  52.     [4716,682,190,0,378, 122, 620,926,2436,2830],
  53.     [4690,950,544,378,0, 256, 280,580,2100,2436],
  54.     [4674,780,288,122,256, 0, 500,810,2320,2710],
  55.     [5070,1110,787,620,280, 500, 0,330,1840,2200],
  56.     [4880,1190,1092,926,580, 810, 330,0,1650,1985],
  57.     [4280,2700,2600,2436,2100, 2320, 1840,1650,0,450],
  58.     [3880,3100,3000,2830,2436, 2710, 2200,1985,450,0]
  59.     ]
  60.  
  61. g.primMST();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement