01背包
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1000 + 9;
int n,m;
int v[N],w[N];int f[N][N];
//只从前i个物品中选,总体积小于j的所有选法
void solve()
{
cin >> n >> m;
for (int i = 1;i <= n;i ++) cin >> v[i] >> w[i];
//f[0][0~m] = 0;
for (int i = 1;i <= n;i ++)
for (int j = 0;j <= m;j ++)
{
f[i][j] = f[i - 1][j];
if (j >= v[i]) f[i][j] = max(f[i][j],f[i - 1][j - v[i]] + w[i]);
}
cout << f[n][m] << endl;
}
二维到一维的转化
f[i][j] = max(f[i][j],f[i - 1][j - v[i]] + w[i]) => f[j] = max(f[j],f[j - v[i]] + w[i]);
需要倒着枚举体积,因为原始方程是,f[i - 1][j - v[i]],是i - 1层的体积,如果从小到大枚举体积,由于 j - v[i] < j ,所以f[j - v[i]] 会被提前更新,f[j - v[i]] 表示的就不是我们所需要的i - 1层的体积了,因此需要从大到小枚举体积
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1000 + 9;
int n,m;
int v[N],w[N];
int f[N];
//只从前i个物品中选,总体积小于j的所有选法
void solve()
{
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],f[j - v[i]] + w[i]);
}
cout << f[m] << endl;
}
完全背包 //UNDO