一维数组(滚动数组)
和01背包很像,就是背包的遍历顺序不一样
https://www.bilibili.com/video/BV11K411i7od (结合y总讲的)
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
int dp[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++) // 每个物品随便取,所以要更新所以程序
dp[j] = max(dp[j], dp[j - v[i]] + w[i]);
cout << dp[m] << endl;
return 0;
}
超级暴力(三重循环)(现在会TLE)
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
int f[N][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;
return 0;
}
进化一下两重循环的
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int w[N], v[N];
int n, m;
int dp[N][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++) {
dp[i][j] = dp[i - 1][j]; // 拷贝上一层数据
if (j >= v[i]) { // 满足条件
dp[i][j] = max(dp[i][j], dp[i][j - v[i]] + w[i]); // 同一层的比较,这也是优化为一维数组的一个重要条件,即为什么可以从头遍历
}
}
}
cout << dp[n][m] << endl;
return 0;
}