天天看點

51 NOD 1007 正整數分組(0-1背包)

題目連結:https://www.51nod.com/onlineJudge/questionCode.html#problemId=1007¬iceId=275106

1007 正整數分組

51 NOD 1007 正整數分組(0-1背包)

基準時間限制:1 秒 空間限制:131072 KB 分值: 10  難度:2級算法題

51 NOD 1007 正整數分組(0-1背包)

 收藏

51 NOD 1007 正整數分組(0-1背包)

 關注 将一堆正整數分為2組,要求2組的和相差最小。 例如:1 2 3 4 5,将1 2 4分為1組,3 5分為1組,兩組和相差1,是所有方案中相差最少的。 Input

第1行:一個數N,N為正整數的數量。
第2 - N+1行,N個正整數。
(N <= 100, 所有正整數的和 <= 10000)      

Output

輸出這個最小差      

Input示例

5
1
2
3
4
5      

Output示例

1      

解析:0-1背包,背包容量所有數的和sum/2,每一個數的價值和重量都為這個數

代碼:

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1000009;

int a[1009], dp[10009];

int main()
{
    int n;
    scanf("%d", &n);
    int sum = 0;
    for(int i = 1; i <= n; i++)
    {
        scanf("%d", &a[i]);
        sum += a[i];
    }
    memset(dp, 0, sizeof(dp));
    for(int i = 1; i <= n; i++)
    {
        for(int j = sum/2; j >= a[i]; j--)
        {
            dp[j] = max(dp[j], dp[j-a[i]]+a[i]);
        }
    }
    printf("%d\n", abs(dp[sum/2]*2-sum));
    return 0;
}