装箱问题动态规划Java实现
import java.util.Scanner;
public class Extend {
public static void main(String[] args) {
int[] w = new int[30];
Scanner sc = new Scanner(System.in);
int num, bag;
bag = sc.nextInt();
num = sc.nextInt();
int[][] dp = new int[num + 1][bag + 1];
w[0] = 0;
for (int i = 0; i < num; i++) {
w[i + 1] = sc.nextInt();
}
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
dp[i][j] = 24;
}
}
for (int i = 1; i <= num; i++) {
for (int j = 1; j <= bag; j++) {
if (j < w[i]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = min(dp[i - 1][j], dp[i-1][j - w[i]] - w[i]);
}
}
}
sc.close();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
System.out.println(dp[dp.length - 1][dp[1].length - 1]);
}
public static int min(int i, int j) {
if (i > j)
return j;
else {
return i;
}
}
}
/*
24
6
8
3
12
7
9
7
*/
代码是背包问题改过来的。所以bag,w这两个变量命名不太规范。
bag指箱剩余容量
w指物品体积。
底部为测试样例,结果应该为0。