0-1背包算法
以下 0-1 背包问题是否可解:
- “浮动”正值和
- “浮动”权重(可以是正数或负数)
- 背包的“浮动”容量 > 0
我平均有 < 10 项,所以我正在考虑使用暴力实现。但是,我想知道是否有更好的方法。
Is the following 0-1 Knapsack problem solvable:
- 'float' positive values and
- 'float' weights (can be positive or negative)
- 'float' capacity of the knapsack > 0
I have on average < 10 items, so I'm thinking of using a brute force implementation. However, I was wondering if there is a better way of doing it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是一个相对简单的二进制程序。
我建议用蛮力进行修剪。如果任何时候你超过了允许的重量,你不需要尝试其他物品的组合,你可以丢弃整棵树。
哦等等,你有负权重?始终包括所有负权重,然后按照上述方法处理正权重。或者负重量的物品也有负值吗?
包括所有具有正值的负重量项目。排除所有具有正重量和负价值的物品。
对于具有负值的负重量物品,减去其重量(增加背包容量)并使用代表未拿走该物品的伪物品。伪物品将具有正的重量和价值。通过强力修剪来进行。
This is a relatively simple binary program.
I'd suggest brute force with pruning. If at any time you exceed the allowable weight, you don't need to try combinations of additional items, you can discard the whole tree.
Oh wait, you have negative weights? Include all negative weights always, then proceed as above for the positive weights. Or do the negative weight items also have negative value?
Include all negative weight items with positive value. Exclude all items with positive weight and negative value.
For negative weight items with negative value, subtract their weight (increasing the knapsack capavity) and use a pseudo-item which represents not taking that item. The pseudo-item will have positive weight and value. Proceed by brute force with pruning.
是的,用暴力破解吧这是一个 NP 完全问题,但这并不重要,因为您的项目数少于 10 个。暴力破解不会有问题。
Yeah, brute force it. This is an NP-Complete problem, but that shouldn't matter because you will have less than 10 items. Brute forcing won't be problematic.
如果你只能有正值,那么每一个负重量的物品都必须进去。
然后我想你可以计算价值/重量比,并根据该顺序暴力破解剩余的组合,一旦你得到一个合适的,你就可以跳过休息。
问题可能在于,分级和排序实际上比仅仅进行所有计算更昂贵。
根据集合的大小和分布,显然会有不同的盈亏平衡点。
If you can only have positive values then every item with a negative weight must go in.
Then I guess you could calculate Value/Weight Ratio, and brute force the remaining combinations based on that order, once you get one that fits you can skip the rest.
The problem may be that the grading and sorting is actually more expensive than just doing all the calculations.
There will obviously be a different breakeven point based on the size and distribution of the set.
这可以使用动态规划来解决。下面的代码可以帮助您使用动态规划解决 0/1 背包问题。
This can be solved using Dynamic Programming. Below code can help you solve the 0/1 Knapsack problem using Dynamic Programming.