Topic:
There are n items and a backpack with a capacity of V. The volume of article I is c[i], the value is v[i]. Solving which items are loaded into the backpack maximizes the sum of the values:
There are 5 items, the size of the backpack is 10, their volume is c[5] = {3,5,2,7,4}; Value is v[5] = {2,4,1,6,5}.
Solution:
The final run result diagram is as follows
Solution Analysis
The main program is as follows
All code: (worker input should pay attention to upper bounds check)
1#include <stdio.h>2 3 Static Const intc[5]={3,5,2,7,4};// Cost4 Static Const intv[5]={2,4,1,6,5};//value5 Static intmem_table[6][ One];//MEM table for dynamic programming6 7 Static intWorkerintAbility,intLen) {8 9 if(ability<=0|| len<=0)Ten return 0; One if(mem_table[len][ability]!=-1) A returnmem_table[len][ability]; - if(len==1){ - if(ability>=c[len-1]) themem_table[len][ability]=v[len-1]; - Else -mem_table[len][ability]=0; -}Else{ + intYes,no; - if(ability<c[len-1]) +yes=-1; A Else atYes=worker (ability-c[len-1],len-1) +v[len-1]; -No=worker (ability,len-1); -mem_table[len][ability]= (yes>no)?Yes:no; - } - returnmem_table[len][ability]; - in } - to intMain () { + - //mem_table init to invalid-1 the inti,j; * for(i=0;i<6; i++) $ for(j=0;j< One; j + +)Panax Notoginsengmem_table[i][j]=-1; - the //Dump +printf"table:\n"); A for(i=5;i>0; i--) { theprintf"\ t"); + for(j=1;j< One; j + +) -printf"%5d", Mem_table[i][j]); $printf"\ n"); $ } - - //Call the worker:) theprintf"result:%d\n", Worker (Ten,5)); - Wuyi //Dump theprintf"table:\n"); - for(i=5;i>0; i--) { Wuprintf"\ t"); - for(j=1;j< One; j + +) Aboutprintf"%5d", Mem_table[i][j]); $printf"\ n"); - } - -}
Code on paper: 01 knapsack Problem of Dynamic planning