装箱问题(01背包)

来源:互联网 发布:通用域名查询 编辑:程序博客网 时间:2024/05/21 22:52

装箱问题

描述 Description
有一个箱子容量为v(正整数,o≤v≤20000),同时有n个物品(o≤n≤30),每个物品有一个体积 (正整数)。要求从 n 个物品中,任取若千个装入箱内,使箱子的剩余空间为最小。

输入格式 Input Format
第一行,一个整数,表示箱子容量;
第二行,一个整数,表示有n个物品;
接下来n行,分别表示这n个物品的各自体积。

输出格式 Output Format
一个整数,表示箱子剩余空间。

样例输入 Sample Input
24
6
8
3
12
7
9
7

样例输出 Sample Output

0

#include <iostream>#include <algorithm>#include <cstring>using namespace std;int main(int ac,char *av[]){    int dp[20001],max_v,n,tmp,i,j;    while(cin>>max_v>>n)    {    memset(dp,0,sizeof(dp));    for(i=1;i<=n;i++)    {        cin>>tmp;        for(j=max_v;j>=tmp;j--)         {          dp[j]=max(dp[j],dp[j-tmp]+tmp);         }    }    cout<<max_v-dp[max_v]<<endl;    }    return 0;}


原创粉丝点击