dividing coins 简单dp

Input

          A line with the number of problems n, followed by n times:

  • a line with a non negative integer m ($m \le 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.

#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;
        }
    }
}

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值