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