问题描述:给定一个钢条的长度,求最大效益和切割方法
长度和价格的关系如下:
length 1 2 3 4 5 6 7 8 9 10
price 1 5 8 9 10 17 17 20 24 30
package com.dynamic;
public class CutRod {
private int []price;
private int length;
private int []r;
private int []s;
public CutRod(int []price){
this.price=price;
}
/**
*自顶向下递归
* @param length
* @return
*/
public int momoizedCutRod(int length){
r=new int[length+1];
for(int i=0;i<=length;i++){
r[i]=-1;
}
return memoizedCutRodAux(length,r);
}
private int memoizedCutRodAux(int length,int []r){
if(r[length]>=0){
return r[length];
}
int q;
if(length==0){
q=0;
}else{
if(length>=price.length){
q=price[price.length-1];
}else{
q=price[length];
}
if(length>price.length){
for(int i=1;i<=price.length-1;i++){
q=Math.max(q, price[i]+memoizedCutRodAux(length-i,r));
}
}else{
for(int i=1;i<=length-1;i++){
q=Math.max(q, price[i]+memoizedCutRodAux(length-i,r));
}
}
}
r[length]=q;
return q;
}
public int bottomUpCutRod(int length){
r=new int[length+1];
r[0]=0;
for(int j=1;j<=length;j++){
int q=0;
if(j>=price.length){
q=price[price.length-1];
}else{
q=price[j];
}
for(int i=1;i<=j;i++){
q=Math.max(q, price[i]+r[j-i]);
}
r[j]=q;
}
return r[length];
}
public int extendBottomUpCutRod(int length){
r=new int[length+1];
s=new int[length+1];
r[0]=0;
for(int j=1;j<=length;j++){
int q=0;
if(j>=price.length){
q=price[price.length-1];
}else{
q=price[j];
}
for(int i=1;i<=j;i++){
if(q<=price[i]+r[j-i]){
q=price[i]+r[j-i];
s[j]=i;
}
}
r[j]=q;
}
return r[length];
}
public void printSolution(int length){
extendBottomUpCutRod(length);
int n=length;
while(n>0){
System.out.print(s[n]+" ");
n=n-s[n];
}
System.out.println();
}
public static void main(String[] args) {
int []price=new int[]{0,1,5,8,9,10,17,17,20,24,30};
CutRod cut=new CutRod(price);
System.out.println(cut.extendBottomUpCutRod(3));
cut.printSolution(3);
System.out.println(cut.extendBottomUpCutRod(4));
cut.printSolution(4);
System.out.println(cut.extendBottomUpCutRod(5));
cut.printSolution(5);
System.out.println(cut.extendBottomUpCutRod(10));
cut.printSolution(10);
System.out.println("===========");
System.out.println(cut.bottomUpCutRod(5));
System.out.println("===========");
System.out.println(cut.momoizedCutRod(4));
}
}