[动态规划] 洛谷P1049 装箱问题 (01背包)

题目

LP1049

思路

本题唯一难度在于发现,问题的隐藏价值W[i] = V[i]。分清消耗量与价值量,并且有时它们甚至还会相等。
剩下的就是裸01背包

代码

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#define _for(i,a,b) for(int i = (a); i<(b); i++)
#define _rep(i,a,b) for(int i = (a); i<=(b); i++)
using namespace std;

const int maxx = 20000+100;
int n, C, d[maxx];

int main(){
    scanf("%d%d",&C,&n);
    int V;
    _rep(i,1,n){
        scanf("%d",&V);
        for(int j = C; j>=0; j--)
            if(j >= V)
                d[j] = max(d[j],d[j-V]+V);
    }
    printf("%d\n",C-d[C]);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/icecab/article/details/80768374