diff --git a/dynamic_programming/rod_cut/readme b/dynamic_programming/rod_cut/readme new file mode 100644 index 000000000..076d6ea3b --- /dev/null +++ b/dynamic_programming/rod_cut/readme @@ -0,0 +1 @@ +Dynamic programming solution to the rod-cut problem from Cormen's Introduction to Algorithms. diff --git a/dynamic_programming/rod_cut/rod-cut-main.c b/dynamic_programming/rod_cut/rod-cut-main.c new file mode 100644 index 000000000..1f56d48c1 --- /dev/null +++ b/dynamic_programming/rod_cut/rod-cut-main.c @@ -0,0 +1,18 @@ +#include +#include + +#include + + +int main(int argc, char *argv[]) { + + int p[] = {0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30}; + size_t len_of_p = sizeof p / sizeof *p; + + for(size_t i = 0; i < len_of_p; i++) { + printf("itr %zd\n", i); + printf("memoized: %d\n", memoized_cut_rod(p, i)); + printf("bottomup: %d\n", bottom_up_cut_rod(p, i)); + putchar('\n'); + } +} diff --git a/dynamic_programming/rod_cut/rod-cut.c b/dynamic_programming/rod_cut/rod-cut.c new file mode 100644 index 000000000..b9da14c3c --- /dev/null +++ b/dynamic_programming/rod_cut/rod-cut.c @@ -0,0 +1,56 @@ +#include + +#include +#include + + +int max(int a, int b) { + return a > b ? a : b; +} + +int memoized_cut_rod_aux(int *p, size_t n, int *r) { + if(r[n] >= 0) + return r[n]; + + int q; + if(n == 0) + q = 0; + + else { + q = -1; + for(size_t 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, size_t n) { + int *r; + check_mem(r = malloc((n + 1) * sizeof *r)); + for(size_t i = 0; i <= n; i++) + r[i] = -1; + + return memoized_cut_rod_aux(p, n, r); + + error: + return -1; +} + +int bottom_up_cut_rod(int *p, size_t n) { + int *r; + check_mem(r = malloc((n + 1) * sizeof *r)); + r[0] = 0; + + for(size_t j = 1; j <= n; j++) { + int q = -1; + for (size_t i = 1; i <= j; i++) + q = max(q, p[i] + r[j - i]); + r[j] = q; + } + return r[n]; + + error: + return -1; +}