题目链接
首先,50分做法:
把原先的多重背包二进制拆分为01背包
100分做法:
考虑优化
设置状态 f [ i ] [ j ] f[i][j] f[i][j] 表示到第 i i i 个时总体积为 j j j 的最大价值,那么我们只要求 f [ d i − 1 ] [ e i ] f[d_i-1][e_i] f[di−1][ei] 就可以把第 d i d_i di 个给忽略掉啦,然后后半段只要从后往前做预处理,然后再来个for循环合并答案就可以了。
code:(有点丑,慎看)
#include
using namespace std;
#define s1(a,n) sort(a+1,a+n+1)
#define s2(a,n) sort(a+1,a+n+1,mycmp)
#define ll long long
#define sg string
#define st struct
#define f1(i,l,r) for(int i=l;i<=r;++i)
#define f2(i,r,l) for(int i=r;i>=l;--i)
#define f3(i,a,b) for(int i=a;i;i=b)
#define me(a,b) memset(a,b,sizeof(a))
#define sf scanf
#define pf printf
#define fo freopen
const int maxn=1000+10;
int n,q,ans,a[maxn],b[maxn],c[maxn],d,e,f[maxn][maxn]={},g[maxn][maxn]={},l,r,k;
bool mycmp(int x,int y){
return x>y;
}
void init(){
sf("%d",&n);
f1(i,1,n) sf("%d %d %d\n",&a[i],&b[i],&c[i]);
}
void work(){
f2(i,n,1){
l=1;
r=c[i];
f1(j,0,1000) g[i][j]=g[i+1][j];
while(l<=r){
k=l*a[i];
f2(j,1000,k) g[i][j]=max(g[i][j],g[i][j-k]+l*b[i]);
r-=l;
l*=2;
}
if(r>0){
k=r*a[i];
f2(j,1000,k) g[i][j]=max(g[i][j],g[i][j-k]+r*b[i]);
}
}
f1(i,1,n){
l=1;
r=c[i];
f1(j,0,1000) f[i][j]=f[i-1][j];
while(l<=r){
k=l*a[i];
f2(j,1000,k) f[i][j]=max(f[i][j],f[i][j-k]+l*b[i]);
r-=l;
l*=2;
}
if(r>0){
k=r*a[i];
f2(j,1000,k) f[i][j]=max(f[i][j],f[i][j-k]+r*b[i]);
}
}
}
void print(){
sf("%d",&q);
f1(i,1,q){
ans=0;
sf("%d %d\n",&d,&e);
f1(j,0,e) ans=max(ans,f[d][j]+g[d+2][e-j]);
pf("%d\n",ans);
}
}
int main(){
fo("bag.in","r",stdin);
fo("bag.out","w",stdout);
init();
work();
print();
return 0;
}