解题思路
代码
原始做法
#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 - v[i]] + w[i], f[i][j]);
}
}
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 = m; j >= v[i]; j--) f[j] = max(f[j - v[i]] + w[i], f[j]);
}
cout << f[m] << endl;
return 0;
}