动态规划-多重背包(取的次数有限制)

   #include
#include
using namespace std;
int v[6002], w[6002], s[6002];
int f[6002];
int n, m;
//多重背包 
int main()
{
    scanf("%d%d",&n,&m);
    for (int i = 1; i <= n; i++)
        scanf("%d%d%d",&v[i],&w[i],&s[i]);
    for (int i = 1; i <= n; i++)
       for (int j = m; j >= 0; j--)
          for (int k = 0; k <= s[i]; k++)
          {
               if (j-k*v[i]<0) break;
               f[j] = max(f[j],f[j-k*v[i]]+k*w[i]);
          }
    printf("%d\n",f[m]);
    return 0;
} 
//优化
#include
#include
using namespace std;
int v[10001],w[10001];
int f[6001];
int n,m,n1;
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        int x,y,s,t=1;
        scanf("%d%d%d",&x,&y,&s);
        while (s>=t) 
        {
            v[++n1]=x*t;
            w[n1]=y*t;
            s-=t;
            t*=2;
        }
        v[++n1]=x*s;
        w[n1]=y*s;                             //把s以2的指数分堆:1,2,4,…,2^(k-1),s-2^k+1,
    }
for(int i=1;i<=n1;i++)
        for(int j=m;j>=v[i];j--)
           f[j]=max(f[j],f[j-v[i]]+w[i]); 
    printf("%d\n",f[m]);
    return 0;
} 

转载于:https://www.cnblogs.com/mch5201314/p/10324849.html

你可能感兴趣的:(动态规划-多重背包(取的次数有限制))