Va 562-Dividing coins (01 backpack)

Source: Internet
Author: User

The nominal value of n coins should be divided into two heaps (the average number is not required), and the absolute value of the sum of the two heaps of coins should be minimized, the absolute value of the minimum output value. Solution: Consider half of the sum of half as the capacity of the backpack, and then perform the 01 backpack processing, and then take the reachable value cur as close as possible to half, two times of half-cur is the required value ans. Note that when sum is an odd number, ans must add 1.

#include <stdio.h>  #include <string.h>  const int N = 50005;  const int M = 105;    int n, sum, dp[N], coin[M], Max;    int solve() {      memset(dp, 0, sizeof(dp));      dp[0]= 1;      int half = sum / 2;        for (int i = 0; i < n; i++) {      for (int j = half - 1; j >= 0; j--)          if (dp[j])  dp[j + coin[i]] = 1;      }        for (int i = 0; i <= half; i++)      if (dp[half - i])   return i * 2;  }    int main() {      int cas;      scanf("%d", &cas);      while (cas--) {      sum = 0;      scanf("%d", &n);      memset(coin, 0, sizeof(coin));      for (int i = 0; i < n; i++) {          scanf("%d", &coin[i]);          sum += coin[i];      }      printf("%d\n", solve() + sum % 2);      }      return 0;  }  

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.