51Nod 1007 01背包

本文介绍了一种解决将n个数分为两组使差值最小的问题的方法,通过01背包问题的变形来实现。具体算法采用空间复杂度为O(V)的递推方式,从每个层次的最大容量向前计算,最终输出两组数的差值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门

  • 题意:把n个数分成两组,使得这两组数的差值最小
  • 解析:01背包的变形。分成两组,也就相当于是挑出一部分,剩下一部分。这样我们就可以把问题看做01背包。即从n个数里选一些数放入背包,背包最大容量是sum/2。

这里采用的是空间复杂度为O(V)的算法,从每个层次最大容量向前计算。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <iomanip>
#include <assert.h>
#include <bitset>
using namespace std;

#define eps         (1e-6)
#define LL          long long
#define pi          acos(-1.0)
#define rd(a)       (a = read())
#define mem(a,b)    memset(a,b,sizeof(a))

#define FOR(x,to)   for(int x=0;x<(to);++x)
#define FORR(x,arr) for(auto& x:arr)
#define LOOP(x,k,to) for(int x=k;x<(to);++x)
#define ITR(x,c)    for(auto x=c.begin();x!=c.end();x++)
#define ALL(a)      (a.begin(),(a.end())
#define ZERO(a)     memset(a,0,sizeof(a))
#define MINUS(a)    memset(a,0xff,sizeof(a))
#define IOS         cin.tie(0) , cout.sync_with_stdio(0)
#define PRINT(a,b)  cout << "#" << (a) << " " << (b) << endl
#define DEBUG(a,b)  cout << "$" << (a) << " " << (b) << endl

const int INF = 0x3f3f3f3f;
const int MAXN = 105;
const int MAXM = 1e4 + 10;
int n;
int v = 0;
int a[MAXN];
int dp[MAXM];
int sum = 0;

void CONFIRM()
{
    DEBUG("sum =", sum);
    for(int i=1; i<=n; ++i){
            PRINT(i, dp[i]);
    }
    cout << "\n---------------\n";
    return;
}

void SOLVE()
{
    v = sum / 2;
    ZERO(dp);
    for(int i=1; i<=n; ++i){
        for(int j=v; j>=a[i]; --j){
            dp[j] = max(dp[j], dp[j-a[i]]+a[i]);
            
        }
    }
    cout << abs(sum - dp[v]*2) << endl;
    return;
}

int main()
{
    IOS;
    cin >> n;
    for(int i=1; i<=n; ++i){
        cin >> a[i];
        sum += a[i];
    }
    SOLVE();
    //CONFIRM();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值