diff --git a/greedy_algorithms/activity_select/activity-select-main.c b/greedy_algorithms/activity_select/activity-select-main.c new file mode 100644 index 000000000..f65a1db4e --- /dev/null +++ b/greedy_algorithms/activity_select/activity-select-main.c @@ -0,0 +1,22 @@ +#include + +#include +#include + + +int main() { + int s[] = {0, 1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12}; + int f[] = {0, 4, 5, 6, 7, 9, 9, 10, 11, 12, 14, 16}; + size_t s_len = sizeof s / sizeof *s; + + list_t *(*selects[])(int *, int *, size_t) = + { recursive_activity_select, iterative_activity_select }; + size_t selects_len = sizeof selects / sizeof *selects; + + for(size_t i = 0; i < selects_len; i++) { + size_t calls = 0; + list_t *solution = selects[i](s, f, s_len); + list_print(solution); + list_destroy(solution); + } +} diff --git a/greedy_algorithms/activity_select/activity-select.c b/greedy_algorithms/activity_select/activity-select.c new file mode 100644 index 000000000..318620c30 --- /dev/null +++ b/greedy_algorithms/activity_select/activity-select.c @@ -0,0 +1,35 @@ +#include + + +void recursive_activity_select_aux(int *s, int *f, size_t k, size_t n, list_t *res); + +list_t *recursive_activity_select(int *s, int *f, size_t n) { + list_t *A = list_init(); + + recursive_activity_select_aux(s, f, 0, n, A); + + return A; +} + +void recursive_activity_select_aux(int *s, int *f, size_t k, size_t n, list_t *res) { + size_t m = k + 1; + while(m <= n && s[m] < f[k]) m++; + if (m <= n) { + list_add(res, (long)m); + recursive_activity_select_aux(s, f, m, n, res); + } +} + +list_t *iterative_activity_select(int *s, int *f, size_t n) { + list_t *A = list_init(); + + size_t k = 1; + list_add(A, 1); + for(size_t m = 2; m < n; ++m) { + if(s[m] >= f[k]) { + k = m; + list_add(A, m); + } + } + return A; +} diff --git a/greedy_algorithms/activity_select/readme b/greedy_algorithms/activity_select/readme new file mode 100644 index 000000000..2704cc15a --- /dev/null +++ b/greedy_algorithms/activity_select/readme @@ -0,0 +1 @@ +Greedy solution to the activity selection problem from Cormen's Introduction to Algorithms.