Distribute numbers to two “containers” and minimize their difference of sum

馋奶兔 提交于 2020-01-23 22:25:14

问题


Suppose there are n numbers let says we have the following 4 numbers 15,20,10,25

There are two container A and B and my job is to distribute numbers to them so that the sum of the number in each container have the least difference.

In the above example, A should have 15+20 and B should have 10+ 25. So difference = 0.

I think of a method. It seems to work but I don't know why.

Sort the number list in descending order first. In each round, take the maximum number out and put to the container have less sum.

Btw, is it can be solved by DP? THX


回答1:


  1. In fact, your method doesn't always work. Think about that 2,4,4,5,5.The result by your method will be (5,4,2)(5,4), while the best answer is (5,5)(4,4,2).

  2. Yes, it can be solved by Dynamical Programming.Here are some useful link:

    Tutorial and Code: http://www.cs.cornell.edu/~wdtseng/icpc/notes/dp3.pdf
    A practice: http://people.csail.mit.edu/bdean/6.046/dp/ (then click Balanced Partition)

  3. What's more, please note that if the scale of problem is damn large (like you have 5 million numbers etc.), you won't want to use DP which needs a too huge matrix. If this is the case, you want to use a kind of Monte Carlo Algorithm:

    1. divide n numbers into two groups randomly (or use your method at this step if you like);
    2. choose one number from each group,
      if (to swap these two number decrease the difference of sum) swap them;
    3. repeat step 2 until "no swap occurred for a long time".

    You don't want to expect this method could always work out with the best answer, but it is the only way I know to solve this problem at very large scale within reasonable time and memory.



来源:https://stackoverflow.com/questions/8612056/distribute-numbers-to-two-containers-and-minimize-their-difference-of-sum

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