平衡问题,将n个硬币的总价值累加得到sum,再用sum/2作为背包容量对n个硬币做01背包处理,看能组成的最大容量是多少。
/*********************
* Author:fisty
* Data:2014-10-02
* uva562
* ******************/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <math.h>
using namespace std;
#define MAX_N 110000
int dp1[MAX_N], dp2[MAX_N];
int main(){
int t;
scanf("%d", &t);
while(t--){
int n;
scanf("%d", &n);
int sum = 0;
int v[MAX_N];
for(int i = 0;i < n; i++){
scanf("%d", &v[i]);
sum += v[i];
}
int m = sum;
sum = sum / 2;
int u[MAX_N];
memset(u, 0, sizeof(u));
memset(dp1, 0, sizeof(dp1));
memset(dp2, 0, sizeof(dp2));
for(int i = 0;i < n; i++){
for(int j = sum; j >= v[i]; j--){
if(dp1[j] < dp1[j-v[i]] + v[i]){
dp1[j] = max(dp1[j], dp1[j-v[i]] + v[i]);
//u[i] = 1;
}
}
}
/*for(int i = 0;i < n; i++){
if(!u[i]){
for(int j = sum;j >= v[i]; j--){
dp2[j] = max(dp2[j], dp2[j-v[i]] + v[i]);
}
}
}*/
printf("%d\n", abs(m-2*dp1[sum]));
}
return 0;
}