|
| 1 | +<h1 align="center">Minimum - Cost of - Ropes</h1> |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +**Problem URL :** [Minimum Cost of Ropes](https://www.geeksforgeeks.org/problems/minimum-cost-of-ropes-1587115620/1) |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | +### Problem Explanation |
| 10 | +You are given a collection of ropes with different lengths. The task is to connect these ropes into a single rope. Each time you connect two ropes, the cost of the operation is equal to the sum of the lengths of the two ropes. You need to minimize the total cost of connecting all the ropes. |
| 11 | + |
| 12 | +**Example:** |
| 13 | +- Suppose you have ropes with lengths `{4, 3, 2, 6}`. |
| 14 | + |
| 15 | + - **Step 1**: Select the two smallest ropes (lengths 2 and 3). The cost of connecting them is `2 + 3 = 5`. |
| 16 | + - **Step 2**: The new rope formed has a length of `5`. Now, the ropes are `{4, 5, 6}`. |
| 17 | + - **Step 3**: Select the two smallest ropes (lengths 4 and 5). The cost of connecting them is `4 + 5 = 9`. |
| 18 | + - **Step 4**: The new rope formed has a length of `9`. Now, the ropes are `{6, 9}`. |
| 19 | + - **Step 5**: Select the two smallest ropes (lengths 6 and 9). The cost of connecting them is `6 + 9 = 15`. |
| 20 | + |
| 21 | + - **Total cost**: `5 + 9 + 15 = 29`. |
| 22 | + |
| 23 | +Thus, the minimum cost of connecting all the ropes is `29`. |
| 24 | + |
| 25 | +### Greedy Algorithm Approach |
| 26 | + |
| 27 | +The greedy approach works well for this problem because at each step, you are always making the locally optimal choice, i.e., selecting the two smallest ropes to connect, which ensures the minimum cost in the long run. |
| 28 | + |
| 29 | +#### Steps: |
| 30 | +1. **Sort the ropes** (or use a priority queue/min-heap to easily extract the smallest ropes). |
| 31 | +2. **Extract the two smallest ropes**. |
| 32 | +3. **Connect the ropes**, which adds to the total cost. |
| 33 | +4. **Push the new combined rope** back into the heap or list. |
| 34 | +5. **Repeat the process** until only one rope remains. |
| 35 | + |
| 36 | +### Example Walkthrough of the Greedy Algorithm |
| 37 | + |
| 38 | +For the array `{4, 3, 2, 6}`: |
| 39 | +1. **Initialization**: Use a priority queue (min-heap) to automatically sort the ropes. |
| 40 | +2. After pushing all the ropes into the heap, we get `{2, 3, 4, 6}`. |
| 41 | +3. **First iteration**: |
| 42 | + - Extract `2` and `3` (the two smallest ropes). |
| 43 | + - Cost to combine them: `2 + 3 = 5`. |
| 44 | + - New rope of length `5` is pushed back into the heap, so the heap becomes `{4, 5, 6}`. |
| 45 | +4. **Second iteration**: |
| 46 | + - Extract `4` and `5`. |
| 47 | + - Cost to combine them: `4 + 5 = 9`. |
| 48 | + - New rope of length `9` is pushed back into the heap, so the heap becomes `{6, 9}`. |
| 49 | +5. **Final iteration**: |
| 50 | + - Extract `6` and `9`. |
| 51 | + - Cost to combine them: `6 + 9 = 15`. |
| 52 | + - Total cost is `5 + 9 + 15 = 29`. |
| 53 | + |
| 54 | +## Problem Solution |
| 55 | +```cpp |
| 56 | +class Solution { |
| 57 | + public: |
| 58 | + // Function to return the minimum cost of connecting the ropes. |
| 59 | + int minCost(vector<int>& arr) { |
| 60 | + // Create a min-heap (priority queue) to store the rope lengths |
| 61 | + priority_queue<int, vector<int>, greater<int>> pq; |
| 62 | + |
| 63 | + // Push all the rope lengths into the priority queue |
| 64 | + for(int i = 0; i < arr.size(); i++) pq.push(arr[i]); |
| 65 | + |
| 66 | + // Variable to store the total cost of connecting the ropes |
| 67 | + int totalCost = 0; |
| 68 | + |
| 69 | + // Continue combining the two smallest ropes until only one rope remains |
| 70 | + while(pq.size() > 1){ |
| 71 | + // Get the two smallest ropes from the heap |
| 72 | + int mini_1 = pq.top(); |
| 73 | + pq.pop(); |
| 74 | + |
| 75 | + int mini_2 = pq.top(); |
| 76 | + pq.pop(); |
| 77 | + |
| 78 | + // Calculate the cost of connecting the two smallest ropes |
| 79 | + int total = mini_1 + mini_2; |
| 80 | + |
| 81 | + // Add this cost to the total cost |
| 82 | + totalCost += total; |
| 83 | + |
| 84 | + // Push the new combined rope (total length) back into the priority queue |
| 85 | + pq.push(total); |
| 86 | + } |
| 87 | + |
| 88 | + // Return the total cost of connecting all ropes |
| 89 | + return totalCost; |
| 90 | + } |
| 91 | +}; |
| 92 | +``` |
| 93 | +
|
| 94 | +## Problem Solution Explanation |
| 95 | +
|
| 96 | +#### 1. **Class Definition**: |
| 97 | +```cpp |
| 98 | +class Solution { |
| 99 | +``` |
| 100 | +- The class `Solution` is defined to encapsulate the logic for the problem of finding the minimum cost of connecting ropes. |
| 101 | + |
| 102 | +#### 2. **Function Definition**: |
| 103 | +```cpp |
| 104 | +int minCost(vector<int>& arr) { |
| 105 | +``` |
| 106 | +- The function `minCost` takes a reference to a vector of integers `arr`, where each integer represents the length of a rope. The function returns the minimum cost of connecting all the ropes. |
| 107 | +
|
| 108 | +#### 3. **Priority Queue Definition**: |
| 109 | +```cpp |
| 110 | +priority_queue<int, vector<int>, greater<int>> pq; |
| 111 | +``` |
| 112 | +- Here, a **min-heap** (implemented using a priority queue) is defined. The min-heap will store the rope lengths and allow us to efficiently extract the two smallest lengths. |
| 113 | +- The type `greater<int>` specifies that the priority queue will give priority to the smallest element (i.e., it behaves like a min-heap). |
| 114 | + |
| 115 | +#### 4. **Inserting Rope Lengths into the Priority Queue**: |
| 116 | +```cpp |
| 117 | +for(int i = 0; i < arr.size(); i++) pq.push(arr[i]); |
| 118 | +``` |
| 119 | +- This loop iterates over all the elements in the vector `arr`, and each rope length is pushed into the priority queue. |
| 120 | +- For example, if `arr = [8, 4, 6, 12]`, the priority queue after this loop will be `pq = {4, 6, 8, 12}`. |
| 121 | + |
| 122 | +#### 5. **Initialize Total Cost**: |
| 123 | +```cpp |
| 124 | +int totalCost = 0; |
| 125 | +``` |
| 126 | +- We initialize the `totalCost` variable to 0. This variable will keep track of the total cost of combining the ropes. |
| 127 | + |
| 128 | +#### 6. **While Loop to Combine Ropes**: |
| 129 | +```cpp |
| 130 | +while(pq.size() > 1){ |
| 131 | +``` |
| 132 | +- The `while` loop runs as long as there is more than one rope in the priority queue. This is because, at the end, we want only one rope left, which represents the final connected rope. |
| 133 | +
|
| 134 | +#### 7. **Extract the Two Smallest Ropes**: |
| 135 | +```cpp |
| 136 | +int mini_1 = pq.top(); |
| 137 | +pq.pop(); |
| 138 | +
|
| 139 | +int mini_2 = pq.top(); |
| 140 | +pq.pop(); |
| 141 | +``` |
| 142 | +- `pq.top()` gives the smallest element in the heap, and `pq.pop()` removes the smallest element from the heap. |
| 143 | +- The two smallest ropes (`mini_1` and `mini_2`) are extracted here. |
| 144 | +- For example, if the heap is `pq = {4, 6, 8, 12}`, after this code, `mini_1 = 4` and `mini_2 = 6`. |
| 145 | + |
| 146 | +#### 8. **Calculate the Cost of Connecting the Two Smallest Ropes**: |
| 147 | +```cpp |
| 148 | +int total = mini_1 + mini_2; |
| 149 | +``` |
| 150 | +- We calculate the cost of connecting the two smallest ropes by adding their lengths together (`total = mini_1 + mini_2`). |
| 151 | + |
| 152 | +#### 9. **Add the Cost to the Total Cost**: |
| 153 | +```cpp |
| 154 | +totalCost += total; |
| 155 | +``` |
| 156 | +- The calculated `total` is added to the `totalCost`, which accumulates the cost of connecting all ropes. |
| 157 | + |
| 158 | +#### 10. **Push the New Combined Rope Back into the Priority Queue**: |
| 159 | +```cpp |
| 160 | +pq.push(total); |
| 161 | +``` |
| 162 | +- The newly combined rope (with length `total`) is pushed back into the priority queue. |
| 163 | + |
| 164 | +#### 11. **Repeat the Process Until One Rope Remains**: |
| 165 | +- This loop continues until only one rope remains in the priority queue. |
| 166 | + |
| 167 | +#### 12. **Return the Total Cost**: |
| 168 | +```cpp |
| 169 | +return totalCost; |
| 170 | +``` |
| 171 | +- Finally, after all ropes are connected, we return the `totalCost`, which is the minimum cost to connect all the ropes. |
| 172 | + |
| 173 | +### Example Walkthrough: |
| 174 | + |
| 175 | +Let's consider an example input `arr = [8, 4, 6, 12]`. |
| 176 | + |
| 177 | +1. Initially, the priority queue will be: `{4, 6, 8, 12}`. |
| 178 | + |
| 179 | +2. **First Iteration:** |
| 180 | + - Extract the two smallest ropes: `mini_1 = 4`, `mini_2 = 6`. |
| 181 | + - The cost to connect these ropes is `4 + 6 = 10`. |
| 182 | + - Add this cost to the total cost: `totalCost = 0 + 10 = 10`. |
| 183 | + - Push the new rope of length `10` into the priority queue. The new queue is: `{8, 10, 12}`. |
| 184 | + |
| 185 | +3. **Second Iteration:** |
| 186 | + - Extract the two smallest ropes: `mini_1 = 8`, `mini_2 = 10`. |
| 187 | + - The cost to connect these ropes is `8 + 10 = 18`. |
| 188 | + - Add this cost to the total cost: `totalCost = 10 + 18 = 28`. |
| 189 | + - Push the new rope of length `18` into the priority queue. The new queue is: `{12, 18}`. |
| 190 | + |
| 191 | +4. **Third Iteration:** |
| 192 | + - Extract the two smallest ropes: `mini_1 = 12`, `mini_2 = 18`. |
| 193 | + - The cost to connect these ropes is `12 + 18 = 30`. |
| 194 | + - Add this cost to the total cost: `totalCost = 28 + 30 = 58`. |
| 195 | + - Now, only one rope remains in the queue, and the loop ends. |
| 196 | + |
| 197 | +5. The final `totalCost` is `58`, which is returned as the minimum cost of connecting the ropes. |
| 198 | + |
| 199 | +### Time Complexity: |
| 200 | + |
| 201 | +1. **Inserting into the Priority Queue**: |
| 202 | + Inserting `n` elements into the priority queue takes `O(log n)` time for each element, so inserting all elements will take `O(n log n)` time. |
| 203 | + |
| 204 | +2. **Combining the Ropes**: |
| 205 | + In each iteration, we extract two ropes and insert the combined rope back into the queue. Each extract and insert operation takes `O(log n)` time. Since there are `n - 1` iterations (as we combine the ropes until one remains), the total time for combining the ropes is `O(n log n)`. |
| 206 | + |
| 207 | +3. **Overall Time Complexity**: |
| 208 | + The overall time complexity is `O(n log n)`. |
| 209 | + |
| 210 | +### Space Complexity: |
| 211 | + |
| 212 | +- The primary space usage is by the priority queue, which stores all `n` rope lengths at once. |
| 213 | +- The space complexity is therefore `O(n)` due to the priority queue. |
| 214 | + |
| 215 | +### Summary: |
| 216 | + |
| 217 | +- The **time complexity** of the solution is `O(n log n)` because each insert and extract operation in the priority queue takes `O(log n)` time, and there are `n` operations. |
| 218 | +- The **space complexity** is `O(n)` because we store all `n` rope lengths in the priority queue. |
| 219 | + |
| 220 | +This approach efficiently minimizes the cost of connecting ropes by always combining the smallest available ropes first, making it a typical greedy algorithm. |
| 221 | + |
0 commit comments