The implementation of this DP problem is implemented in code, which is divided into recursive algorithm (top-down) and non-recursive algorithm (from bottom-up), and the implementation of the extended bottom-up algorithm.
Recursive algorithm:
1#include <iostream>2 3 using namespacestd;4 5 intSize =Ten;6 7InlineintMaxintAintb)8 {9 returna > B?a:b;Ten } One A intCutrod (intP[],intN) - { - if(n = =0) the return 0; - Else - { - intQ =int_min; + for(inti =1; I < n; i++) - { +Q = max (q, P[i] + Cutrod (p, N-i-1)); A } at returnQ; - } - } - - - in intMain () - { to intA[] = {1,5,8,9,Ten, -, -, -, -, - }; +cout << Cutrod (A,6) <<Endl; -}
Non-recursive algorithm:
#include <iostream>using namespacestd;intSize =Ten; inlineintMaxintAintb) { returna > B?a:b;}intNonrecursioncutrod (intP[],intN) { int*r =New int[n]; r[0] = p[0]; for(intj =1; J < N; J + +) { intQ =P[j]; for(inti =0; I < J; i++) { if(q< (P[i] + r[j-i-1])) {Q= P[i] + r[j-i-1]; }} R[j]=Q; } returnr[n-1];}intMain () {intA[] = {1,5,8,9,Ten, -, -, -, -, - }; cout<< Nonrecursioncutrod (A,6) <<Endl;}
Extended non-recursive algorithm:
Here I set up a result struct to be used as the return results, in fact this intention: if we ask for a solution of length J, then we will put the length of the first segment of the cut in the cell labeled J in the array, if I, then the remainder can be found by looking for the j-i scheme, This way, a solution of length J can be obtained by recursion.
1#include <iostream>2 3 using namespacestd;4 5typedefstructResult6 {7 intMax;8 int*Price ;9 }result;Ten OneResult Extendnonrecursioncutrod (intA[],intN) A { - result result; -Result. Price =New int[n+1]; the int*r =New int[n+1]; -r[1] = a[1]; -Result. price[1] = a[1]; - for(intj =1; J <= N; J + +) + { - intQ =A[j]; + intt =J; A for(inti =1; I < J; i++) at { - if(Q < (A[i] + r[j-i])) - { -Q = a[i] + r[j-i]; -t =i; - } in } -R[J] =Q; toResult. PRICE[J] =T; + } -Result. Max =R[n]; the returnresult; * } $ Panax Notoginseng intMain () - { the intA[] = {0,1,5,8,9,Ten, -, -, -, -, - }; +Result result = Extendnonrecursioncutrod (A,Ten); Acout << result. Max <<Endl; the for(inti =1; I <Ten; i++) +cout << result. Price[i] <<" "; -}
Introduction to Algorithms 15.1 steel strip cutting