
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Cost to Connect Sticks in C++
Suppose we have some sticks with positive integer lengths. We can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. This will be performed until there is one stick remaining. We have to find the minimum cost of connecting all the given sticks into one stick in this way. So if the stack is [2,4,3], then the output will be 14.
To solve this, we will follow these steps −
- Define a max heap priority queue pq
- insert all elements of s into pq
- ans := 0
- while pq has more than one element
- temp := top of the queue, delete top from pq
- temp := temp + top element of pq, and delete from pq
- ans := ans + temp
- insert temp into pq
- return ans
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int connectSticks(vector<int>& s) { priority_queue <int, vector<int>, greater<int> > pq; for(int i =0;i<s.size();i++)pq.push(s[i]); int ans = 0; while(pq.size()>1){ int temp = pq.top(); pq.pop(); temp += pq.top(); pq.pop(); ans+=temp; pq.push(temp); } return ans; } }; main(){ vector<int> v = {2,4,3}; Solution ob; cout <<ob.connectSticks(v); }
Input
[2,4,3]
Output
14
Advertisements