fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long ll;
  5.  
  6. long getMinimumCost(vector<int> cost, int minWeight) {
  7. int n = cost.size();
  8.  
  9. // (cost per weight, weight, cost)
  10. vector<tuple<double, int, int>> items;
  11.  
  12. long long temp = 1ll;
  13.  
  14. for (int i = 0; i < n; i++) {
  15. double efficiency = (double)cost[i] / temp; // i+1 is the weight
  16. items.push_back({efficiency, temp, cost[i]});
  17. temp *= 2ll;
  18. }
  19.  
  20. // Sort by efficiency (smallest first)
  21. sort(items.begin(), items.end());
  22.  
  23. ll totalCost = 0;
  24. int weightAchieved = 0;
  25.  
  26. ll ans = LLONG_MAX;
  27.  
  28.  
  29. for (auto [eff, weight, cst] : items) {
  30. if (weightAchieved >= minWeight) break;
  31.  
  32. // How many units needed?
  33. int needed = (minWeight - weightAchieved + weight - 1) / weight; // ceil
  34.  
  35. totalCost += (ll)needed * cst;
  36. weightAchieved += (ll)needed * weight;
  37.  
  38. ans = min(ans, totalCost);
  39.  
  40. if (weightAchieved == minWeight) break;
  41.  
  42. totalCost -= cst;
  43. weightAchieved -= weight;
  44. }
  45.  
  46. return ans;
  47. }
  48.  
  49. int main() {
  50. int n = 5;
  51. vector<int> cost = {2, 5, 7, 11, 25};
  52. int minWeight = 26;
  53.  
  54. cout << getMinimumCost(cost, minWeight) << endl;
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
37