Description
It's commonly known that the Dutch have invented copper-wire. Two Dutch men were fighting over a nickel, which was made of copper. They were both so eager to get it and the fighting was so fierce, they stretched the coin to great length and thus created copper-wire.
Not commonly known is that the fighting started, after the two Dutch tried to divide a bag with coins between the two of them. The contents of the bag appeared not to be equally divisible. The Dutch of the past couldn't stand the fact that a division should favour one of them and they always wanted a fair share to the very last cent. Nowadays fighting over a single cent will not be seen anymore, but being capable of making an equal division as fair as possible is something that will remain important forever...
That's what this whole problem is about. Not everyone is capable of seeing instantly what's the most fair division of a bag of coins between two persons. Your help is asked to solve this problem.
Given a bag with a maximum of 100 coins, determine the most fair division between two persons. This means that the difference between the amount each person obtains should be minimised. The value of a coin varies from 1 cent to 500 cents. It's not allowed to split a single coin.
Input
A line with the number of problems n, followed by n times:
- a line with a non negative integer m (m<=100) indicating the number of coins in the bag
- a line with m numbers separated by one space, each number indicates the value of a coin.
Output
The output consists of n lines. Each line contains the minimal positive difference between the amount the two persons obtain when they divide the coins from the corresponding bag.
Sample Input
2
3
2 3 5
4
1 2 4 6
Sample Output
0
1
解析
两人分到硬币价值之差最小的情况是两人恰好能平分(int)。那么试着转化为01背包问题,假设背包容积是硬币总价值的一半sum/2,第i枚硬币的价值是coin[i],体积也是coin[i]。最后两人分到的硬币价值之差就是fabs(sum-2*dp[sum/2])。
代码
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,i,j,coin[105];
scanf("%d",&n);
int sum=0;
for(i=1;i<=n;i++)
{
scanf("%d",&coin[i]);
sum+=coin[i];
}
int ave=sum/2;
int dp[50005];
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
{
for(j=ave;j>=coin[i];j--)
{
dp[j]=max(dp[j],dp[j-coin[i]]+coin[i]);
}
}
int ans=fabs(sum-2*dp[ave]);
printf("%d\n",ans);
}
return 0;
}