Subset sum problem where each number can be added or subtracted

跟風遠走 提交于 2019-12-06 15:52:03

问题


Given a set A containing n positive integers, how can I find the smallest integer >= 0 that can be obtained using all the elements in the set. Each element can be can be either added or subtracted to the total. Few examples to make this clear.

A = [ 2, 1, 3]

Result = 0 (2 + 1 - 3)

A = [1, 2, 0]

Result = 1 (-1 + 2 + 0)

A = [1, 2, 1, 7, 6]

Result = 1 (1 + 2 - 1 - 7 + 6)


回答1:


You can solve it by using Boolean Integer Programming. There are several algorithms (e.g. Gomory or branch and bound) and free libraries (e.g. LP-Solve) available.

Calculate the sum of the list and call it s. Double the numbers in the list. Say the doubled numbers are a,b,c. Then you have the following equation system:

Boolean x,y,z 

a*x+b*y+c*z >= s

Minimize ax+by+cz!

The boolean variables indicate if the corresponding number should be added (when true) or subtracted (when false).

[Edit]

I should mention that the transformed problem can be seen as "knapsack problem" as well:

Boolean x,y,z 

-a*x-b*y-c*z <= -s

Maximize ax+by+cz!


来源:https://stackoverflow.com/questions/5741242/subset-sum-problem-where-each-number-can-be-added-or-subtracted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!