标签:
#include<iostream> #include<algorithm> using namespace std; //rn=max(pi+rn-1) int Cut_Rod(int *p, int n) { if (n == 0) return 0; int q = -1; for (int i = 1; i <= n; i++) { q = max(q,p[i]+Cut_Rod(p,n-i)); } return q; } int Memoized_Cut_Rod_Aux(int *p, int n, int* r) { if (r[n] >= 0) return r[n]; int q; if (n == 0) q = 0; else { q = -1; for (int i = 1; i <= n; i++) { q = max(q, p[i]+Memoized_Cut_Rod_Aux(p, n - i, r)); } } r[n] = q; return q; } int Memoized_Cut_Rod(int *p, int n) { int *r = new int[n+1]; for (int i = 0; i < n+1; i++) r[i] = -1; int res= Memoized_Cut_Rod_Aux(p,n,r); delete[]r; return res; } int Bottom_Up_Rod(int *p, int n) { int *r = new int[n + 1]; r[0] = 0; for (int j = 1; j <= n; j++) { int q = -1; for (int i = 1; i <= j; i++) { q = max(q,p[i]+r[j-i]); } r[j] = q; } for (int i = 0; i < n; i++) delete [i]r; return r[n]; } int main() { int p[] = {0,1,5,8,9,10,17,17,20,24,30}; cout << Memoized_Cut_Rod(p, 11) << endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/liuhg/p/Cut_Rod.html