AcWing 2. 01背包问题
原题链接
简单
作者:
Value
,
2020-05-28 08:41:36
,
所有人可见
,
阅读 513
二维
#include <iostream>
using namespace std;
const int N = 1010;
int weight[N], value[N], f[N][N];
int main(){
int n, bag;
cin >> n >> bag;
for(int i = 1; i <= n; i ++ ) cin >> weight[i] >> value[i];
for(int i = 1; i <= n; i ++ ){
for(int j = 1; j <= bag; j ++ ){ # 顺序无关,可以从1 - bag,也可以从bag - 1,二维所以状态均存储了
f[i][j] = f[i - 1][j];
if(weight[i] <= j) f[i][j] = max(f[i-1][j], f[i-1][j - weight[i]] + value[i]);
}
}
cout << f[n][bag] << endl;
return 0;
}
一维优化
不同的地方在于枚举时候的顺序,必须从bag开始
#include <iostream>
using namespace std;
const int N = 1010;
int weight[N], value[N], f[N];
int main(){
int n, bag;
cin >> n >> bag;
for(int i = 1; i <= n; i ++ ){
cin >> weight[i] >> value[i];
}
for(int i = 1; i <= n; i ++ ){
for(int j = bag; j >= weight[i]; j -- ){
f[j] = max(f[j], f[j - weight[i]] + value[i]);
}
}
cout << f[bag] << endl;
return 0;
}