钢条切割

#include<iostream>
#include<algorithm>
using namespace std;
//rn=max(pi+rn-1)

int Cut_Rod(int *p, int n)
{
    if (n == 0)
        return 0;
    int q = -1;
    for (int i = 1; i <= n; i++)
    {
        q = max(q, p[i] + Cut_Rod(p, n - i));
    }
    return q;
}
int Memoized_Cut_Rod_Aux(int *p, int n, int *r)
{
    if (r[n] >= 0)
        return r[n];
    int q;
    if (n == 0)
        q=0;
    else
    {
        q = -1;
        for (int i = 1; i <= n; i++)
        {
            q = max(q, p[i] + Memoized_Cut_Rod_Aux(p,n-i,r));
        }
    }
    r[n] = q;
    return q;
}
int Momized_Cut_Rod(int *p, int n)
{
    int *r = new int[n + 1];
    for (int i = 0; i < n + 1; i++)
        r[i] = -1;
    int res = Memoized_Cut_Rod_Aux(p,n,r);
    delete[]r;
    return res;
}
int Bottom_Up_Cut_Rod(int *p, int n)
{
    int *r = new int[n + 1];
    r[0] = 0;
    int q;
    for (int j = 1; j <= n; j++)
    {
        q = -1;
        for (int i = 1; i <= j; i++)
        { 
            q = max(q, p[i] + r[j - i]);
        }
        r[j] = q;
    }
    return q;

}
int Extended_Bottom_Cut_Rod(int *p, int n,int *s)
{
    int *r = new int[n + 1];
    r[0] = 0;
    int q;
    for (int j = 1; j <= n; j++)
    {
        q = -1;
        for (int i = 1; i <= j; i++)
        {
            if (q < p[i] + r[j - i])
            {
                q = p[i] + r[j - i];
                s[j] = i;
            }
        }
        r[j] = q;
    }
    int res = r[n];
    delete[]r;
    return res;
}
int Print_Cut_Rod_Solution(int *p, int n)
{
    int *s=new int[n+1];
    int r = Extended_Bottom_Cut_Rod(p,n,s);
    while (n>0)
    {
        cout << s[n] << "  ";
        n = n - s[n];
    }
    cout << "\n";
    delete[]s;
    return r;

}
int main()
{
    int p[] = {0,1,5,8,9,10,17,17,20,24,30};
    cout << Print_Cut_Rod_Solution(p, 4) << endl;

    return 0;
}

 

posted @ 2015-04-06 20:34  liuhg  阅读(272)  评论(0编辑  收藏  举报