Title description]
There are n n items, each item has a weight and a value. However, the number of each item is unlimited. At the same time, there is a backpack with a maximum load of M M. Now select several items from n n items (the same item can be selected multiple times) so that the sum of their weights is less than or equal to M M, and the sum of value is the largest.
【Enter】
The first line: two integers, M M (backpack capacity, M ≤ 200 M ≤ 200 ) and N N (number of items, N ≤ 30 N ≤ 30 );
Line 2 .. N + 1 2. Line N + 1 : Two integers W i , C i Wi, Ci in each line , indicating the weight and value of each item.
【Output】
Only one line, one number, represents the maximum total value.
【Input example】
10 4 2 1 3 3 4 5 7 9
[Sample output]
max = 12
idea: add a quantity on the basis of 01 backpack, the value range is between 0 and j / v [i], because it cannot exceed the current volume
code:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
int m, n;
int f [21] [310], w [ 31], v [31];
int main ()
{
cin >> m >> n;
for (int i = 1; i <= n; i ++)
cin >> v [i] >> w [i];
for (int i = 1; i <= n; i ++)
for (int j = 0; j <= m; j ++)
for (int k = 0; k * v [i] <= j; k ++)
f [i] [j] = max (f [i] [j], f [i-1] [jk * v [i]] + k * w [i]); // Using the two-dimensional method, is to add one Layer loop, because when k is 0, it is equivalent to not taking it, so there is no need to classify it again. As for whether i is a type or a number here, I am also a bit confused. If the number should be -k, why is it -1? So it should be kind.
cout << "max =" << f [n] [m];
return 0;
}