Dynamic Programming for 0-1 knapsack problems

Source: Internet
Author: User


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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.