题目描述 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
数据范围及提示 Data Size & Hint
分析:
背包型动态规划问题,类似于背包容量和背包中物品价值二者相等的一般背包问题。
对于每个物品 i ,有存放和不存放两种情况。当前箱子容量剩余 j 的时候,若放入 i 放入,则为spaceV[j-goodsV[i]],若 i 不放入,则为dp[i],因此,状态转移方程为:spaceV[j] = Math.max(spaceV[j], spaceV[ j - goodsV[i]] + goodsV[i])。
代码如下:
public class SpaceTest{
//箱子容量
private static Integer v;
//物品个数
private static Integer n;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入背包容量V:");
v = scanner.nextInt();
System.out.println("请输入物品数量:");
n = scanner.nextInt();
//每个商品占用空间
int[] goodsV = new int[n+1];
//加入i哥商品后背包剩余空间
int[] spaceV = new int[v+1];
System.out.println("请输入各物品体积:");
for (int i = 1; i <= n; i++){
goodsV[i] = scanner.nextInt();
spaceV[i] = 0;
}
scanner.close();
for (int i = 1; i <= n; i++){
for (int j = v; j >=goodsV[i]; j--){
spaceV[j] = Math.max(spaceV[j], spaceV[j-goodsV[i]] + goodsV[i]);
}
}
System.out.println(v - spaceV[v]);
}
}
题目来源:http://codevs.cn/problem/1014/
另外可以学习一下下面的文章:背包九讲 2.0