Greedy method: always make the best choice for the current problem, that is, local optimization. Finally, the overall optimization is obtained.
Application: 1: this problem can be gradually transitioned to "Overall Optimization" through "local optimization", which is the main difference between greedy choice and "dynamic planning.
2: optimal sub-structure: the overall optimal solution of a problem includes the optimal solution of the subproblem.
The complete code is as follows:
# Include "iostream" using namespace STD; struct goodinfo {float P; // item benefit float W; // item weight float X; // int flag; // item number}; // void insertionsort (goodinfo goods [], int N) {Int J, I; for (j = 2; j <= N; j ++) {goods [0] = goods [J]; I = J-1; while (goods [0]. p> goods [I]. p) {goods [I + 1] = goods [I]; I --;} goods [I + 1] = goods [0] ;}/// benefit by item, weight Ratio in ascending order void bag (goodinfo goods [], float M, int N) {float Cu; int I, j; for (I = 1; I <= N; I ++) goods [I]. X = 0; Cu = m; // remaining backpack capacity for (I = 1; I <n; I ++) {If (goods [I]. w> Cu) // when the weight of the item is large and the remaining capacity jumps out of break; goods [I]. X = 1; Cu = Cu-goods [I]. w; // determine the new remaining size of the backpack} if (I <= N) goods [I]. X = Cu/goods [I]. w; // The quantity of the item to be placed // sort by item number in descending order for (j = 2; j <= N; j ++) {goods [0] = goods [J]; I = J-1; while (goods [0]. flag <goods [I]. flag) {goods [I + 1] = goods [I]; I --;} goods [I + 1] = goods [0];} cout <"the optimal solution is: "<Endl; for (I = 1; I <= N; I ++) {cout <" no. "<I <" items to be placed :"; cout <goods [I]. x <Endl ;}int main (void) {cout <"| -------- solve the knapsack problem using greedy method --------- |" <Endl; cout <"| ----------------------------------- |" <Endl; int I, j, N; float m; goodinfo * goods; // define a pointer cout <"press <1> to run the program" <Endl; cout <"press <0> to exit" <Endl; cin> J; while (j) {cout <"Enter the total number of items:"; CIN> N; goods = new struct goodinfo [n + 1]; cout <"Enter the maximum capacity of the backpack:"; CIN> m; cout <Endl; for (I = 1; I <= N; I ++) {goods [I]. flag = I; cout <"Enter the" <I <"Weight of the item:"; CIN> goods [I]. w; cout <"Enter the" <I <"item benefits:"; CIN> goods [I]. p; goods [I]. P = goods [I]. p/goods [I]. w; // obtain the benefit of the item, weight ratio cout <Endl;} insertionsort (goods, n); bag (goods, m, n ); cout <"press <1> to run agian" <Endl; cout <"press <0> to exit" <Endl; CIN> J ;} system ("pause"); Return 0 ;}