多重背包 模板题 二进制拆分 洛谷 P1776 宝物筛选
作者:互联网
每类物品每2的幂次分成一组, 每个小组合并为1个大物品, 做01背包.
重新划分新物品要注意两点:
Ⅰ2的幂次从小到大枚举
Ⅱ拆分有剩余直接将剩下的放入.
代码:
int n;
ll W, dp[M], v[M], w[M], m[M];
struct node {ll v, w;};
vector<node> obj;
void init() {
n = read(), W = read();
for (int i = 1; i <= n; ++i)v[i] = read(), w[i] = read(), m[i] = read();
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m[i]; j <<= 1) {// 二进制拆分, 从2的0次方开始枚举
obj.emplace_back((node) {v[i] * j, w[i] * j});
m[i] -= j;
}
if (m[i]) {//拆分如果剩下, 直接将这个剩余的放入.
obj.emplace_back((node) {v[i] * m[i], w[i] * m[i]});
m[i] = 0;
}
}
for (auto i:obj)
for (int j = W; j >= i.w; --j)
checkMax(dp[j], dp[j - i.w] + i.v);
ll ans = 0;
for (int i = 0; i <= W; ++i)checkMax(ans, dp[i]);
write(ans), enter;
}
标签:洛谷,幂次,int,ll,read,P1776,模板,物品,dp 来源: https://blog.csdn.net/qq_32259423/article/details/99655780