装箱问题
Description
有一个箱子容量为 V (正整数, 0≤V≤20000 ),同时有 n 个物品( 0<n≤30 ,每个物品有一个体积(正整数,且保证n个物品体积和不超过int)。
要求 n 个物品中,任取若干个装入箱内,使箱子的剩余空间为最小。
Input
1 个整数,表示箱子容量
1 个整数,表示有 n 个物品
接下来 n 行,分别表示这 n 个物品的各自体积
Output
1个整数,表示箱子剩余空间。
Sample Input 1
24
6
8
3
12
7
9
7
Sample Output 1
0
Source
丁金峰
这个题就是简单的01背包变形,把每个物品都当成体积和价值都相等。然后在体积允许的范围内去选价值最大的就好。
AC代码:
#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
int a[50],dp[20010];
int main()
{
int c,n;
scanf("%d%d",&c,&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=n;i++)
{
for(int j=c;j>=a[i];j--)
{
dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
}
}
printf("%d\n",c-dp[c]);
return 0;
}