题目链接
https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1086
题意
有N种物品,每种物品的数量为C1,C2……Cn。从中任选若干件放在容量为W的背包里,每种物品的体积为W1,W2……Wn(Wi为整数),与之相对应的价值为P1,P2……Pn(Pi为整数)。求背包能够容纳的最大价值。
题解
转化为01背包。
有5件第一种物品,转化成三种:将1个打包作为一种,将2个打包作为一种,将2个打包作为一种。
有8件第二种物品,转化为四种:将1个打包作为一种,将2个打包作为一种,将
个打包作为一种,将1个打包作为一种。
规律:
有Ci件第k种物品,可以分成log2(Ci)+1种.
原N最大100,Ci最大200,最多可以形成800种左右。背包容量W最大50000,时间复杂度800*50000可以接受。
AC代码
#include <bits/stdc++.h>
using namespace std;
const int maxn=5e4+7;
struct node
{
int v,w;
node(){}
node(int v,int w):v(v),w(w){}
}a[1000];
int cnt;
int dp[maxn];
int main()
{
int n,W;
while(~scanf("%d%d",&n,&W))
{
cnt=0;
int x,p,c;
for(int j=1;j<=n;j++)
{
scanf("%d%d%d",&x,&p,&c);
int i=0,cc=c;
while(c)
{
a[++cnt]=node((1<<i)*x,(1<<i)*p);
c>>=1;
i++;
}
int tmp=cc-(1<<(i-1))+1;
// cout<<"tmp="<<tmp<<endl;
a[cnt]=node(x*(tmp),p*tmp);
}
//for(int i=1;i<=cnt;i++)
// printf("hhh%d %d\n",a[i].v,a[i].w);
memset(dp,0,sizeof(dp));
for(int i=1;i<=cnt;i++)
{
for(int j=W;j>=a[i].v;j--)
dp[j]=max(dp[j],dp[j-a[i].v]+a[i].w);
}
printf("%d\n",dp[W]);
}
return 0;
}