0-1 knapsack problem

Hello,everyone.Today i want to show you the 0-1 Knapsack problem,which is based on dynamic programming.Although i can solve this problem,but i still do not  have a good command at the dynamic programming.So i want to take it done in three days.Do not believe it?I will show you.^_^

Have fun coding,i_human.Have fun coding,everyone!

THE CODE:


#include "stdafx.h"
#include<iostream>
#define a 100


using namespace std;


int b[a][a];
int re[a];


int put(int v[],int we[],int n,int w);


int main()
{
int n,w;
int we[a];
int v[a];
cin>>n>>w;
for(int i=1;i<=n;i++)
{
cin>>v[i];
cin>>we[i];
}
for(int i=1;i<a;i++)
for(int j=1;j<a;j++)
b[i][j]=-1;
put(v,we,n,w);
for(int i=1;i<=n;i++)
cout<<re[i]<<" ";
cout<<endl<<put(v,we,n,w);
system("pause");
return 0;
}


int put(int v[],int we[],int n,int w)
{
if(b[n][w]!=-1)
return b[n][w];
if(n==1 && w>=we[1])
{
b[1][w]=v[1];
re[n]=1;
return v[1];
}
else if(n==1 && w<we[1])
{
b[1][w]=0;
re[n]=0;
return 0;
}
else
{
if(v[n]+put(v,we,n-1,w-we[n])>put(v,we,n-1,w) && w-we[n]>=0)
{
re[n]=1;
b[n][w]=v[n]+put(v,we,n-1,w-we[n]);
return v[n]+put(v,we,n-1,w-we[n]);
}
else
{
re[n]=0;
b[n][w]=put(v,we,n-1,w);
return put(v,we,n-1,w);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值