http://www.cnblogs.com/Anker/archive/2013/05/04/3059070.html
编程实现
现在给定3个物品,背包的容量为50磅。物品1重10磅,价值为60,物品2重20磅,价值为100,物品3重30磅,价值为120。采用动态规划可以知道最优解为220,选择物品2和3。采用C++语言实现如下:
1 #include <iostream> 2 using namespace std; 3 4 //物品数据结构 5 typedef struct commodity 6 { 7 int value; //价值 8 int weight; //重量 9 }commodity; 10 11 const int N = 3; //物品个数 12 const int W = 50; //背包的容量 13 14 //初始物品信息 15 commodity goods[N+1]={{0,0},{60,10},{100,20},{120,30}}; 16 int select[N+1][W+1]; 17 18 int max_value(); 19 20 int main() 21 { 22 int maxvalue = max_value(); 23 cout<<"The max value is: "; 24 cout<<maxvalue<<endl; 25 int remainspace = W; 26 //输出所选择的物品列表: 27 for(int i=N; i>=1; i--) 28 { 29 if (remainspace >= goods[i].weight) 30 { 31 if ((select[i][remainspace]-select[i-1][remainspace-goods[i].weight]==goods[i].value)) 32 { 33 cout << "item " << i << " is selected!" << endl; 34 remainspace = remainspace - goods[i].weight;//如果第i个物品被选择,那么背包剩余容量将减去第i个物品的重量 ; 35 } 36 } 37 } 38 return 0; 39 } 40 int max_value() 41 { 42 //初始没有物品时候,背包的价值为0 43 for(int w=1;w<=W;++w) 44 select[0][w] = 0; 45 for(int i=1;i<=N;++i) 46 { 47 select[i][0] = 0; //背包容量为0时,最大价值为0 48 for(int w=1;w<=W;++w) 49 { 50 if(goods[i].weight <= w) //当前物品i的重量小于等于w,进行选择 51 { 52 if( (goods[i].value + select[i-1][w-goods[i].weight]) > select[i-1][w]) 53 select[i][w] = goods[i].value + select[i-1][w-goods[i].weight]; 54 else 55 select[i][w] = select[i-1][w]; 56 } 57 else //当前物品i的重量大于w,不选择 58 select[i][w] = select[i-1][w]; 59 } 60 } 61 return select[N][W]; //最终求得最大值 62 }
程序测试结果如下: