/* * 钢条切割方案自底向上 */ public class CutRodBottom2Up { //钢条价格表 private final int[] price={1,5,8,9,10,17,17,20,24,30}; public static void main(String[] args) { new CutRodBottom2Up().start(); } private void start() { for(int i=1;i<=10;i++) { //打印一种最优方案 printCutRodSolution(i); } } private CutRodSolution bottomUpCutRod(int n) { CutRodSolution crsl = new CutRodSolution(price.length+1); crsl.r[0] = 0; for(int j=1;j<=n;j++) { //因为钢条价格非负,因此-1可以看做-OO int q=-1; for(int i=1;i<=j;i++) { if(q < price[i-1]+crsl.r[j-i]) { //存储最优收益值 q = price[i-1]+crsl.r[j-i]; //存储最优切割方法(第一次切割长度) crsl.s[j] = i; } } crsl.r[j] = q; } return crsl; } //打印输出钢条长度为n的完整切割方案 private void printCutRodSolution(int n) { CutRodSolution sl = bottomUpCutRod(n); System.out.print("长度为"+n+"的钢条最优收益为:"+sl.r[n]+" "); System.out.print("切割方案为:"); while(n > 0) { System.out.print(sl.s[n]+" "); n = n-sl.s[n]; } System.out.println(); } //内部类存储最优切割方案信息 private static class CutRodSolution { //存储最优收益值数组r[0..n] int[] r = null; //存储最优切割方案数组s[0..n] int[] s = null; public CutRodSolution(int capacity) { r = new int[capacity]; s = new int[capacity]; } } }
时间: 2024-10-23 06:08:36