带打印子结点的自底向上算法
对我随笔的第一个算法做了一点点改动,可以打印出全部的切割长度,时间复杂度不算高
#include<iostream> #include<time.h> #include<algorithm> using namespace std; int p[1000], r[1000], s[1000]; int *EXTENDED_BOTTON_UP_CUT_ROD(int *p, int n) { r[0] = 0; int q = 0; for(int j = 1; j <= n; j++) { q = -1e8; for(int i = 1; i <= j; i++) { if(q < (p[i] + r[j - i])) { q = p[i]+r[j-i]; s[j] = i; r[j] = q; } } } return r, s; } /*PRINT_CUT_ROD_SOLUTION(p, n) { } */ int main() { int n = 0, q = 0; //q是最优收益 clock_t start, finish; double duration = 0.0; int *a, *b; p[0] = 0; p[1] = 1; p[2] = 5; p[3] = 8; p[4] = 9; p[5] = 10; p[6] = 17; p[7] = 17; p[8] = 20; p[9] = 24; p[10] =30; cout << "请输入钢管的长度:"; cin >> n; start = clock(); (a, b) = EXTENDED_BOTTON_UP_CUT_ROD(p, n); while(n > 0) { cout << s[n] << endl; n = n - s[n]; } cout << "最优长度为:" << q; finish = clock(); duration = (double)(finish - start )/CLOCKS_PER_SEC; cout << "运行时间为" << duration << endl; return 0; }
}