算法:完全背包问题
时间复杂度:$O(n \times m)$
背包问题用于求解价值最大以及方案数是比较多的,注意区别和理解模板并记下来。
因为背包问题的常数比较小,所以即使是 $O(m \times n)$ 也是可以过的。
C++ 代码
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 10010;
int n, m;
LL f[N];
int main()
{
cin >> m >> n;
f[0] = 0;
for (int i = 0; i < n; ++i) {
int w, v;
cin >> w >> v;
for (int j = v; j <= m; ++j) {
f[j] = max(f[j], f[j - v] + w);
}
}
cout << f[m] << endl;
return 0;
}