钢管切割原始问题:
某公司生产长钢管,然后一般,会将钢条切断,变成不同长度,然后去售卖。其中有个问题是,不同长度的钢管的售价是不一样的,但是它们并不是完全按照比例来,比如2米的钢管售价要比3米的钢管售价要少,但是并不是2比3的比例。钢管的长度售价表如下:
长度i | 1 2 3 4 5 6 7 8 9 10 |
价格Pi | 1 5 8 9 10 17 17 20 24 30 |
于是问题就来了,比如30米长的钢管,要如何切割,切割成多长的几条,才能让售价最高,收益最高呢?
using namespace std;
struct result {
int* r;
int* s;
int len;
result(int l) :
r(), s(), len(l) {
r = new int[len];
s = new int[len];
r[0] = 0;
}
~result() {
delete[] r;
delete[] s;
}
};
result* extended_bottom_up_cut_rod(int p[], int n) {
result* res = new result(n + 1);
int q = -1;
//外层的循环代表的是保留的不切割的那段
for (int i = 1; i <= n; i++) {
//内层的循环代表的是要分割的,且要求出最佳分割的那段
for (int j = 1; j <= i; j++) {
if (q < p[j] + res->r[i - j]) {
q = p[j] + res->r[i - j];
res->s[i] = j;
}
}
res->r[i] = q;
}
return res;
}
int main() {
int p[] = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
int n = 9;
result* res = extended_bottom_up_cut_rod(p, n);
cout <<res->r[9] << endl;//循环输出实际的最佳分割段长
cout << "分段情况:";
while (n > 0) {
cout << res->s[n] << ' ';
n = n - res->s[n];
}
delete res;
return 0;
}