NOIP2001装箱问题(codevs1014)

装箱问题

题目描述   Description                   

有一个箱子容量为V(正整数,0<=V<=20000),同时有n个物品(0<n<=30),每个物品有一个体积(正整数)。

要求n个物品中,任取若干个装入箱内,使箱子的剩余空间为最小。

输入描述  Input Description              

一个整数v,表示箱子容量

一个整数n,表示有n个物品

接下来n个整数,分别表示这n 个物品的各自体积

 输出描述  Output Description              

一个整数,表示箱子剩余空间。

样例输入  Sample Input              

24

6

8

3

12

7

9

7

样例输出   Sample Output              

0

其实就是一个二维的dp。每输入一个物体a[i]就更新体积为j(a[i]≤j≤V)的背包的最大体积值即可。

 1 #include <iostream>
 2 #include <cmath>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <cstdlib>
 6 #include <algorithm>
 7 using namespace std;
 8 int a[35];
 9 int f[20101];
10 int main()
11 {
12     int n,V;
13     scanf("%d%d",&V,&n);
14     for(int i=1;i<=n;i++)
15     {
16         scanf("%d",&a[i]);
17         for(int j=V;j>=a[i];j--) f[j]=max(f[j],f[j-a[i]]+a[i]);
18     }
19     printf("%d",V-f[V]);
20     //system("pause");
21     return 0;
22 }
codevs1014
原文地址:https://www.cnblogs.com/YXY-1211/p/7120992.html