This is the question of the 01 backpack. Although the backpack won't, I still can see it. The recursive formula was not written. Later I learned it together as a DFS, so I started,
The question is to give you n stones whose weight is wn so that you can put them in two packages to see that the difference between the two is the minimum and the difference is output.
DFS code
# Include <stdio. h> int sum; int h, T; int A [1, 100]; void DFS (int x, int y) {If (x = T) {If (Y> H) H = y; return;} If (H = sum/2) return; If (Y + A [x] <= sum/2) // The equals sign must exist, this has been called for a long time, because they may be equal. DFS (x + 1, Y + A [x]); DFS (x + 1, Y);} int main () {While (scanf ("% d ", & T) = 1) {sum = 0; h = 0; For (INT I = 0; I <t; I ++) {scanf ("% d ", & A [I]); sum + = A [I];} // printf ("% d \ n", sum); DFS (0, 0 ); // printf ("% d \ n", H); printf ("% d \ n", Sum-2 * H );}}
DP code
# Include <cstring> # include <cstdio> const int Maxx = 2000010; int DP [Maxx], a [25], n; int ABS (int x) {return (x> 0 )? X:-X;} int Maxxx (int A, int B) {return (A> B )? A: B;} int main () {While (scanf ("% d", & n) = 1) {If (n = 1) {scanf ("% d", & A [0]); printf ("% d", a [0]); continue;} int sum = 0, temp, ans; for (INT I = 1; I <= N; I ++) {scanf ("% d", & A [I]); sum + = A [I]; DP [I] = 0;} temp = sum/2; DP [0] = 0; For (INT I = 1; I <= N; I ++) for (Int J = temp; j> = A [I]; j --) DP [J] = Maxxx (DP [J-A [I] + A [I], DP [J]); // you can find the maximum number in [0-temp] For (INT I = temp; I> = 0; I --) if (DP [I]! = 0) {ans = DP [I]; break;} printf ("% d \ n", ABS (Sum-2 * ans);} return 0 ;}