Cut Rod

Geeks, textbook


Description:

Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. F

Example:

For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)


length   | 1   2   3   4   5   6   7   8  
--------------------------------------------
price    | 1   5   8   9  10  17  17  20
And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1)

length   | 1   2   3   4   5   6   7   8  
--------------------------------------------
price    | 3   5   8   9  10  17  17  20

Idea:

DP is O(n2).

cutRod(n) = max(price[i] + cutRod(n-length[i])) for all i in {0, 1 .. n-1} && n>=length[i]

Note compare with knapsack

Code:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// DP with Memoization
int rodPriceDPHelper(int totalLen, vector<int>& rodPriceStore, 
                    const vector<int>& length, const vector<int>& price){
    if(rodPriceStore[totalLen]!=-1)
        return rodPriceStore[totalLen];

    if(totalLen==0){
        rodPriceStore[totalLen]=0;
        return 0;
    }
    int maxPrice=0;
    for(int i=0; i<length.size(); i++){
        if(length[i]<=totalLen)
            maxPrice = max(maxPrice, rodPriceDPHelper(totalLen-length[i], rodPriceStore, length, price) + price[i] );
    }
    rodPriceStore[totalLen] = maxPrice;
    return rodPriceStore[totalLen];    
}

int rodPriceDP(int totalLen, const vector<int>& length, const vector<int>& price){
    vector<int> rodPriceStore(totalLen+1, -1);
    return rodPriceDPHelper(totalLen, rodPriceStore, length, price);
}


// Naive recursion
int rodPrice(int totalLen, const vector<int>& length, const vector<int>& price){
    int maxPrice=0;
    if(totalLen==0){
        return 0;
    }
    for(int i=0; i<length.size(); i++){
        if(length[i]<=totalLen)
            maxPrice = max(maxPrice, rodPrice(totalLen-length[i], length, price) + price[i] );
    }
    return maxPrice;
}

int main(){
    vector<int> length = {1, 2, 3, 4, 5, 6, 7, 8};
    vector<int> price = {1, 5, 8, 9, 10, 17, 17, 20};

    cout<<rodPrice(8, length, price)<<endl;
    cout<<rodPriceDP(8, length, price)<<endl;
}

results matching ""

    No results matching ""