Connect n ropes with minimum cost | Python3 program to connect n ropes with minimum cost ; Create a priority queue out of the given list ; Initializ result ; While size of priority queue is more than 1 ; Extract shortest two ropes from arr ; Connect the ropes : update result and insert the new rope to arr ; Driver code
import heapq NEW_LINE def minCost ( arr , n ) : NEW_LINE INDENT heapq . heapify ( arr ) NEW_LINE res = 0 NEW_LINE while ( len ( arr ) > 1 ) : NEW_LINE INDENT first = heapq . heappop ( arr ) NEW_LINE second = heapq . heappop ( arr ) NEW_LINE res += first + second NEW_LINE heapq . heappush ( arr , first + second ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT lengths = [ 4 , 3 , 2 , 6 ] NEW_LINE size = len ( lengths ) NEW_LINE print ( " Total ▁ cost ▁ for ▁ connecting ▁ ropes ▁ is ▁ " + str ( minCost ( lengths , size ) ) ) NEW_LINE DEDENT