。
We provide a complete C language source code for the Dynamic Programming solution of the 0-1 knapsack problem to be tested:
#include<stdio.h>#include<stdlib.h>void knappsack(int *w,int *v,int c,int n,int m[][10]){int k=n-1;int t_v;for(int j=0;j<c;j++){if(j<w[k]-1)m[k][j]=0;else m[k][j]=v[k];}for(int i=k-1;i>=0;i--){for(int j=0;j<c;j++){if(j<w[i]-1){m[i][j]=m[i+1][j];}else{int temp,t_v;t_v=j-w[i]+1;if(t_v>0)t_v--;temp=m[i+1][t_v]+v[i];m[i][j]=temp>m[i+1][j]?temp:m[i+1][j];}}}m[0][9]=m[1][9];if(c>w[0]){t_v=m[1][c-w[0]-1]+v[0];m[0][9]=t_v>m[1][9]?t_v:m[1][9];}}void Traceback(int m[][10],int *w,int c,int *x,int n){for(int i=0;i<n-1;i++){if(m[i][c-1]==m[i+1][c-1])x[i]=0;else{x[i]=1;c-=w[i];}}x[n-1]=(m[n-1][c-1])?1:0;}int main(){int n,c,w[5]={2,2,6,5,4},v[5]={6,3,5,4,6},m[5][10],x[5];n=5;c=10;knappsack(w,v,c,5,m);Traceback(m,w,c,x,5);for(int i=0;i<5;i++){for(int j=0;j<10;j++)printf("%3d",m[i][j]);printf("\n");}for(int i=0;i<5;i++)printf("%3d",x[i]);printf("\n %3d\n",m[0][9]);}
Computing complexity analysis: From the recursive formula of M (I, j), we can see that knw.ack () requires O (NC) computing time, while traceback () requires O (n) time, therefore, the overall computing time complexity is O (NC ). However, there is a potential problem. When C> 2n, the computing time changes to O (n2n), which reduces the efficiency.
0-1 backpacks cannot be solved using greedy algorithms. The reason is that greedy choices cannot ensure that the backpack is full at last. Although it increases the value of the loaded items per unit capacity, however, the free space will reduce the unit value. All in all, the 0-1 backpack problem is not greedy.