数据结构上机实验五——01背包问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21385857/article/details/51427246
  01背包问题

编写一个程序,求解背包问题:设有不同价值、不同重量的物品n件,求从这n件物品中选取一部分物品的方案,使选中物品的总重量不超过指定的限制重量,但选中物品的总价值最大。

代码:

#include <iostream>

using namespace std;
int sum=0;  //保存书包存放物品的最大价值
struct item
{
    int value;
    int weight;
} a[99];
bool f(int WeightMax,int num)
{
    if(WeightMax==0)
        return true;
    if(WeightMax<0||(WeightMax>0&&num<0))
        return false;
    if(f(WeightMax-a[num-1].weight,num-1))
    {
        cout<<"  第"<<num<<"种物品"<<endl;
        sum+=a[num-1].value;
        return true;
    }
    else
        return f(WeightMax,num-1);
}
int main()
{
    int num,WeightMax;
    char ch;
    cout << "物品种类:";
    cin>>num;
    for(int i=0; i<num; i++)
    {
        cout<<"  第"<<i+1<<"种物品(重量,价值):";
        cin>>a[i].weight>>ch>>a[i].value;
    }
    cout<<"背包所能承受的最大重量是:";
    cin>>WeightMax;
    cout<<"最佳装填方案是:"<<endl;
    f(WeightMax,num);
    cout<<"总价值="<<sum<<endl;
    return 0;
}



猜你喜欢

转载自blog.csdn.net/qq_21385857/article/details/51427246