切割棒的问题如下:
给定一个长度为n英寸的杆子和一个价格表pi,i= 1,2,...,n,确定通过切割杆子并出售这些块可以获得的最大收益Rn。请注意,如果长度为n的杆的价格Pn足够大,则最优解可能根本不需要切割。
Consider the following example:
length i 1 2 3 4 5 6 7 8 9 10
price pi 1 5 8 9 10 17 17 20 24 30考虑当n=4时的情况。将一个4英寸的棒切成两个2英寸的部分产生收益p2 + p2 =5+5= 10,这是一个从上面解决问题的程序,使得时间复杂度不高于Θ(n^2)。您的解决方案必须在不列出削减的情况下确定最优收入。
我已经开发了以下代码:
#include <iostream>
#include <stdio.h>
#include <limits.h>
using namespace std;
int max(int a, int b) {return (a > b)? a : b;}
int cutRod(int price[], int n){
int r[n+1];
r[0] = 0; //solution array
for (int i = 1; i <= n; i++){
int q = INT_MIN;
for( int j = 1; j <= i; j++) {
q = max(q, price[j-1] + r[i-j]);
r[i] = q;
}
}
return r[n];
}
int main() {
int price[] = {1, 5, 8, 9, 10, 17, 20, 24, 30};
cout << cutRod(price, 1) << endl;
cout << cutRod(price, 2) << endl;
cout << cutRod(price, 3) << endl;
cout << cutRod(price, 4) << endl;
cout << cutRod(price, 5) << endl;
cout << cutRod(price, 6) << endl;
cout << cutRod(price, 7) << endl;
cout << cutRod(price, 8) << endl;
cout << cutRod(price, 9) << endl;
cout << cutRod(price, 10) << endl;
return 0;
}我在编译过程中没有得到任何错误,但是当我运行它时,结果如下:
1
5
8
10
13
17
20
24
30
32766这意味着当n=9和n= 10时,最大收益分别为30和32766。这是错误的,因为n=9的最大收益是24,n= 10的最大收益是30。我曾尝试重新构造for循环,但我无法纠正此问题。我这里的问题是,代码的哪一部分是不正确的,因为n => 8的收入是不正确的。非常感谢您的帮助!
发布于 2020-08-14 19:25:35
你的数组中有9个元素...(按1关闭)
另外,作为附注,您应该使用C++算法而不是您自己的max函数(std::max在<algorithm>中),并且在C++代码中不要使用.h系统头文件(使用它们的C++等效项,因此在这里它们将是cstdio和climits)。
作为第二个旁注,您应该尊重一致性(因此在参数列表中将const放在int price[]前面,它可能会显示一些bug)。
作为第三个备注,您可以使用0来代替INT_MIN。
作为第四个附注,也许可以使用std::array?(虽然这纯粹是可选的,这是一个偏好问题!您可能需要一个数组,在这种情况下,请不要担心。)
作为最后一个附注,由于在C/C++中数组是0索引的,所以您应该让循环从0开始,而不是从1开始(尽管这仍然是一个偏好问题)。
(PS:我刚刚注意到,在您上面提供的示例中,您的17的价格是6和7个单位长度的两倍。)
https://stackoverflow.com/questions/63411440
复制相似问题