1. Description of the problem:
A certain object and a backpack, the weight of the object I is the value of the WI for the VI, the capacity of the backpack is C, how to put the maximum value of the backpack? The problem can be described as:
2. Problem Analysis:
1) Optimal sub-structure:
where J=c-wiyi
2) Recursive relationship: Set the optimal value of M (I,j), J for the optimal capacity, I for optional items, by the optimal substructure properties can be established recursive:
3. Algorithm Description:(not optimized)
1#include <iostream>2 using namespacestd;3 intc[Ten][ -];4 intKnap (intMintN) {5 intw[Ten];6 intv[Ten];7cout <<"input Object Weight W and value v:\n";8 for(inti =1; I <= N; i++){9CIN >> W[i] >>V[i];Ten } One for(inti =1; I <= N; i++) A { - for(intj =1; J <= M; J + +)//the capacity of the backpack is tested individually - { the if(W[i] <=j) - { - if(C[i-1][J] < V[i] + c[i-1][j-W[i]]) -C[I][J] = V[i] + c[i-1][j-W[i]]; + Else -C[I][J] = c[i-1][j]; + } A Else atC[I][J] = c[i-1][j]; - } - } - returnC[n][m]; - } - in intMain () { - intN, M; tocout <<"number of input objects N and backpack capacity m:\n"; +CIN >> N >>m; -cout << Knap (n, m) <<Endl; the for(inti =0; I <= N; i++) * { $ for(intj =0; J <= M; J + +)Panax Notoginsengcout<<C[i][j]; -cout<<Endl; the } + return 0; A}
Dynamic planning Three: 0-1 knapsack problem