算法面试---01背包问题---动态规划

来源:互联网 发布:the ludlows 知乎 编辑:程序博客网 时间:2024/06/10 00:09

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     //初始没有物品时候,背包的价值为043     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时,最大价值为048            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                    else55                     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 }
复制代码

程序测试结果如下:


0 0
原创粉丝点击