动态规划之均衡划分

题目描述:Balanced Partition You have a set, A = {a1,··· ,an}, of n integers each in the range [0..K]. Partition these integers into two subsets such that you minimize |S1−S2|, where S1 and S2 denote the sums of the elements in each of the two subsets. Design a DP algorithm to solve the problem.

题目的意思是,给你一个大小为n的数组,每个数的大小都在0到K之间。让你将这个数组划分为两个,使两个数组的数的和的差最小,即|S1-S2|最小。

首先我们要设计状态转移函数:

有了状态转移函数,就可以着手写代码了。

#include

#include

using namespace std;

int n

int number[505];

int dp[505][505];

int mindec()

{

    int sum = 0;

    memset(dp,0,sizeof(dp));

    for(int i=0;i

        sum+=number[i];

    }

    for(int i=0;i

        dp[i][0]=1;

    }

    for(int i=1;i<=n;i++){

        for(int j=1;j<=sum;j++){

            if(j-number[i-1]>=0){

                if(dp[i-1][j]||dp[i][j-number[i-1]])

                    dp[i][j]=1;

            }else dp[i][j]=dp[i-1][j];

        }

    }

    for(int i=1;i<=sum;i++){

        for(int j=sum/2;j>=0;j--){

            if(dp[i][j]) return sum-j-j;

        }

    }

    return -1;

}

int main()

{

    cout << "请输入数组的元素个数及元素:"<

    cin >>n;

    for(int i=0; i

    {

        int temp;

        cin >> temp;

        number[i]=temp;

    }

    int answer = mindec();

    cout << answer << endl;

    return 0;

}

 

 

 

你可能感兴趣的:(动态规划之均衡划分)