01背包+完全背包+多重背包模板

来源:互联网 发布:windows一键还原软件 编辑:程序博客网 时间:2024/05/21 16:22

n种物品,容量为v,第i件费用为c[i],价值为w[i]

1.01背包

方程:

f[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]}

模板:

  1. void zeropack(int cost,int weight)  
  2. {  
  3.     for(int i=v;i>=cost;i--)  
  4.         dp[i]=max(dp[i-cost]+weight,dp[i]);  
  5. }  
  6. for(int i=1;i<=n;i++)
  7.    zeropack(c[i],w[i]);

2.完全背包

f[i][v]=max{f[i-1][v-k*c[i]]+k*w[i]|0<=k*c[i]<=v}

  1. void completepack(int cost,int weight)  
  2. {  
  3.     for(int i=cost;i<=V;i++)  
  4.         dp[i]=max(dp[i-cost]+weight,dp[i]);  
  5. }  

3.多重背包

f[i][v]=max{f[i-1][v-k*c[i]]+k*w[i]|0<=k<=n[i]}

num 为限制几个

  1. void multipack(int cost,int weight,int num)  
  2. {  
  3.     if(num*cost>=V)  
  4.     {  
  5.         completepack(cost,weight);  
  6.         return;  
  7.     }  
  8.     int k=1;  
  9.     while(k<num)  
  10.     {  
  11.         zeropack(k*cost,k*weight);  
  12.         num-=k;  
  13.         k*=2;  
  14.     }  
  15.       
  16.     zeropack(cost*num,weight*num);  
  17. }  



0 0