vjudge Bone Collector 01背包

165 阅读3分钟

思路:

思路个屁啊,这就是简单的01背包模板啊混蛋,照着模板抄都能做出来

最核心的代码就三行

for(int i=0;i<n;i++)// 外层循环骨头的个数
    for(int j=tot;j>=w[i];j--)//tot:背包总大小,w[i],这个骨头的重量
        dp[j] = max(dp[j],dp[j-w[i]]+v[i]);// 就是选这个,还是不选这个,

最后dp[tot]就是所求的最大值

说到01背包了,还有几个变种

  1. 多个属性的01背包

    不只是只有weight和value,可能还有其他的属性,参考 NASA的食物计划

    解法也很简单,多了一个限制条件,那么我们dp数组变成二维,然后多一重循环就好了

    // 作者: 龘龘龘龘龘龘
    #include<iostream>
    using namespace std;
    int a[51],b[51],c[51];//题目中有三个变量就设三个变量;
    int f[501][501];
    int main()
    {
        int i,j,l,m,n,k;
        cin>>m>>n>>k;//输入
        for(i=1;i<=k;i++)
          cin>>a[i]>>b[i]>>c[i];//表示每个食品的体积质量和卡路里;
        for(i=1;i<=n;i++)
          for(j=m;j>=a[i];j--)
            for(l=n;l>=b[i];l--)//记住j和l不能同时写在一起,刚开始我就写在一起,调了1分钟才发现
              f[j][l]=max(f[j][l],f[j-a[i]][l-b[i]]+c[i]);//公式;直接套用就是的
          cout<<f[m][n];//输出最优解
          return 0;
    }
    
  2. 我记得还有一个叫做分组背包的,但是目前还没写过这种题,先不管了

本题注水代码

ps: dp数组一定要初始化,一定要初始化,一定要初始化,md,坑死我了

#include<iostream>
#include<algorithm>
typedef long long LL;

using namespace std;

LL w[10000+10],v[10000+10],dp[10000+10];
int n,tot;
/*
    有限背包
    水水水
*/
int main(){
   //  freopen("data.in","r",stdin);
    int t;
    cin>>t;
    while(t--){
        cin>>n>>tot;
        for(int i=0;i<=tot;i++)
            dp[i] = 0;
        for(int i=1;i<=n;i++)
            cin>>v[i];
        for(int i=1;i<=n;i++)
            cin>>w[i];
        for(int i=1;i<=n;i++){
            for(int j=tot;j>=w[i];j--){
                    dp[j] = max(dp[j],dp[j-w[i]]+v[i]);
            }
        }
        cout<<dp[tot]<<endl;
    }
    return 0;
}

题面:

Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave … The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?

img

Input

The first line contain a integer T , the number of cases. Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.

Output

One integer per line representing the maximum of the total value (this number will be less than 2 31).

Sample Input

1
5 10
1 2 3 4 5
5 4 3 2 1

Sample Output

14