Пример #1
0
/// use recursive algorithm, easy to understand. looks like a tree
int knapsack_rec(int index, int current_size){
    if (current_size + weight[index] <= knapsacksize && index < nitems){
        return max(value[index] + knapsack_rec(index + 1, current_size + weight[index]),
                   knapsack_rec(index + 1, current_size));
    }
    return 0;
}
Пример #2
0
int main () {
	int i;
	Tab = (int *) malloc ((M+1) * sizeof(int));
	/* inizializzazione tabella */
	for(i=0;i<=M;i++)
		Tab[i] = -1;
	printf("\n---------------------------\n-      LISTA OGGETTI     -\n---------------------------\n");
	printf(" OGGETTO  VALORE\t  SPAZIO\n");
	for(i=0;i<N;i++)
		printf("\t%c\t\t  %2d\t\t%2d\n",O[i].name,O[i].v,O[i].s);

	knapsack_rec(M);
	printf("\nIl massimo valore ottenuto e' %d\n",knapsack_din(M));
	printf("\nNumero di ricorsioni con knapsack_rec = %d\n",count_rec);
	printf("Numero di ricorsione con knapsack_din = %d\n",count_din);
	
	printf("\n---------------------------\n-  LISTA OGGETTI SCELTI  -\n---------------------------\n");
	printf(" OGGETTO  VALORE\t  SPAZIO\n");
/*	for(i=M; i >= 1;i-O[indexes[i]].s)
		printf("   %c\t%2d\t%2d\n",O[indexes[i]].name,O[indexes[i]].v,O[indexes[i]].s);*/
	
	i=M;
	while(i)
	{
		printf("\t%c\t\t  %2d\t\t%2d\n",O[indexes[i]].name,O[indexes[i]].v,O[indexes[i]].s);
		i=i-O[indexes[i]].s;
	}
	return 0;
}
Пример #3
0
int knapsack_rec(int r){
	int i,t,max = 0;
	for(i=0;i<N;i++)
	{
		count_rec++;		
		if((r - O[i].s) >= 0)
			if( (t = O[i].v + knapsack_rec((r - O[i].s))) > max)
				max = t;
	}
	return max;
}
Пример #4
0
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;
}