给定一根长度为 n 英寸的棒和一个价格表 pi,i = 1, 2,... n,确定通过切割棒并出售碎片可获得的最大收益 rn。
Bottom_Up_Cut_Rod(p, n)
1 let r[0...n] be a new array
2 r[0] = 0
3 for j = 1 to n
4 q = -infinity
5 for i = 1 to j
6 q = max(q; p[i] + r[j - i])
7 r[j] = q
8 return r[n]
执行
#include <iostream>
#include <algorithm>
using namespace std;
int RodCut(long long P[],long long n)
{
long long r[n];
r[0]=0;
for(long long j=0;j<n;j++)
{
long long q = -100000;
for(long long i=0;i<j;i++)
{
q = max(q , P[i] + r[j-i]);
}
r[j] = q;
}
return r[n];
}
int main()
{
long long num;
long long N;
long long K;
cin>>N;
long long a[N];
for (long long i = 0; i < N; i++)
{
cin>>num;
a[i] = num;
}
int res = 0;
res = RodCut(a,N);
cout<<"Answer : "<<res;
return 0;
}
我的输入是1 5 8 9 10 17 17 20 24 30
,但输出是2686348
。我的代码有什么问题?