This question has plagued me for a long time. The original idea was correct, but I found a reason to deny myself. I believe that the first feeling is good. First find the maximum price mx, and then let the other do 0/1 backpack, let its total approach dp [M-5], which should be well understood, the most available food is dp [M-5] + mx, so the balance is m-dp [M-5]-mx; however, to judge m <5 is not to buy it ).
Code:
[Cpp]
# Include <iostream>
# Include <algorithm>
Using namespace std;
Int a [1005], dp [1005];
Int main ()
{
Int n, m, mx, I, j, pt;
While (scanf ("% d", & n ){
Mx = 0; pt = 0;
For (I = 1; I <= n; I ++ ){
Scanf ("% d", & a [I]);
If (a [I]> mx) {// select the maximum value
Mx = a [I];
Pt = I;
}
}
Scanf ("% d", & m );
Int temp = a [pt];
A [pt] = a [n];
A [n] = a [pt];
If (m> = 5 ){
Memset (dp, 0, sizeof (dp ));
For (I = 1; I <n; I ++) // use the remaining n-1 TO MAKE A 0/1 backpack.
For (j = M-5; j> = a [I]; j --)
Dp [j] = max (dp [j], dp [j-a [I] + a [I]);
Printf ("% d \ n", m-dp [M-5]-mx );
}
Else
Printf ("% d \ n", m );
}
Return 0;
}
Author: aacm1992