[英]Knapsack with mutually exclusive items
While standard knapsack problem can be solved by dynamic programming, I am trying to twist the problem a bit to clear my concept, however I found it maybe harder than I thought. 虽然标准的背包问题可以通过动态编程来解决,但我试图稍微扭转问题以清除我的概念,但是我发现它可能比我想象的更难。
Original knapsack problem is that given a knapsack with size W
, and a list of items which weight w[i]
and has a value v[i]
, find the subset of items which can fit in the knapsack with highest total value. 原始背包问题是,给定一个尺寸为W
的背包,以及一个重量为w[i]
并且具有值v[i]
的项目列表,找到可以适合具有最高总值的背包的项目子集。
To my understanding, this can be done by O(Wn)
with dynamic programming, where n
is the number of items. 据我所知,这可以通过动态编程的O(Wn)
来完成,其中n
是项目的数量。
Now if I try to add m
constrains, each of them is a pair of items which can only be picked mutual exclusively (ie if there exist a constrain of item A and item B, then I can only take either one of them but not both) 现在,如果我尝试添加m
约束,它们中的每一个都是一对只能相互选择的项目(即如果存在项目A和项目B的约束,那么我只能选择其中一个而不是两个)
Under such constrains, can this problem still be solved by dynamic programming in O(Wn)
? 在这样的约束下,这个问题仍然可以通过O(Wn)
动态编程来解决吗?
Assumption : Each element is included in atmost one constraint. 假设 :每个元素都包含在最多一个约束中。
For the usual Knapsack problem, the optimal substructure that the problem exhibits is as follows: 对于通常的背包问题,问题表现出的最佳子结构如下:
For each item there can be two cases: 对于每个项目,可能有两种情况:
1. The item is included in the solution 1.该项目包含在解决方案中
2. The item not included in the solution. 2.未包含在解决方案中的项目。
Hence, the optimal solution for n
items is given by max of following two values. 因此, n
项的最优解由下面两个值的最大值给出。
1. Maximum value obtained by n-1
items and W
weight. 1.由n-1
项和W
权重获得的最大值。
2. v_n
+ maximum value obtained by n-1
items and W-w_n
weight. 2. v_n
+由n-1
项和W-w_n
权重获得的最大值。
Now if we add the constraint that either of n
th or (n-1)
th item can exist in the solution, then the optimal solution for n
items is given by max of following three values. 现在,如果我们添加任何的约束n
个或(n-1)
个项目可在溶液中存在,那么最优解n
项目由最高给出以下三个值。
1. Maximum value obtained by n-2
items and W
weight. 1.由n-2
项和W
权重获得的最大值。
2. v_n
+ maximum value obtained by n-2
items and W-w_n
weight. 2. v_n
+由n-2
项和W-w_n
权重获得的最大值。
3. v_(n-1)
+ maximum value obtained by n-2
items and W-w_(n-1)
weight. v_(n-1)
+由n-2
项和W-w_(n-1)
权重获得的最大值。
So we treat each pair of elements in the constraint as a single element and execute the dynamic programming algorithm in O(Wn)
time. 因此,我们将约束中的每对元素视为单个元素,并在O(Wn)
时间内执行动态编程算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.