- 题意:把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;
}