您的位置:首页 > 其它

混合背包+多重背包的二进制优化

2013-10-27 21:40 465 查看
#include <iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#define LL long long
using namespace std;

const int maxn = 200000+10;
const int maxc = 1e9+7;

LL f[maxn];
int v[210],w[210],m[210];
int n,V;

void ZeroOnePack(int cost,int weight)//0-1背包
{
for(int j=V;j>=cost;j--)
f[j]=max(f[j],f[j-cost]+weight);
}
void CompletePack(int cost ,int weight)//完全背包
{
for(int j=cost;j<=V;j++)
f[j]=max(f[j],f[j-cost]+weight);
}
void MultiPack(int cost,int weight,int amount)//多重背包
{
if(cost*amount>=V)
{
CompletePack(cost,weight);
return;
}
int k=1;
while(k<amount)
{
ZeroOnePack(k*cost,k*weight);
amount-=k;
k*=2;
}
ZeroOnePack(amount*cost,amount*weight);
}

int main()
{
cin>>n>>V;
memset(f,0,sizeof(f));
for(int i=1;i<=n;i++)
scanf("%d %d %d",&v[i],&w[i],&m[i]);
for(int i=1;i<=n;i++)
{
if(m[i]==1)//0-1背包
{
ZeroOnePack(v[i],w[i]);
}
else if(m[i]==-1)//完全背包
{
CompletePack(v[i],w[i]);
}
else //多重背包
{
MultiPack(v[i],w[i],m[i]);
}
}
cout<<f[V]<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: