Two methods:
The first type is to use half of the total number as a backpack. The total number-2 * is the maximum number;
Type 2: Deep Search;
ZB's birthday restrictions: 3000 MS | memory limit: 65535 KB difficulty: 2
-
-
Description
-
Today is the birthday of the ACM team member ZB on March 13, lunar July 5. ZB is training in Wuhan with C Xiaojia and never. He wanted to buy something for the two brothers to celebrate his birthday. After investigation, ZB found that C Xiaojia and never both liked to eat watermelon, and they were a bunch of them, ZB immediately decided to buy a pile of watermelon. When he was about to give the watermelon to C Xiaojia and never, he encountered a problem. Never and C Xiaojia were not in the same place. They could only divide the watermelon into two heaps for them, to be fair to everyone, he wants to minimize the weight difference between the two stacks. The weight of each watermelon is known. Can you help him?
-
-
Input
-
-
Multiple groups of test data (<= 1500 ). Data ends with EOF
The first line inputs the number of watermelons N (1 ≤ n ≤ 20)
The second row has n numbers, W1 ,..., Wn (1 ≤ wi ≤ 10000) represents the weight of each watermelon respectively
-
-
Output
-
-
Quality difference after the output is divided into two heaps
-
-
Sample Input
-
-
55 8 13 27 14
-
-
Sample output
-
-
3
Code:
# Include <stdio. h ># include <cstring> int DP [100005]; int main () {<span style = "white-space: pre"> </span> int N, s [25], I, j; <span style = "white-space: pre"> </span> while (scanf ("% d", & N) = 1) {<span style = "white-space: pre"> </span> int sum = 0; <span style = "white-space: pre "> </span> for (I = 0; I <n; I ++) {<span style =" white-space: pre "> </span> scanf (" % d ", & S [I]); <span style =" white-space: pre "> </span> sum + = s [I]; <span style =" white-space: pre "> </SPAN >}< span style =" white-space: pre "> </span> memset (DP, 0, sizeof (DP )); <span style = "white-space: pre"> </span> for (I = 0; I <n; I ++) {<span style = "white-space: pre "> </span> for (j = sum/2; j> = s [I]; j --) <span style =" white-space: pre "> </span> If (DP [J] <DP [J-s [I] + s [I]) DP [J] = DP [J-s [I] + s [I]; <span style = "white-space: pre "> </SPAN >}< span style =" white-space: pre "> </span> printf (" % d \ n ", sum-2 * DP [sum/2]); <span style = "white-space: pre"> </SPAN >}< span style = "white-space: pre "> </span> return 0 ;}
Second (Deep Search ):
# Include <cstdio> # include <cstdlib> # define INF 0x7ffffint all, min; int s [25]; void DFS (INT sum, int right) {If (right <0) return; If (ABS (all-2 * sum) <min) min = ABS (all-2 * sum); DFS (sum + s [right], right-1 ); DFS (sum, right-1);} int main () {int N; while (scanf ("% d", & n) = 1) {min = inf; all = 0; For (INT I = 0; I <n; I ++) {scanf ("% d", & S [I]); all + = s [I];} DFS (0, n-1); printf ("% d \ n", min );}}