fork download
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. class Knapsack{
  7. public:
  8. long long maximumValue(vector<int>& weights, vector<int>& values, int n, int capacity) {
  9. long long total_value = 0;
  10. for(int v : values) total_value += v;
  11.  
  12. vector<long long> dp(total_value+1, LLONG_MAX);
  13. dp[0] = 0;
  14.  
  15. for(int i = 0; i < n; ++i) {
  16. for(int v = total_value; v >= values[i]; --v) {
  17. if(dp[v - values[i]] != LLONG_MAX) {
  18. dp[v] = min(
  19. dp[v],
  20. weights[i] + dp[v - values[i]]
  21. );
  22. }
  23. }
  24. }
  25.  
  26. int res = 0;
  27. for(int v = total_value; v > 0; --v) {
  28. if(dp[v] <= capacity) {
  29. res = v;
  30. break;
  31. }
  32. }
  33. return res;
  34. }
  35. };
  36.  
  37.  
  38. int main() {
  39. int n, c;
  40. cin >> n >> c;
  41. vector<int> weights(n), values(n);
  42.  
  43. for(int i = 0; i < n; ++i) {
  44. cin >> weights[i] >> values[i];
  45. }
  46.  
  47. Knapsack* obj = new Knapsack();
  48. cout << obj->maximumValue(weights, values, n, c);
  49. return 0;
  50. }
Success #stdin #stdout 0.01s 5312KB
stdin
6 15
6 5
5 6
6 4
6 6
3 5
7 2
stdout
17