首页 > 代码库 > rod cutting

rod cutting

for a rod of length i the price of it si pi,to cut the rod to earn more money

package dynamic_programming;

public class rod_cutting {
    int [] r;
    public int[] BTU_rod_cutting(int[] p,int n)
    {
          r = new int[n];  //r[n] is the most money of the //length n 
        int[] s = new int[n];
        int q;
        r[0] = 0;
        for(int j = 0;j <= n-1;j++){ //all the amount
            q = -1;
            for(int i = 0;i<=j;j++){//divide
                if(q < p[i] + r[j-i]){
                q = p[i] + r[j-i];
                s[j] = i;    //record j rods how to divide
                }
                
            }
            r[j] = q;  //every time memory it
            
        }
        return s;
    }
    
    public void print(int[] p,int n){
        int[] a = BTU_rod_cutting(p,n);
        while(n>=0){
             System.out.println(a[n-1]+"");
             n = n - a[n-1];
        }
    }
}

 

rod cutting