fork download
  1. //Fractional Knapsack
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. struct Item {
  6. int value, weight;
  7. };
  8.  
  9. bool cmp(Item a, Item b) {
  10. return (double)a.value/a.weight > (double)b.value/b.weight;
  11. }
  12.  
  13. int main() {
  14. vector<Item> arr = {{60,10},{100,20},{120,30}};
  15. int W = 50;
  16.  
  17. sort(arr.begin(), arr.end(), cmp);
  18.  
  19. double total = 0;
  20.  
  21. for (int i = 0; i < arr.size(); i++) {
  22. if (W >= arr[i].weight) {
  23. W -= arr[i].weight;
  24. total += arr[i].value;
  25. } else {
  26. total += (double)arr[i].value * W / arr[i].weight;
  27. break;
  28. }
  29. }
  30.  
  31. cout << "Maximum value: " << total << endl;
  32. }
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
Maximum value: 240