int memoized_cut_rod_aux(int *p, int n, int *r) { int q; if (r[n] >= 0) { return r[n]; } if (n == 0) { q = 0; } else { q = INT_MIN; for (int i = 0; i < n; i++) { int j = i > 9 ? 9 : i; q = MAX(q, p[j] + memoized_cut_rod_aux(p, n - i - 1, r)); } } r[n] = q; printf("r = "); for (int i = 0; i < n; i++) { printf("%d ", r[i]); } printf("\n"); return q; }
/* * return the max proceed of n-length rod, * n is not equal the whole rod_length */ int memoized_cut_rod_aux( int *p, int n, int *s, int *r ) { /* r[n] is the memo */ if( r[n] >= 0 ) return r[n]; int q = INT_MIN; if( n == 0 ){ q = 0; } else { /* * i counts from 1 but not 0, * because a function can't call itself with the same parameters. */ for( int i = 1; i <= n; i++ ){ int current_proceed = p[i] + memoized_cut_rod_aux( p, n-i, s, r ); if( q < current_proceed ){ q = current_proceed; s[n] = i; } } } return q; }
/* * memoized method, form top downto bottom, * calculate the necessary the subquestion only * and store it for further uses. */ int memoized_cut_rod( int *p, int n, int *s ) { int *r = (int *)malloc( sizeof(int) * ( n + 1 )); for( int i = 0; i <= n; i++ ) r[i] = INT_MIN; return memoized_cut_rod_aux( p, n, s, r ); }
int memoized_cut_rod(int *p, int n) { int r[n+1]; for (int i = 0; i < n + 1; i++) { r[i] = INT_MIN; } return memoized_cut_rod_aux(p, n, r); }