题目:http://poj.org/problem?id=1276

多重背包模板题,没什么好说的,但是必须利用二进制的思想来求,否则会超时,二进制的思想在之前的博客了有介绍,在这里就不多说了。

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <math.h>
using namespace std;
int V,n,w[20],cnt[20],dp[1000010];
void com(int v)
{
    for(int i=v; i<=V; i++)
    {
        dp[i]=max(dp[i],dp[i-v]+v);
    }
    return ;
}
void one(int v)
{
    for(int i=V;i>=v;i--)
    {
        dp[i]=max(dp[i],dp[i-v]+v);
    }
    return ;
}
int main()
{
    while(scanf("%d",&V)!=EOF)
    {
        scanf("%d",&n);
        for(int i=0; i<n; i++)
        {
            scanf("%d%d",&cnt[i],&w[i]);
        }
        memset(dp,0,sizeof(dp));
        for(int i=0; i<n; i++)
        {
            if(cnt[i]==0) continue;
            if(cnt[i]*w[i]>=V)
            {
                com(w[i]);
            }
            else
            {
                int t=1;
                while(t<cnt[i])
                {
                   one(w[i]*t);
                   cnt[i]-=t;
                   t<<=1;
                }
                one(w[i]*cnt[i]);
            }
        }
        printf("%d\n",dp[V]);
    }
    return 0;
}

 

相关文章:

  • 2021-09-18
  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
  • 2021-05-02
  • 2022-12-23
  • 2021-10-15
  • 2021-10-07
猜你喜欢
  • 2022-12-23
  • 2021-06-05
  • 2022-01-24
  • 2022-12-23
  • 2021-12-31
  • 2021-06-10
  • 2022-01-22
相关资源
相似解决方案