题目地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=3236
思路:d[i][j][k][l]表示第i种物品,第一种背包容量j,第二种背包容量k,l==0表示使用过免费,l==1表示未使用免费。
则d[i][j][k][1]=max{ d[i][j][k][1],d[i-1][j][k][0]+s.happy,d[i-1][j-s.cost][k][1]+s.happy,d[i-1][j][k-s.cost][1]+s.happy }
d[i][j][k][0]=max{ d[i][j][k][0],d[i-1][j-s.cost][k][0]+s.happy,d[i-1][j][k-s.cost][0]+s.happy)
先对必须选择的物品做一次背包,若结果小于必须选择的物品happy值之和,则无解。否则,继续对非必须选择的物品做背包,注意状态转移时先判断当前值是否大于必须选择物品happy值之和(即必须选择物品全部选择后)。
注意:j、k的值应循环到0,而不是s[i].happy(j为0时,k仍可能继续选,k为0时同理)。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define debu
using namespace std;
const int maxn=350;
struct Node
{
int cost,happy;
};
int v1,v2,n,ans;
int d[550][55][2];
Node s0[maxn],s1[maxn];
int main()
{
#ifdef debug
freopen("in.in","r",stdin);
#endif // debug
int cas=0;
while(scanf("%d%d%d",&v1,&v2,&n)==3&&(v1||v2||n))
{
int sum=0,tot0=0,tot1=0;
memset(d,0,sizeof(d));
for(int i=0; i<n; i++)
{
int p,h,id;
scanf("%d%d%d",&p,&h,&id);
if(id==1)
{
s1[tot1].cost=p;
s1[tot1++].happy=h;
sum+=h;
}
else
{
s0[tot0].cost=p;
s0[tot0++].happy=h;
}
}
for(int i=0; i<tot1; i++)
{
for(int j=v1; j>=0; j--)
{
for(int k=v2; k>=0; k--)
{
d[j][k][1]=max(d[j][k][1],d[j][k][0]+s1[i].happy);
if(j>=s1[i].cost)
{
d[j][k][1]=max(d[j][k][1],d[j-s1[i].cost][k][1]+s1[i].happy);
d[j][k][0]=max(d[j][k][0],d[j-s1[i].cost][k][0]+s1[i].happy);
}
if(k>=s1[i].cost)
{
d[j][k][0]=max(d[j][k][0],d[j][k-s1[i].cost][0]+s1[i].happy);
d[j][k][1]=max(d[j][k][1],d[j][k-s1[i].cost][1]+s1[i].happy);
}
}
}
}
if(d[v1][v2][1]<sum&&d[v1][v2][0]<sum) ans=-1;
else
{
for(int i=0; i<tot0; i++)
{
for(int j=v1; j>=0; j--)
{
for(int k=v2; k>=0; k--)
{
if(d[j][k][0]>=sum)
d[j][k][1]=max(d[j][k][1],d[j][k][0]+s0[i].happy);
if(j>=s0[i].cost)
{
if(d[j-s0[i].cost][k][1]>=sum)
d[j][k][1]=max(d[j][k][1],d[j-s0[i].cost][k][1]+s0[i].happy);
if(d[j-s0[i].cost][k][0]>=sum)
d[j][k][0]=max(d[j][k][0],d[j-s0[i].cost][k][0]+s0[i].happy);
}
if(k>=s0[i].cost)
{
if(d[j][k-s0[i].cost][1]>=sum)
d[j][k][1]=max(d[j][k][1],d[j][k-s0[i].cost][1]+s0[i].happy);
if(d[j][k-s0[i].cost][0]>=sum)
d[j][k][0]=max(d[j][k][0],d[j][k-s0[i].cost][0]+s0[i].happy);
}
}
}
}
ans=d[v1][v2][1];
}
printf("Case %d: %d\n\n",++cas,ans);
}
return 0;
}
原文:http://blog.csdn.net/wang2147483647/article/details/52280629