Balanced partition

后端 未结 3 762
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 19:47

I know this was talked over a lot here, but I am struggling with this problem.

We have a set of numbers, e.g [3, 1, 1, 2, 2, 1], and we need to break it into two sub

相关标签:
3条回答
  • 2020-12-16 20:08

    I faced this same problem recently, and I posted a question about it (here: Variant of Knapsack). The difference in my case is that the resulting subsets must be the same size (if the original set has an even number of elements). In order to assure that, I added a few lines to @Sandesh Kobal answer;

    void partition(unsigned int i,long &diffsofar, long sum1,long sum2)
    {
        int maxsize = (array.size()+1)/2;
    
        if(p1.size()>maxsize)
            return;
    
        if(p2.size()>maxsize)
            return;
    
        if(i==array.size())
        {
            ...
    

    Also, after both calls to partition, I added if(diffsofar==0) return;. If we already found an optimal solution, it makes no sense to keep searching...

    0 讨论(0)
  • 2020-12-16 20:15

    This will be O(2^N). No Dynamic Programming used here. You can print result1, result2 and difference after execution of the function. I hope this helps.

    vector<int> p1,p2;
    vector<int> result1,result2;
    vector<int> array={12,323,432,4,55,223,45,67,332,78,334,23,5,98,34,67,4,3,86,99,78,1};
    
    void partition(unsigned int i,long &diffsofar, long sum1,long sum2)
    {
        if(i==array.size())
        {
            long diff= abs(sum1 - sum2);
            if(diffsofar > diff)
            {
                result1 =  p1;
                result2 = p2;
                diffsofar = diff;
            }
            return;
        }
    
        p1.push_back(array[i]);
        partition(i+1,diffsofar,sum1+array[i],sum2);
        p1.pop_back();
    
        p2.push_back(array[i]);
        partition(i+1,diffsofar,sum1,sum2+array[i]);
        p2.pop_back();
    
        return;
    }
    
    0 讨论(0)
  • 2020-12-16 20:19

    The pseudo-polynomial algorithm is designed to provide an answer to the decision problem, not the optimization problem. However, note that the last row in the table of booleans in the example indicates that the current set is capable of summing up to N/2.

    In the last row, take the first column where the boolean value is true. You can then check what the actual value of the set in the given column is. If the sets summed value is N/2 you have found the first set of the partition. Otherwise you have to check which set is capable of being the difference to N/2. You can use the same approach as above, this time for the difference d.

    0 讨论(0)
提交回复
热议问题