int main() { printf ("1. rec max value = %d\n", knapsack_rec(0, 0)); printf ("2. bru max value = %d\n", knapsack_bruteforce()); printf ("3. dyn max value = %d\n", knapsack_dynamic()); memset(dynamic_tab_rec, -1, sizeof(dynamic_tab_rec)); printf ("4. dre max value = %d\n", knapsack_dynamic_rec(nitems, knapsacksize)); return 0; }
void knapsack_bf_iface(int n, int capacity, int *value, int *weight) { //first call of knapsack_bruteforce with default values knapsack_bruteforce(-1, 0, 0, capacity, n, value, weight); #ifdef VERBOSE printf("Max value is: %d\n", best); printf("The solution is: "); //printf("res_x: %lld\n\n",res_x); for(int i=0; i<=n; i++) { if(res_x%2) printf("%d ", i+1); res_x=res_x>>1; } printf("\n"); #endif }
void knapsack_bruteforce (int id, int sum_weight, int sum_value, int capacity, int n, int *value, int *weight) { #ifndef NONSENSE if(sum_weight>capacity) return; //there is no reaaasooon #endif if(id<n-1) { //if there are more items to check //decision: false //our algorithm is not paralell, so we can use single temporary var for every call temp_x &= ~(1ull << (id+1)); knapsack_bruteforce(id+1, sum_weight, sum_value, capacity, n, value, weight); //decision: true temp_x |= (1ull << (id+1)); knapsack_bruteforce(id+1, sum_weight+weight[id+1], sum_value+value[id+1], capacity, n, value, weight); }else{ //each item is checked. if(sum_value>best) { res_x=temp_x; best=sum_value; } } }