Kruskal (MST): Really Special Subtree

  • + 1 comment

    MY PYTHON AC SOLUTION

    from collections import defaultdict 
    
    
    class Graph:
          
          def __init__(self, vertices):
                self. parent = defaultdict(int)
                self. rank = defaultdict(int) 
                self. V = vertices 
                self. graph = [] #we will append (u, v, w)
                
                
          def addEdge(self, u, v, w):
                self. graph. append([u, v, w])
          
          
          def find(self, v):
                if self. parent[v] == 0 :
                      return v 
                
                temp = self. find(self. parent[v])
                self. parent[v] = temp 
                
                return temp 
                
          def union(self, x, y):
                x_set = self. find(x) 
                y_set = self. find(y) 
                
                
                if self. rank[x_set] == self. rank[y_set]:
                      self. parent[x_set] = y_set 
                      self. rank[y_set] += 1  
                
                elif self. rank[x_set] < self. rank[y_set]: 
                      
                      self. parent[x_set] = y_set 
                
                else:
                      self. parent[y_set] = x_set 
                      
          def kruskal_Algo(self):
                self. graph = sorted(self. graph, key = lambda x: x[2] )
                            
                edges = 0 
                answer  = 0 
                for i in self. graph:
                      if edges == self. V - 1: 
                            break 
                      
                      u, v, w = i 
                      x = self. find(u)
                      y = self. find(v) 
                      
                      if x != y: 
                            edges += 1 
                            self. union(x, y)
                            answer += w 
                      
                print(answer)
                
    def main():
          v, e = map(int, input(). split() )
          g = Graph(v)
    
          for i in range(e):
            u, v, w = map(int, input(). split() )
            g.addEdge(u, v, w)
    
          g. kruskal_Algo() 
    
    
    if __name__ == '__main__':
          main()