标签:
钢条切割问题的两种解法
#ifndef IRON_CUT_PRB_H#define IRON_CUT_RPB_H#include <iostream>int ironCutPrb(int *ironPrice,int Length); //这个是基于递规逄法的int ironCutPrb_optimize(int *ironPrice,int Length); //这个是基于双层循环的。#endif
#include"ironCutPrb.h"#define Max(a,b) a>b? a:bint storePre[100]={0};int ironCutPrb(int *ironPrice,int Length){if(Length==0)return 0;if(storePre[Length]!=0)return storePre[Length];int price=-245;for(int i=1;i<=Length; i++){price=Max((ironPrice[i]+ironCutPrb(ironPrice,Length-i-1)),price);}storePre[Length]=price;return price;}int ironCutPrb_optimize(int *ironPrice,int Length){int *cutIndex=new int[Length+1];int *priceStore=new int[Length+1];int *pathStore=new int[Length+1];for(int i=0;i<=Length; i++){pathStore[i]=0;}priceStore[0]=0;for(int i=1;i<=Length; i++){int price=-200;int j;for(j=1;j<=i; j++){if(priceStore[i-j]+ironPrice[j-1]>price){pathStore[i]=j; //意思为使是长度为i的钢条价格达到最优,需要从第j个位置进行截断,当然//可能还有其它的位置呢。}price=Max(price,(priceStore[i-j]+ironPrice[j-1]));}priceStore[i]=price;}int n=Length;while(n>0){std::cout<<pathStore[n]<<std::endl;n=n-pathStore[n];}return priceStore[Length];}
for(int i=1;i<=Length; i++){price=Max((ironPrice[i]+ironCutPrb(ironPrice,Length-i-1)),price);}
for(int i=1;i<=Length; i++){price=Max(price,ironCutPrb(ironPrice,Length-i)+ironCutPrb(ironPrice,i));}
标签:
原文地址:http://www.cnblogs.com/yml435/p/4655544.html