fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. // Function to return the minimum cost of connecting the ropes.
  7. int minCost(vector<int>& arr) {
  8. int totalCost = 0;
  9. while (arr.size() > 1) {
  10. sort(arr.begin(), arr.end());
  11. int first = arr[0];
  12. int second = arr[1];
  13. arr.erase(arr.begin());
  14. arr.erase(arr.begin());
  15. int cost = first + second;
  16. totalCost += cost;
  17. arr.push_back(cost);
  18. }
  19. return totalCost;
  20. }
  21.  
  22. int main() {
  23. vector<int> ropes = {4, 6,8, 1, 56, 43, 10};
  24. cout << minCost(ropes) << endl;
  25. return 0;
  26. }
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
263