Minimum Cost of ropes | Practice | GeeksforGeeks

There are given N ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost.
Example 1:
Input:
n = 4
arr[] = {4, 3, 2, 6}
Output: 
29
Explanation:
For example if we are given 4
ropes of lengths 4, 3, 2 and 6. We can
connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3.
Now we have three ropes of lengths 4, 6
and 5.
2) Now connect ropes of lengths 4 and 5.
Now we have two ropes of lengths 6 and 9.
3) Finally connect the two ropes and all
ropes have connected.
Total cost for connecting all ropes is 5
+ 9 + 15 = 29. This is the optimized cost
for connecting ropes. Other ways of
connecting ropes would always have same
or more cost. For example, if we connect
4 and 6 first (we get three strings of 3,
2 and 10), then connect 10 and 3 (we get
two strings of 13 and 2). Finally we
connect 13 and 2. Total cost in this way
is 10 + 13 + 15 = 38.
Example 2:
Input:
n = 5
arr[] = {4, 2, 7, 6, 9}
Output: 
62 
Explanation:
First, connect ropes 4 and 2, which makes
the array {6,7,6,9}. Next, add ropes 6 and
6, which results in {12,7,9}. Then, add 7
and 9, which makes the array {12,16}. And
finally add these two which gives {28}.
Hence, the total cost is 6 + 12 + 16 + 
28 = 62.

Your Task:
You don't need to read input or print anything. Your task isto complete the function minCost() which takes 2 arguments and returns the minimum cost.
Expected Time Complexity : O(nlogn)
Expected Auxilliary Space : O(n)
Constraints:
1 ≤ N ≤ 100000
1 ≤ arr[i] ≤ 106
0
himanshibaranwal05129in 9 hours
Can someone tell me why in c# i am getting this error? 
 
prog.cs(46,22): error CS0246: The type or namespace name `PriorityQueue' could not be found. Are you missing an assembly reference?
This is anyways imported from System.Collections.Generic
 
 
public class Solution{  //Function to return the minimum cost of connecting the ropes.   public long minCost(int[] arr, int n) {       var rev = Comparer<long>.Create((x, y) => y.CompareTo(x));       var pQ = new PriorityQueue<long, long>(rev);              for(int i=0; i<arr.Length; i++){           pQ.Enqueue(arr[i], arr[i]);       }              int ans = 0;              while(pQ.Count!=1){           long min1 = pQ.Dequeue();           long min2 = pQ.Dequeue();           pQ.Enqueue(min1+min2 , min1+min2);       }              return ans;   }   }
0
koulikmaity5 days ago
long long minCost(long long arr[], long long n) {              // create min-heap       priority_queue<long long, vector<long long>, greater<long long> >pq;              for(int i=0; i<n; i++)       {           pq.push(arr[i]);       }              long long cost = 0;       while(pq.size() > 1)       {           long long a = pq.top();           pq.pop();                      long long b = pq.top();           pq.pop();                      long long sum = a+b;           cost += sum;                      pq.push(sum);       }       return cost;   }
0
amarrajsmart1971 week ago
 
//*simply use min heap*//
   priority_queue<long long,vector<long long>,greater<long long>> pq;       for(long long i=0;i<n;i++)       {           pq.push(arr[i]);       }       long long sum=0;       while(pq.size()>=2)       {           long long curr=pq.top();           pq.pop();           curr+=pq.top();           pq.pop();           pq.push(curr);           sum+=curr;       }       return sum;   }
0
pavsevaibhav1 week ago
Simple idea is to use PriorityQueue.
First store all the array elements to priorityqueue. then traverse through the priorityqueue until its size is not equal to 1.
while : we pop first to elements from queue and add its sum to totalCost as well as back to queue also.
 
long minCost(long arr[], int n) 
    {
        // your code here
        PriorityQueue<Long> queue = new PriorityQueue<>();
        for(long ele : arr) {
            queue.add(ele);
        }
        long totalCost = 0;
        while(queue.size() > 1) {
            long rope1 = queue.poll();
            long rope2 = queue.poll();
            totalCost += rope1 + rope2;
            queue.add(rope1 + rope2);
        }
        return totalCost;
    }
Complexity : 
Time : O(n*logn)
Space:O(n)
0
bhaskarmaheshwari81 week ago
long long cost=0;                        for(int j=0;j<n-1;j++)        {           // cout<<arr[0]<<endl;            sort(arr,arr+n-j);            for(int i=0;i<n-1;i++)            {                if(i==0)                {                    arr[i]+=arr[i+1];                                        cost+=arr[i];                   // cout<<cost<<endl;                }                else                 {                    arr[i]=arr[i+1];                }            }        }       return cost;
0
harshscode1 week ago
again with the use of priority queue....
 
 long long int sum=0,temp1=0;       priority_queue<long long int,vector<long long int>,greater<long long int>> q;              for(long long int i=0;i<n;i++)       {                     q.push(a[i]);       }             for(int i=0;i<n-1;i++)       {             temp1=q.top();                         q.pop();                         temp1+=q.top();                        q.pop();              q.push(temp1);             sum+=temp1;                                }              return sum;   }
0
18951a04c32 weeks ago
Min Heap in Python
from heapq import heapify, heappush, heappop
class Solution:
    def minCost(self,arr,n):
        heap = []
        heapify(heap)
        for i in range(n):
            heappush(heap,arr[i])
        cost = 0
        while(len(heap)>1):
            cost1 = heappop(heap)
            cost2 = heappop(heap)
            curr_cost = cost1+cost2
            cost+=curr_cost
            heappush(heap,curr_cost)
        return cost
0
hharshit81182 weeks ago
min_heap is created in O(nlogn);
traversing through the heap (n-1) time - 
1- taking two min items at a time
2- adding to the result.
3- adding to min heap pq.
overall time complexity : O(nlogn)
 
 
class Solution{   public:   long long minCost(long long arr[], long long n) {       priority_queue<long long, vector<long long>, greater<long long>> pq;       for(long long i = 0; i< n; i++){           pq.push(arr[i]);       }       long long sum = 0;       for(long long i = 0; i<n-1; i++){           long long curr = pq.top();pq.pop();           curr += pq.top();pq.pop();           pq.push(curr);           sum += curr;       }       return sum;   }};
 
0
jaintanisha20134 weeks ago
C++ solution using minheap:
class Solution
{
    public:
    //Function to return the minimum cost of connecting the ropes.
    long long minCost(long long arr[], long long n) {
        priority_queue<long long,vector<long long>,greater<long long>>pq(arr,arr+n);
        if(n<=1)
        return 0;
        long long ans=0;
        while(pq.size()>=2)
        {
            long long first=pq.top();
            pq.pop();
            long long second=pq.top();
            pq.pop();
            ans=ans+first+second;
            pq.push(first+second);
        }
        return ans;
        // Your code here
    }
};
 
0
987rashita12holkar1 month ago
My code in C++ using Min_HEAP c++ stl priority queue
long long minCost(long long arr[], long long n) {       // Your code here       priority_queue<long long,vector<long long>,greater<long long>>pq(arr,arr+n);       long long ans=0;       if(n==1||n==0)       return 0;       while(!pq.empty())       {           long long a=pq.top();           pq.pop();           long long b=pq.top();           pq.pop();           ans+=(a+b);           if(!pq.empty())           pq.push(a+b);       }       return ans;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.