开发者

Subset sum problem where each number can be added or subtracted

开发者 https://www.devze.com 2023-02-27 06:58 出处:网络
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 b开发者_运维百科e either added or

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 b开发者_运维百科e 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)


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!
0

精彩评论

暂无评论...
验证码 换一张
取 消