版本一: 时间复杂度$O(nm^2)$, 所以TLE
#include<iostream>
using namespace std;
const int N = 1010;
int n, m;
int f[N][N];
int v[N], w[N];
int main() {
cin >> n >> m;
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][j - v[i] * k] + w[i] * k);
}
}
}
cout << f[n][m] << endl;
}
版本二 一维优化
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
int f[N];
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> v[i] >> w[i];
for (int i = 1; i <= n; i++)
for (int j = v[i]; j <= m; j++)
f[j] = max(f[j], f[j - v[i]] + w[i]);
cout << f[m] << endl;
return 0;
}
01 背包问题 优化成一维 j维度从大到小
枚举
f[i][j]=max(f[i][j], f[i-1][j-v[i]+w[i]);
完全背包问题 优化成一维 j维度从小到大
枚举
f[i][j]=max(f[i][j], f[i][j-v[i]+w[i]);
谢谢