对应于算法导论上的钢条切割问题。
package Dynamic_Programming;
/*
* 动态优化问题之钢条切割问题
* 长度i: 1 2 3 4 5 6 7 8 9 10
* 价格p: 1 5 8 9 10 17 17 20 24 30
*
* 问题,对于长度为i的钢条,怎么切割,使之价值最大。
*
*/
public class Steel_Bar_Cutting {
/*
* 带备忘录的自顶向下方法,递归
*/
public int cut(int[] p, int[] r,int n) //n表示钢条多长
{
if(n==0)
{
return 0;
}
if(r[n]!=0)
{
return r[n];
}
int result=-Integer.MAX_VALUE;
for(int i=1;i<=n;i++)
{
int temp=p[i]+cut(p,r,n-i);
if(temp>result)
{
result=temp;
}
}
r[n]=result;
return r[n];
}
/**
* 自底向上
*
*
* @param args
*/
public int cut_bottom(int[] p,int[] r,int n)
{
for(int i=1;i<=n;i++)
{
int result=-Integer.MAX_VALUE;
int temp;
for(int j=1;j<=i;j++)
{
temp=p[j]+r[i-j];
if(temp>result)
{
result=temp;
}
}
r[i]=result;
}
return r[n];
}
public static void main(String[] args) {
int[] p=new int[]{0,1,5,8,9,10,17,17,20,24,30};
int n=p.length;
int[] r=new int[n];
Steel_Bar_Cutting instance=new Steel_Bar_Cutting();
for(int i=0;i<n;i++)
{
System.out.println("钢条长"+String.valueOf(i)+":"+instance.cut(p,r,i));
}
System.out.println("------------------");
for(int i=0;i<n;i++)
{
System.out.println("钢条长"+String.valueOf(i)+":"+instance.cut_bottom(p,r,i));
}
}
}