一、01背包问题
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
int f[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 = m; j >= v[i]; j -- )
f[j] = max(f[j], f[j - v[i]] + w[i]);
cout << f[m] << endl;
return 0;
}
二、完全背包问题
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
int f[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 ++ )
f[j] = max(f[j], f[j - v[i]] + w[i]);
cout << f[m] << endl;
return 0;
}
三、多重背包问题I
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int n, m;
int v[N], w[N], s[N];
int f[N][N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> v[i] >> w[i] >> s[i];
for (int i = 1; i <= n; i ++ )
for (int j = 0; j <= m; j ++ )
for (int k = 0; k <= s[i] && 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;
}
四、多重背包问题II
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 11010, M = 2010;
int n, m;
int v[N], w[N];
int f[N];
int main()
{
cin >> n >> m;
int cnt = 0;
for (int i = 1; i <= n; i ++ )
{
int a, b, s;
cin >> a >> b >> s;
int k = 1;
while (k <= s)
{
cnt ++ ;
v[cnt] = a * k;
w[cnt] = b * k;
s -= k;
k *= 2;
}
if (s > 0)
{
cnt ++ ;
v[cnt] = a * s;
w[cnt] = b * s;
}
}
n = cnt;
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;
return 0;
}
五、分组背包问题
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int n, m;
int v[N][N], w[N][N], s[N];
int f[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
{
cin >> s[i];
for (int j = 0; j < s[i]; j ++ )
cin >> v[i][j] >> w[i][j];
}
for (int i = 1; i <= n; i ++ )
for (int j = m; j >= 0; j -- )
for (int k = 0; k < s[i]; k ++ )
if (v[i][k] <= j)
f[j] = max(f[j], f[j - v[i][k]] + w[i][k]);
cout << f[m] << endl;
return 0;
}
部分代码为yxc上课代码
ok
0-1 背包,空间优化 :由二维数组变一维数组的时候,
第二层循环 需要从大到小枚举这里老是绕不过弯来
过了一个月 终于绕过来 了 果然要时间沉淀来耗
hhh,可否给我讲讲,我也绕不过来
首先要理解递推公式,因为当前的状态依赖之前的状态,所以要确保把
之前的状态
先计算出来。现在的目标为怎么合理设置循环的顺序,是从小到大枚举还是从大到小枚举呢,使得之前的状态先计算出来。
比如f(i, 10) 依赖f(i, 11) ,那么f(i,11)就先的计算出来,所以要从到大到小枚举才能到达此
效果
从
f(i,j) = max(f(i-1,j),f(i-1,j-v) + w
可以得出当前状态之和上一层有关,且只和上一层的左边的列有关系,所以可以用滚动数组来优化。值得注意的是,内层的循环需要
从大到小
遍历,若从小到大遍历的话,计算当前状态所依赖的值被覆盖更新,因此计算的结果会有问题。倒着遍历,也就是从右到左遍历,右边的值会覆盖更新,当前依赖的状态没有更新,还是上一层的状态。
其实模拟一遍就很清晰了~
赞