This problem has a small point, is less than 5 block can not be selected, more than 5, it is optional, so in the initial conditions to determine the remaining amount of money, and then if greater than 5, then it is necessary to use the idea of greed, as long as greater than or equal to 5, the first to find the largest, and then the rest of the backpack Such a result must be optimal. Because the biggest one will be selected, how much money left is irrelevant, with the backpack can get the rest of the best solution, so the final is the best solution
The code is as follows
1#include <cstdio>2#include <cstring>3#include <algorithm>4 using namespacestd;5 Const intN =1006;6 intDp[n];7 intValue[n];8 intMain ()9 {Ten intN; One while(SCANF ("%d", &n) = =1, N) A { - for(inti =0; I < n; i++) -scanf"%d", &value[i]); the intv; -scanf"%d", &v); - if(V <5)//if the initial conditions are not met, the direct output amount - { +printf"%d\n", v); - Continue; + } ASort (value, value + N);//Sort atMemset (DP,0,sizeof(DP)); - //01 Backpack - for(inti =0; I < n-1; i++) - { - for(intj = V-5; J >= Value[i]; j--) - if(Dp[j] < Dp[j-value[i]] +Value[i]) inDP[J] = Dp[j-value[i]] +Value[i]; - } toprintf"%d\n", V-dp[v-5]-Value[n-1]); + } - return 0; the}
HDU-2546 Rice Card (01 backpack + greedy)