/*************************************************************************** *** FILE: knapsack_recursion.cpp *** DATE: 11/01/2003 *** AUTHOR: Daniel Dementiev *** DESCR: This is an example program for IST238:Algorihms class. *** This programm illustrates the simple recursion solution *** of the knapsack prblem. The recursion algorithm is implemented *** in the knapsack() function. This function takes three arguments: *** - an array of items *** - the number of items *** - the limit weight *** This function returns an integer number - the sum value of the *** selected items. *** To execute this program you can use: *** ...> knapsack_recursion *** ...> knapsack_recursion *** ...> knapsack_recursion *** All the items will be generated rendomly. ***************************************************************************/ #include #include #include #include using namespace std; #include // New type that contains all information about an item struct TItem { int price; int weight; }; void print_items(TItem *items, int size) { cout<<" # w $$$\n"; for(int i=0;i weight ) return sub_price; int max_price = items[n-1].price + knapsack(items, n-1, weight-items[n-1].weight); if( max_price < sub_price ) max_price = sub_price; return max_price; } // ============================================= void main(int argc, char *argv[]) { int N, W, totalw=0, price; TItem *items; N = argc>1 && (N=atoi(argv[1])) ? N : 10; W = argc>2 && (W=atoi(argv[2])) ? W : 0; cerr<<"Generating a random knapsack problem of the size "<0 ? W : totalw/3; cerr<<"\b\b\b[Done]\n"; print_items(items, N); cout<<"Knapsack can contain up to "<