How to divide a set into two subsets such that difference between the sum of numbers in two sets is minimal?

前端 未结 18 736
攒了一身酷
攒了一身酷 2020-11-27 10:55

Given a set of numbers, divide the numbers into two subsets such that difference between the sum of numbers in two subsets is minimal.

T

18条回答
  •  盖世英雄少女心
    2020-11-27 11:37

    This is a variation of the knapsack and subset sum problem. In subset sum problem, given n positive integers and a value k and we have to find the sum of subset whose value is less than or equal to k. In the above problem we have given an array, here we have to find the subset whose sum is less than or equal to total_sum(sum of array values). So the subset sum can be found using a variation in knapsack algorithm,by taking profits as given array values. And the final answer is total_sum-dp[n][total_sum/2]. Have a look at the below code for clear understanding.

    #include
    #include
    using namespace std;
    int main()
    {
            int n;
            cin>>n;
            int arr[n],sum=0;
            for(int i=1;i<=n;i++)
            cin>>arr[i],sum+=arr[i];
            int temp=sum/2;
            int dp[n+1][temp+2];
            for(int i=0;i<=n;i++)
            {
                for(int j=0;j<=temp;j++)
                {
                    if(i==0 || j==0)
                    dp[i][j]=0;
                    else if(arr[i]<=j)
                    dp[i][j]=max(dp[i-1][j],dp[i-1][j-arr[i]]+arr[i]);
                    else
                    {
                    dp[i][j]=dp[i-1][j];
                    }
                }
            }
            cout<

提交回复
热议问题