A line with the number of problems n, followed by n times:
- a line with a non negative integer m (
) 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.
#include<stdio.h>
#include<string.h>
int n,a[110];
int dp[300010];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
int sum=0;
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
sum+=a[i];
}
memset(dp,0,sizeof(dp));
dp[0]=1;
int mid=sum/2;
for(int i=0;i<n;i++)
{
for(int j=mid;j>=a[i];j--) // for(int j=a[i];j<=mid;j++) 这是有本质区别!倒着循环a[i]只用了一次,正着循环表示可以使用mid-a[i] 次
{
if(dp[j-a[i]]) dp[j]=1;
}
if(dp[mid]) break;
}
for(;mid>=0;mid--)if(dp[mid])
{
printf("%d\n",sum-2*mid);
break;
}
}
}