Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 2546
Solution: to minimize the balance on the card after a meal purchase, but the restriction is that the balance on the card must be no less than 5 yuan to buy meals, in this case, using a 01 backpack is definitely wrong and cannot get the optimal solution. We know that to minimize the balance on the card, we need to buy the most expensive dish at the end, so we can use the 01 backpack to solve the remaining n-1 vegetables.
# Include <iostream> using namespace STD; # define max (A, B) A> B? A: bint W [1005]; int f [10005]; int zerooneback (int w [], int N, int momey, int p) {for (INT I = 1; I <= N; I ++) {if (I! = P) {for (Int J = momey; j> = W [I]; j --) {f [J] = max (F [J], f [J-W [I] + W [I]) ;}} return f [momey];} int main () {int I, P, Max; int M, N; while (CIN> N, N) {max = 0; memset (F, 0, sizeof (f); for (I = 1; I <= N; I ++) CIN> W [I]; CIN> m; for (I = 1; I <= N; I ++) {If (W [I]> MAX) {P = I; max = W [I] ;}} if (M <5) cout <m <Endl; else {int S = zerooneback (W, N, M-5, P); cout <m-S-max <Endl ;}} return 0 ;}