每組物品加入了箱子的限制,如果要買改組物品,就必須先買箱子
考慮第i組物品時,前i-1組的最優值已經知道,假設總容量爲V,改組的箱子的代價爲p,那麼如果我們要買該組物品,可用容量就只有V-p,所以,我們先用tmp數組記錄前i-1階段容量範圍在[0,V-p]這個範圍內的最優值,對應加上箱子的代價p的[p,V]這個區間,然後在這個範圍內對改組物品做01揹包,再去更新dp值
代碼:
#include<iostream>
#include<memory.h>
#include<string>
#include<cstdio>
#include<algorithm>
#include<math.h>
#include<stack>
#include<queue>
#include<vector>
#include<map>
using namespace std;
const int MAX=100005;
int dp[MAX],tmp[MAX];
int main()
{
int i,j,k,l,V,n,vv,cnt,w,v;
while(scanf("%d%d",&n,&V)!=EOF)
{
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
{
scanf("%d%d",&vv,&cnt);
for(j=0;j+vv<=V;j++)
tmp[j+vv]=dp[j];
for(l=1;l<=cnt;l++)
{
scanf("%d%d",&w,&v);
for(j=V;j>=w+vv;j--)
{
tmp[j]=max(tmp[j],tmp[j-w]+v);
}
}
for(j=vv;j<=V;j++)
{
dp[j]=max(dp[j],tmp[j]);
}
}
printf("%d\n",dp[V]);
}
return 0;
}