
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Connect n ropes with minimum cost\n
- Program to find minimum cost to connect all points in Python
- Program to find minimum cost to connect each Cartesian coordinates in C++
- Minimum Cost to Merge Stones in C++
- Minimum Cost to Hire K Workers in C++
- Minimum Cost Polygon Triangulation
- Minimum Cost For Tickets in C++
- Minimum Cost To Make Two Strings Identical in C++
- Find minimum cost to buy all books in C++
- Program to find minimum cost to merge stones in Python
- Minimum Cost to make two Numeric Strings Identical in C++
- Minimum Cost to cut a board into squares in Python
- Minimum Cost to cut a board into squares in C++
- Program to find minimum cost for painting houses in Python
- Program to find minimum cost to cut a stick in Python

Advertisements