This method limits the item weight and backpack capacity as well as the value of an integer
#include <stdio.h>#defineN 50//The number of items is not more than 50#defineM 1000//The backpack weighs no more thanintW[n];intV[n]; ShortFlag[n];//mark the selected itemintM[N][M];//Record Item ValueintGetmax (intAintb) { returnA>b?a:b;}intGetmin (intAintb) { returnA>b?b:a;}//Note: V and W start receiving values from subscript 0voidKnapsack (intNintc) { //request M[1][c], must be from the back to the forward to beg intJmax = Getmin (w[n-1]-1, c);//demarcation Point inti,j; //cannot be loaded into a backpack for(j=0; j<=jmax;j++) M[n][j]=0; //can be loaded into a backpack for(j=w[n-1];j<=c;j++) M[n][j]= v[n-1]; //Select a 2:n-1 item for the serial number for(i=n-1;i>1; i--) {Jmax= Getmin (w[i-1]-1, c);//demarcation Point//less than the cutoff point i.e. I cannot be selected, there is m[i][j]=m[i+1][j] for(j=0; j<=jmax;j++) M[i][j]= m[i+1][j]; //greater than the cutoff point for(j=w[i-1];j<=c;j++) M[i][j]= Getmax (m[i+1][j],m[i+1][j-w[i-1]]+v[i-1]); } //determine the maximum value, because the first choice marks the end of the selection, just determine the m[1][c], so there is no need to set the demarcation point if(w[0]<=c) m[1][C] = Getmax (m[2][c],m[2][c-w[0]]+v[0]);}voidTraceback (intNintc) { for(intI=1; i<n;i++) { if(m[i][c]==m[i+1][c]) flag[i-1] =0;//has not been selected Else{ //is selected from the total weight minus The total amount of itemsflag[i-1] =1; C-=w[i-1]; } } //one last item to consider separatelyflag[n-1] = M[n][c]?1:0;}voidIschosen (intN) { for(intI=0; i<n;i++) if(Flag[i]) printf ("Sequence Number:%HD, Weight:%d, value:%d\n", i+1, W[i],v[i]);}intMain () {intN,c; printf ("Backpack Capacity:"); scanf ("%d",&c); printf ("Number of items:"); scanf ("%d",&N); printf ("Enter the weight of the item in turn:"); for(intI=0; i<n;i++) scanf ("%d",&W[i]); printf ("Enter the item value in turn:"); for(intj=0; j<n;j++) scanf ("%d",&V[j]); Knapsack (N,C); Traceback (N,C); printf ("the selected items are as follows: \ n"); Ischosen (n); printf ("Item Maximum total value:%d\n", m[1][c]); return 0;}
0-1 Backpack