n个正整数均分两组,使两组整数的和的差的绝对值最小

版权声明:人生碌碌,竞短论长,却不道荣枯有数,得失难量。 https://blog.csdn.net/ancientear/article/details/83825645
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int M = 100 + 20;

int w[M];
int dp[M*100];//动态规划
bool bools[M][M];


int main()
{
    int n,i,j;
    while (scanf("%d", &n) != EOF) {
        int sum = 0;
        for (int i = 0; i < n; ++i) {
            scanf("%d", &w[i]);
            sum += w[i];
        }
        memset(dp, 0, sizeof(dp));
        memset(bools, 0, sizeof(bools));
        for (int i = 0; i < n; ++i)
            for (int j = sum/2; j >= w[i]; --j) {
                if (dp[j] < dp[j-w[i]] + w[i]) {
                    dp[j] = dp[j-w[i]] + w[i];
                    bools[i][j] = true;
                }
            }
        printf("%d\n", sum - dp[sum/2]*2);
        i = n;
        j = sum/2;
        while (i--) {
            if (bools[i][j]) {
                    // printf("%d ", w[i]);测试数据分配情况
                j -= w[i];
            }
        }
        
    }
    return 0;
    
}


展开阅读全文

没有更多推荐了,返回首页