题意:
若干硬币,分成两份,使其绝对值之差尽量小。
思路:
算出硬币总和,然后把硬币总和的一半设为背包容量,背包能拿到的最大价值即是2个人中其中一个所得到。
然后用01背包的思路。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int Max(int a,int b){
if(a > b)return a;
return b;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("D:\\acm.txt","r",stdin);
#endif // ONLINE_JUDGE
int cases,ans;
int bags[50010];
int coinNum,coins[200];
cin >> cases;
while(cases--){
memset(bags,0,sizeof(bags));
memset(coins,0,sizeof(coins));
ans = 0;
int coinSum = 0;
///////////////////
cin>>coinNum;
for(int i = 0;i < coinNum;i++) {
cin >> coins[i];
coinSum += coins[i];
}
int half = coinSum / 2;//背包容量设成钱币总数的一半
/////////////
for(int i = 0;i < coinNum;i++){
for(int j = half ;j >= coins[i];j--){
bags[j] = Max(bags[j] , bags[j - coins[i]] + coins[i]);
}//01背包
}
///////////
if(bags[half] > half)ans = bags[half] - (coinSum - bags[half]);
else ans = (coinSum - bags[half]) - bags[half];
cout << ans<<endl;
}
return 0;
}