Uploaded by
Userid=acm_%e8%b5%b5%e9%93%ad%e6%b5%a9 "style=" text-decoration:none; Color:rgb (55,119,188) ">acm_ Zhao Minhao
Dynamic Programming Classic problems, there are several ideas, the best idea of the 01 knapsack problem of the second cycle of the order of a change, we get the best solution of the complete backpack;
This algorithm uses a one-dimensional array, first look at the pseudocode: (referring to the Backpack 9 said inside content)
For I=1..N
For V=0..V
F[v]=max{f[v],f[v-cost]+weight}
You will find that this pseudo-code is different from the pseudo-code of the 01 backpack only having a V loop order. Why is such a change feasible? First think about why P01 in accordance with V=V. 0 in reverse order to cycle.
This is due to the fact that the state in the first cycle of the f[i][v] is recursive by state f[i-1] [V-c[i]]. Other words. This is to ensure that each item is selected only once. Ensure that, in considering the strategy of "Select Item I", it is based on a sub-result (F[i-1][v-c[i]) that has not been selected for article I items. The full backpack now features an unlimited selection of items for each item. Therefore, when considering the strategy of "adding an item I", I am going to need a sub-result that may have been selected in item I (F[i][v-c[i]), so that it can and must be cycled in the order of V=0..V. This is the reason why this simple procedure is set up.
It is worth mentioning that the order of the two-layer for loop can be reversed in the pseudo-code above. This conclusion may lead to optimization of the algorithm's time constants.
This algorithm can also be derived from other ideas.
Like what. The state transfer equation for solving f[i][v-c[i] in the basic idea is explicitly written, substituting the original equation, and the equation can be found to be equivalent to the form:
f[i][v]=max{f[i-1][v],f[i][v-c[i]]+w[i]}
This equation is implemented with a one-dimensional array, and the pseudo-code above is obtained.
The following is the Code of implementation, the code for dynamic programming is very easy, and the most important is mastering the state transition equation:
#include <cstdio> #include <cstring> #define MAX (b) a>b?A:bconst int maxn=50001;int Dp[maxn];int main () { int n,m,v,i,j,c,w; scanf ("%d", &n); while (n--) { memset (dp,-10000,sizeof (DP)), it is also important to note that in the 01 backpack is initialized to 0, here to initialize a larger negative number dp[0]=0;//here also pay attention to, Without this it would WA scanf ("%d%d", &m,&v); for (i=1;i<=m;i++) { scanf ("%d%d", &c,&w); for (j=c;j<=v;j++) Dp[j]=max (dp[j],dp[j-c]+w);//The state transfer equation is also consistent with 01 Knapsack } if (dp[v]<0) printf ("no\n") ; else printf ("%d\n", Dp[v]); } return 0;}