#include<iostream> #include<algorithm> #include<utility> #include<vector> using namespace std; //采用普通的递归算法来求解钢条分割的最大的收益 int cut_rod(int *p,const 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=-1; if(n==0) q=0; else { 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[11]={}; for(int i=0;i<11;++i) r[i]=-1; int q=memoized_cut_rod_aux(p,n,r); return q; } //至顶向上的方法来求解钢条问题 int bottom_up_cut_rod(int *p,int n) { int r[11]={0}; for(int j=1;j<=n;++j) { int q=-1; for(int i=1;i<=j;++i) { q=max(q,p[i]+r[p,j-i]); } r[j]=q; } return r[n]; } pair< vector<int>,vector<int> > extened_bottom_up__cut_rot(int *p,int n) { pair< vector<int>,vector<int> > result; int r[11]={0}; int s[11]={0}; result.first.push_back(0); result.second.push_back(0); for(int j=1;j<=n;++j) { int q=-1; for(int i=1;i<=j;++i) { //q=-1; //q=max(q,p[i]+r[j-i]) if(q<p[i]+r[j-i]) { q=p[i]+r[j-i]; s[j]=i; } } r[j]=q; result.first.push_back(r[j]); result.second.push_back(s[j]); } return result; } //打印结果值; void print_cut_rod_solution(int *p,int n) { cout<<"最大的收益值为"<<endl; //cout<<"钢条的分割方式为"<<endl; pair< vector<int>,vector<int> > result; result=extened_bottom_up__cut_rot(p,n); cout<<result.first[n]<<endl; cout<<"钢条的分割方式为"<<endl; while(n>0) { //cout<<"钢条的分割方式为"<<endl; cout<<result.second[n]; n=n-result.second[n]; cout<<endl; } cout<<endl; cout<<"钢条的分割方式结束"<<endl; } int main() { int price[11]={0,1,5,8,9,10,17,17,20,24,30}; //cout<<cut_rod(price,5)<<endl; cout<< bottom_up_cut_rod(price,8)<<endl; print_cut_rod_solution(price,8); system("pause"); return 0; }
时间: 2024-11-05 15:51:13