3种基础的背包问题(01背包,完全背包,多重背包),这是学习其他复杂背包问题的基础。
模板
//01背包
void ZeroOnePack(int cost,int weight)
{
for(int v=V;v>=cost;v--)
dp[v]=max(dp[v],dp[v-cost]+weight);
}
//完全背包
void CompletePack(int cost,int weight)
{
for(int v=cost;v<=V;v++)
dp[v]=max(dp[v],dp[v-cost]+weight);
}
//多重背包
//处理一个费用为cost,价值为weight,数量最多为amount的物品
void MultiplePack(int cost,int weight,int amount)
{
if(cost*amount>=V) //V为总容量
CompletePack(cost,weight);
else
{
int k=1,num=amount;
while(2*k<=num)
{
ZeroOnePack(k*cost,k*weight);
amount-=k;
k*=2;
}
ZeroOnePack(amount*cost,amount*weight);
}
}
练习:
【01背包】
51Nod_1085 背包问题 (01背包模板题)
题目203 三国志(NYOJ)(01背包 + 最短路径)
【完全背包】
【多重背包】