#include<stdio.h>intmain(){int v[]={0,1500,2000,3000};//价值 int w[]={0,1,3,4};//重量 int W =4;//背包重量 int n =sizeof(v)/sizeof(int)-1;int c[n+1][W+1];int i,j;for(i=0;i<=n;i++){for(j=0;j<=W;j++){
c[i][j]=0;}}for(j=0;j<=W;j++){
c[0][j]=0;}for(i=1;i<=n;i++){
c[i][0]=0;for(j=1;j<=W;j++){if(w[i]<=j){if((v[i]+c[i-1][j-w[i]])>(c[i-1][j]))
c[i][j]=(v[i]+c[i-1][j-w[i]]);else
c[i][j]=(c[i-1][j]);}else{
c[i][j]=(c[i-1][j]);}}}for(i=0;i<=n;i++){for(j=0;j<=W;j++){printf("%d\t",c[i][j]);}printf("\n");}printf("total value:%d\n",c[n][W]);int remainspace = W;//定义剩余空间 //输出所选择的物品列表:for(int i=n; i>=1; i--){if(remainspace >= w[i]){if(c[i][remainspace]-c[i-1][remainspace-w[i]]==v[i]){printf("%d is selected! it's value is %d\n",i,v[i]);
remainspace = remainspace - w[i];//如果第i个物品被选择,那么背包剩余容量将减去第i个物品的重量 ;}}}}
0-1背包问题的动态规划方法#include<stdio.h>int main(){ int v[] = {0,1500,2000,3000};//价值 int w[] = {0,1,3,4};//重量 int W = 4;//背包重量 int n = sizeof(v)/sizeof(int)-1; int c[n+1][W+1]; int i,j; // for(i=0;i<=n;i++)// {// for(j=0;j<=W;j++)//