Solution: Connecting n Pipes with Minimum Cost
Explore methods to connect pipes with minimal cost using various greedy algorithm strategies. Understand brute force, sorting, min heap, and priority queue approaches, and analyze their time complexities to solve this optimization problem efficiently using C++.
Solution #1: Brute Force
In the brute force method, we try all combinations of pipes possible (line34) in order to find the minimum possible cost.
Time Complexity
The time Complexity is because we find all possible combinations and out of that choose the one where we can find the minimum cost.
Solution #2: Sorting
We optimize the solution by sorting the array and choosing the minimum pipes first.
If you look at the animation present in the previous lesson, you will notice that the lengths of the pipes which are picked first are included iteratively (i.e. each time); therefore, we want them to be as small as possible. Now, let’s be greedy!! Grab and connect the smallest two pipes first and recur for remaining pipes.
We always try and put the smallest pipes down the tree so that they can be repeated multiple times, otherwise the longer pipes will be added multiple times.
Time Complexity:
The time complexity for this solution is , because of the optimized built-in C++ sort function.
Solution #3: Using MinHeap
Pseudocode
minCost(pipes, n)
Let there be n pipes of lengths stored in an array
create a minHeap
insert lengths into the min heap.
while ( number of elements in min heap != 1)
Extract the minimum and second minimum from min heap
Add the two extracted values
Insert to the min-heap.
Maintain variable for total cost
Return the value of the total cost.
Time Complexity
The time complexity of the algorithm is only if we use a sorting algorithm.
Note: Heap operations that we have used in our solution like insert and extract take time.
Solution #4: Using Priority Queues
We use STL Priority Queue for our solution. If you want to get an idea of how they are used, have a look at the appendix.
This solution uses a C++ data structure priority_queue. Priority queues are a type of container adaptor.
Here, highlighted in the above code (line 2), the syntax of a priority queue is important to note.
Syntax used for priority queues used.
priority_queue <int, vector <int> , greater <int> > myPriorityQueue(pipes, pipes + n);
We use the greater keyword to use priority queue like a min heap where the first element is the smallest and so on.
In
Priority Queues, the first element is always the greatest or the smallest (depending on our choice) of the elements it contains.
This context is very similar to a heap just like we have used in our first solution, where elements can be inserted at any moment, and only the min heap element can be retrieved (the one at the top in the priority queue).
Time Complexity
The time complexity of the algorithm will remain the same because priority queues use heap implementation and therefore sorting takes time.