终于学会了多重背包和混合背包!!
我们熟悉的背包问题不过就是01背包和完全背包。
但是多重背包如何处理?
一种方法是单调队列,但是我不会。这里介绍比较简便的二进制分解。
比如一件重为19的物品,我们通过二进制讲它分解为1、2、4、8、4。
前面的数字显然是从1开始的等比数列,而最后的是这个数剩下的余数。
可以证明:这些数字可以表达出0~19中任意的一个数。
所以我们成功地将一个大的背包分解为若干个小的物品,并且不改变答案,跑得还更快。
代码是这么写的:
int base = 1;
while(p > base)
{
val[++tot] = v * base;
weight[tot] = w * base;
p -= base;// 注意这里要减掉base,表示我剩下的重量
base <<= 1;
}
if(p)
{
val[++tot] = v * p;
weight[tot] = w * p;
}
P1833这道题还有一种完全背包。我们可以特判,也可以视为一种可以取无限多次(即可以自己设一个INF)。然后可以转换为多重背包,就可以用统一的方法做了。
完整代码:
#include<cstdio>
#include<algorithm>
const int maxn = 1000005;
int val[maxn], weight[maxn];
int n, m, tot;
int dp[maxn];
int read()
{
int ans = 0, s = 1;
char ch = getchar();
while(ch > '9' || ch < '0'){ if(ch == '-') s = -1; ch = getchar(); }
while(ch >= '0' && ch <= '9') ans = (ans << 3) + (ans << 1) + ch - '0', ch = getchar();
return s * ans;
}
int main()
{
n = read(), m = read();
for(int i = 1; i <= n; i++)
{
int v = read(), w = read(), p = read();
int base = 1;
while(p > base)
{
val[++tot] = v * base;
weight[tot] = w * base;
p -= base;
base <<= 1;
}
if(p)
{
val[++tot] = v * p;
weight[tot] = w * p;
}
}
for(int i = 1; i <= tot; i++)
{
for(int j = m; j >= weight[i]; j--)
{
dp[j] = std::max(dp[j], dp[j - weight[i]] + val[i]);
}
}
printf("%d\n", dp[m]);
return 0;
}