Uva562-dividing coins (01 backpack)

Source: Internet
Author: User

Question: uva562-dividing coins (01 backpack)


N coins are given. Each coin has a corresponding face value. Divide the coins into two parts to obtain the minimum difference between the two parts.


Solution: first obtain the money (0, 1 backpack) that these coins can collect, and then start from sum (the sum of these coins)/2 to find out whether the value can be made up by these coins. It should be noted that it can also be composed of the First n coins.


Code:

# Include <cstdio> # include <cstring> const int n = 105; const int maxn = N * 500; int V [N]; bool DP [maxn]; int N, SUM; void Init () {memset (DP, false, sizeof (DP); DP [0] = true; For (INT I = 0; I <N; I ++) for (Int J = sum; j> = V [I]; j --) {If (DP [J-V [I]) DP [J] = true; // DP [J] = DP [J-V [I]; in this case, the I-1 coin in front of it constitutes J. } Int main () {int t; scanf ("% d", & T); While (t --) {scanf ("% d", & N ); sum = 0; For (INT I = 0; I <n; I ++) {scanf ("% d", & V [I]); sum + = V [I];} Init (); int I; for (I = sum/2; I> = 0; I --) if (DP [I]) break; printf ("% d \ n", Sum-2 * I);} 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.