正整数分组----dp(01背包)

题目描述:

Time limit,1000 mshtml

Memory limit,131072 kBios

Author  李陶冶spa

将一堆正整数分为2组,要求2组的和相差最小。code

例如:1 2 3 4 5,将1 2 4分为1组,3 5分为1组,两组和相差1,是全部方案中相差最少的。htm

Inputget

第1行:一个数N,N为正整数的数量。 
第2 - N+1行,N个正整数。 
(N <= 100, 全部正整数的和 <= 10000)string

Outputit

输出这个最小差io

Sample Inputclass

5
1
2
3
4
5

Sample Output

1

思路:

    将这些数分为两组,使差最小,为使差最小就要使每组的数的和尽可能的接近sum/2这个值,因此能够sum/2看做背包容量,那些整数看做要放入背包中的物品,求背包最大能放的数字和,最后sum减去最大的容量的两倍(sum-2*dp[i])即为最小的差值。

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include<string.h>
using namespace std;
int a[110];
int dp[5010];
int main()
{
    int n;
    scanf("%d",&n);
    int sum = 0;
    for(int i = 1; i <= n; i++)
    {
        scanf("%d",&a[i]);
        sum += a[i];
    }
    int b = sum/2;
    memset(dp,0,sizeof(dp));
    for(int i = 1; i <= n; i++)
    {
        for(int j = b; j >= a[i]; j--)
            dp[j] = max(dp[j],dp[j-a[i]]+a[i]);
    }
    printf("%d\n",abs(sum-2*dp[b]));
    return 0;
}

题目连接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1007