usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceseqlistsort{/// <summary> /// <ather> ///Lihonglin/// </ather> /// <content> ///problem Description: There are n items and a backpack with a capacity of C. The value of article I is v[i] and the weight is w[i]. Solve which items are loaded into///The backpack is the most valuable sum. When loading the backpack, each item I have only two options, loading or not loading, can not be loaded multiple times,///You can't just load part of it. Therefore, this issue is called a 0-1 knapsack problem///knapsack problem can be seen as a backtracking: each packet is a node, the node has 2 candidate values of 0, 1. 0 for the non-release backpack, 1 for the backpack. /// </content> /// </summary> classknapsack {Static intn =5;//Number of items Static intc =Ten;//Backpack Capacity Static int[] Weight =New int[] {2,2,6,5,5};//weight of each item Static int[] Value =New int[] {6,3,5,4,6};//the value of each item Static intMax =0;//Max: Record maximum value Static int[] A =New int[n];//Array holds the current solution selection of the items//A[i]=0 said I do not select the article I, A[i]=1 said to select the article I item Static voidCheckmax () {inti =0; intCurweight =0;//the weight of the current item intCurvalue =0;//the value of the current item for(i =0; I < n; i++) { if(A[i] = =1)//If the item is selected{curweight+ = Weight[i];//Cumulative WeightCurvalue + = Value[i];//Cumulative Value } } if(Curweight <= C)//If the solution is feasible if(Curvalue > Max)//and the value is greater than Max{Max= Curvalue;//Replace Max } } Public Static voidSearch (intm) {if(M >=N) Checkmax (); //checks if the current solution is a viable solution, and if it compares its value to Max Else{A[m]=1;//Optional Item MSearch (M +1);//search for the next item recursivelyA[M] =0;//do not select article m itemsSearch (M +1);//search for the next item recursively } } Public Static voidPrintresult () {Console.WriteLine ("Maximum Value"+max); } }}
Retrospective algorithm of 0-1 knapsack problem