钢条切割问题

对应于算法导论上的钢条切割问题。

 

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));
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值