首页 > 编程语言 > 详细

算法导论--钢条切割

时间:2015-08-08 11:57:14      阅读:298      评论:0      收藏:0      [点我收藏+]
#include<iostream>
using namespace std;
/*钢条切割:
给定长度为1,2,3,4......10的价格pi
算出给定一个长度为n的钢条怎样切割使其出售所得利润最大。

*/
int p[]={0,1,5,8,9,10,17,17,20,24,30};
int r[100],s[100];   //最大利润,s用于记录切割位置
//自底向上
int bottomcut(int n){
    r[0]=0;
    int t;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=i;j++){
            t=p[j]+r[i-j];
            if(t>r[i]){
                r[i]=t;
                s[i]=j;
            }
        }
    }
    return 0;
}
//自顶向下,递归
int headcut(int n){
    int t,q;
    if(r[n]>0)
        return r[n];
    if(n==0)
        q=0;
     q=-100;
    for(int i=1;i<=n;i++){
        t=p[i]+headcut(n-i);
        if(t>q)
            q=t;            
    }
    r[n]=q;
    return 0;
}
int main(){
    
    int n;
    while(cin>>n){
        memset(r,0,sizeof(r));
       // bottomcut(n);
        headcut(n);
    for(int i=1;i<=n;i++){
        cout<<r[i]<<endl;
    }

    }
    return 0;
}

 

算法导论--钢条切割

原文:http://www.cnblogs.com/wintersong/p/4712739.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!