现在的位置: 首页 > 综合 > 正文

hdu 2191 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活(多重背包)

2018年01月12日 ⁄ 综合 ⁄ 共 852字 ⁄ 字号 评论关闭

分析:很基本的 多重背包,套用背包九讲的思想和公式,化为ZeroOnePack和CompletePack做的,详细的分析见背包九讲

复杂度为O(V*Σlog n[i]

#include<iostream>

#include<cstdio>
using namespace std;
int dp[1100],p[1100],w[1100],c[1100];
int n,m;
void ZeroOnePack(int cost,int weight)
{
for(int i=n;i>=cost;i--)
if(dp[i]<dp[i-cost]+weight)
dp[i]=dp[i-cost]+weight;
}
void CompletePack(int cost ,int weight)
{
for(int i=cost;i<=n;i++)
if(dp[i]<dp[i-cost]+weight)
dp[i]=dp[i-cost]+weight;
}
void  MultiplePack(int cost,int weight,int amount)
{
if(cost*amount>=n)
{
CompletePack(cost,weight);
   return ;
}
else
{
int k=1;
while(k<amount)
{
ZeroOnePack(k*cost,k*weight);
amount-=k;
k*=2;
}
ZeroOnePack(amount*cost,amount*weight);
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
for(int i=1;i<=m;i++)
scanf("%d %d %d",&p[i],&w[i],&c[i]);
memset(dp,0,sizeof(dp));
        for(int i=1;i<=m;i++)
MultiplePack(p[i],w[i],c[i]);
printf("%d\n",dp[n]);
}
system("pause");
return 0;
}

抱歉!评论已关闭.