Connect n ropes with minimum cost | C # program to connect n ropes with minimum cost ; Create a priority queue ; Initialize result ; While size of priority queue is more than 1 ; Extract shortest two ropes from pq ; Connect the ropes : update result and insert the new rope to pq ; Driver program to test above function
using System ; using System . Collections . Generic ; public class ConnectRopes { static int minCost ( int [ ] arr , int n ) { List < int > pq = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { pq . Add ( arr [ i ] ) ; } int res = 0 ; while ( pq . Count > 1 ) { pq . Sort ( ) ; int first = pq [ 0 ] ; int second = pq [ 1 ] ; pq . RemoveRange ( 0 , 2 ) ; res += first + second ; pq . Add ( first + second ) ; } return res ; } public static void Main ( String [ ] args ) { int [ ] len = { 4 , 3 , 2 , 6 } ; int size = len . Length ; Console . WriteLine ( " Total ▁ cost ▁ for ▁ connecting " + " ▁ ropes ▁ is ▁ " + minCost ( len , size ) ) ; } }