解题思路
代码
原始做法 O(N^3)
#include <iostream>
using namespace std;
const int N = 1010;
int v[N], w[N], f[N][N];
int main() {
int n, m;
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 = 1; j <= m; j++) {
for (int k = 0; j >= k * v[i]; k++)
f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i]);
}
}
cout << f[n][m] << endl;
return 0;
}
优化时间 O(N^2)
#include <iostream>
using namespace std;
const int N = 1010;
int v[N], w[N], f[N][N];
int main() {
int n, m;
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 = 1; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= v[i]) f[i][j] = max(f[i - 1][j], f[i][j - v[i]] + w[i]);
}
}
cout << f[n][m] << endl;
return 0;
}
优化空间
#include <iostream>
using namespace std;
const int N = 1010;
int v[N], w[N], f[N];
int main() {
int n, m;
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 - v[i]] + w[i], f[j]);
}
}
cout << f[m] << endl;
return 0;
}