题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=503
题目大意:两个人去分一些有价值的东西,要求尽可能的共公平,求两个人分完物品的差值
解析: 0-1背包,把最价值算出来 / 2,求其一半得到的最大价值,然后与剩下的比较即可
代码如下:
#include<iostream>
#include<algorithm>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<string>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#define N 50001
using namespace std;
const int inf = 1e9;
const int mod = 1<<30;
const double eps = 1e-8;
const double pi = acos(-1.0);
typedef long long LL;
int a[509], dp[N];
int main()
{
int v, n, i, j, t;
cin >> t;
while(t--)
{
scanf("%d", &n);
int sum = 0;
for(i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
sum += a[i];
}
v = sum / 2;
memset(dp, 0, sizeof(dp));
for(i = 1; i <= n; i++)
{
for(j = v; j >= a[i]; j--)
{
dp[j] = max(dp[j], dp[j - a[i]] + a[i]);
}
}
printf("%d\n", abs(sum - dp[v] - dp[v]) );
}
return 0;
}