01背包问题-动态规划源码

#include
#include
#include
#define max(a,b) (((a) > (b)) ? (a) : (b))
using namespace std;

int M[100][100]={0};
int Value[100]={0};
int Weight[100]={0};
bool Select[100]={0};

int Bag(int,int);
void Selected(int,int);

int main(int argc,char * argv[])
{
int ObjectNum=0;
int Capacity=0;
cout<<"Please input the number of the objects:"<<endl;
cin>>ObjectNum;
cout<<"Please input the value and weight of each object:"<<endl;
for(int i=1;i<=ObjectNum;i++)
{
cout<<"Number "<<i<<':'<<endl;
cin>>Value[i]>>Weight[i];
}
cout<<"Please input the capacity:"<<endl;
cin>>Capacity;
cout<<"The result is:"<<endl;
cout<<Bag(ObjectNum,Capacity)<<endl;
cout<<"The Matrix:"<<endl<<"   ";
for(int i=1;i<=ObjectNum;i++)
{
for(int j=1;j<=Capacity;j++)
{
cout<<M[i][j]<<setw(3);
}
cout<<endl;
}
// Selected(ObjectNum,Capacity);
cout<<"Accroading to the Selected matrix(";
for(int i=1;i<=ObjectNum;i++)
{
cout<<Select[i]<<' ';
}
cout<<"),\n the selected objects are:"<<endl;
for(int i=1;i<=ObjectNum;i++)
{
if(Select[i])
cout<<"No."<<i<<' ';
}
cout<<endl;
system("pause");
return 0;
}

int Bag(int ObjectNum,int Capacity)
{
for(int i=1;i<=ObjectNum;i++)
{
for(int j=1;j<=Capacity;j++)
{
if(j
{
M[i][j]=M[i-1][j];
}
else
{
M[i][j]=max(M[i-1][j],(M[i-1][j-Weight[i]]+Value[i]));
}
}
}
int c=Capacity;
    for(int i=ObjectNum;i>=1;i--)
    {
if(M[i][c]>M[i-1][c])
        {
        Select[i]=1;
        c=c-Weight[i];
        }
    else
        Select[i]=0;    
    }
return M[ObjectNum][Capacity];
}


void Selected(int ObjectNum,int Capacity)
{
cout<<"The selected objects:"<<endl;
Select[1]=M[1][Capacity]==0? 0:1;
for(int i=ObjectNum;i=1;i--)
{
if(M[i][Capacity]>M[i-1][Capacity])
{
Select[i]=1;
Capacity=Capacity-Weight[i];
}
else
Select[i]=0;
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值