多重背包代码

来源:互联网 发布:网络进度计划波浪线 编辑:程序博客网 时间:2024/06/03 08:53
#include <cstdio>#include <algorithm>#include <iostream>using namespace std;const int maxn=10000+10;int dp[maxn],p[maxn],h[maxn],c[maxn];int t,n,m;void ZeroOnePack(int cost,int weight,int exceed){for(int i=exceed;i>=cost;i--){dp[i]=max(dp[i],dp[i-cost]+weight);}}void CompletePack(int cost,int weight,int exceed){for(int i=cost;i<=exceed;i++){dp[i]=max(dp[i],dp[i-cost]+weight);}}//p:价格 h:重量 c:袋数  m:金额 void MultiplePack(){fill(dp,dp+n+1,0);for(int i=1;i<=n;i++){    if(p[i]*c[i]>=m)    CompletePack(p[i],h[i],m);      else    {    int k=1;    while(k<c[i])    {    ZeroOnePack(k*p[i],k*h[i],m);    c[i]-=k;    k<<=1;}ZeroOnePack(c[i]*p[i],c[i]*h[i],m);}} cout<<dp[m]<<endl;}int main(){            cin>>t;      while(t--)      {        cin>>m>>n;        for(int i=1;i<=n;i++)        cin>>p[i]>>h[i]>>c[i];        MultiplePack();          }}

0 0
原创粉丝点击