The idea is: first if the m<5, direct output, if m>5, then take out 5 yuan to buy the most expensive things, so the backpack capacity has become m-5, the number of goods for the n-1 0/1 knapsack problem.
The state transition equation for this problem is: Dp[j]=max{dp[j],dp[j-price[i]]+price[i]},dp[j] represents the purchase of the first item I, the budget is J when the maximum cost.
1#include"iostream"2#include"stdio.h"3#include"Cmath"4#include"algorithm"5#include"Queue"6#include"string.h"7 using namespacestd;8 #defineMX 10059 intPRICE[MX];Ten intDP[MX]; One intMain () A { - inti,j,k,n,m; - while(cin>>n,n) the { - for(i=1; i<=n;i++) -Cin>>Price[i]; -Cin>>m; +Sort (price+1, price+n+1);//The price of items in the order of small to large - if(m<5) {cout<<m<<endl;Continue;} +Memset (DP,0,sizeof(DP));//Initialize the value of the backpack A //Dp[j] Represents the biggest cost of buying a pre-I -item with a budget of J at for(i=1; i<=n-1; i++) - for(j=m-5; j>=price[i];j--) - if(Dp[j]<dp[j-price[i]]+price[i]) dp[j]=dp[j-price[i]]+Price[i]; -cout<<m-price[n]-dp[m-5]<<Endl; - } - return 0; in}
View Code
HDU Rice Card