AcWing 3. 完全背包问题
原题链接
简单
作者:
wugensheng
,
2021-04-17 00:10:14
,
所有人可见
,
阅读 236
完全背包问题-朴素做法 y总-yyds-🐂🐂🐂🍺啊
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010;
int f[N][N];
int w[N], v[N];
int n, m;
int main() {
cin >> n >> m;
for (int i = 1; i <= n ; i++) cin >> w[i] >> v[i];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= w[i]) f[i][j] = max(f[i][j], f[i][j - w[i]] + v[i]);
}
}
cout << f[n][m] << endl;
return 0;
}
一维空间优化-完全背包
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010;
int f[N];
int w[N], v[N];
int n, m;
int main() {
cin >> n >> m;
for (int i = 1; i <= n ; i++) cin >> w[i] >> v[i];
for (int i = 1; i <= n; i++) {
for (int j = w[i]; j <= m; j++) {//从小到大,是因为上面朴素做法中用的是同一层的状态更新的
f[j] = max(f[j], f[j - w[i]] + v[i]);
}
}
cout << f[m] << endl;
return 0;
}