Uva562-Dividing coins (01 backpack)
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
# Include
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 way, the result is that only the I-1 coin in the front 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, sum-2 * I);} return 0 ;}