这是算法导论第三册 动态规划 15.1 别人的一个实现
我为什么在红色字体的地方运行到j=4,i=1时r[0]会被更改呢?j为4啊,不知道什么地方有修改r[0]的语句。
大家知道的,帮我指点一下。
想传张截图上来可是怎么也传不上来,一直卡在上传中
//EXTENDED-BOTTOM-UP-CUT-ROD(p,n)
#include <iostream>
using namespace std;
#include <ctime>
const int MAXISIZE=2000;
void ExtendedBottomUpCutRod(int *p, int n,int *r,int *s)
{
//int r[MAXISIZE];//auxiliary array initialized with minimum
//int s[n];
r[0] = 0;
int i,j,k;
for ( j=1; j<=n; j++)
{
int q = INT_MIN;//??????why q assign so many times
for ( i=1; i<=j; i++)
{
k = p[i-1] + r[j-i]; //p[0] is the price of length 1,so p[0] is 1
if ( q < k )
{
q = k;
s[j]=i;
r[j] = q; }
}
}
// for(int j=0;j<n;j++)
// cout<<"the r["<<j<<"] is:"<<r[j]<<endl;
}
void PrintCutRodSolution(int* p,int n,int* r,int* s)
{
ExtendedBottomUpCutRod(p,n,r,s);
cout<<"the optimal first sizes are:"<<endl;
for(int i=1;i<=n;i++)
cout<<i<<":"<<s[i]<<" ";
cout<<endl;
cout<<"the optimal value of each length are:"<<endl;
for(int i=1;i<=n;i++)
cout<<i<<":"<<r[i]<<" ";
cout<<endl;
//print the partition
cout<<"Print the partition:";
while(n>0)
{
cout<<s[n]<<" ";
n=n-s[n];
}
cout<<endl;
}
int main()
{
int p[] = {1,5,8,9,10,17,17,20,24,30};
//int p[MAXISIZE] ={1,5,8,9,10,17,17,20,24};
const int rodLength=4;
//r is an array of optimal value of each length
int r[rodLength];
int s[rodLength];
clock_t start = clock();
//int k = MemoizedCutRod(p,1999);
//ExtendedBottomUpCutRod(p,rodLength,r,s);
PrintCutRodSolution(p,rodLength,r,s);
// How can i careless to enter the wrong sequence of parameters
// cout<<"the optimal first sizes are:"<<endl;
//for(int i=1;i<=rodLength;i++)
// cout<<i<<":"<<s[i]<<" ";
//cout<<endl;
//
//
// cout<<"the optimal value of each length are:"<<endl;
//for(int i=1;i<=rodLength;i++)
// cout<<i<<":"<<r[i]<<" ";
//cout<<endl;
clock_t end = clock();
cout<<"optimal value:"<<r[rodLength]<<" "<<"time: "<<double(end-start)/CLOCKS_PER_SEC<<"s"<<endl;
return 0;
}