Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dynamic_programming/rod_cut/readme
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Dynamic programming solution to the rod-cut problem from Cormen's Introduction to Algorithms.
18 changes: 18 additions & 0 deletions dynamic_programming/rod_cut/rod-cut-main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#include <stdlib.h>
#include <stdio.h>

#include <dynamic-programming/rod-cut/rod-cut.h>


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');
}
}
56 changes: 56 additions & 0 deletions dynamic_programming/rod_cut/rod-cut.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include <stdlib.h>

#include <dynamic-programming/rod-cut/rod-cut.h>
#include <util/debug.h>


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;
}