码迷,mamicode.com
首页 > 其他好文 > 详细

钢条切割

时间:2015-04-06 21:44:11      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

#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 Memoized_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_Rod(int *p, int n)
{
    int *r = new int[n + 1];
    r[0] = 0;
    for (int j = 1; j <= n; j++)
    {
        int q = -1;
        for (int i = 1; i <= j; i++)
        {
            q = max(q,p[i]+r[j-i]);
        }
        r[j] = q;
    }
    for (int i = 0; i < n; i++)
        delete [i]r;
    return r[n];
}

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

    return 0;
}

 

钢条切割

标签:

原文地址:http://www.cnblogs.com/liuhg/p/Cut_Rod.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!