您的位置:首页 > 其它

01背包问题回溯法和动态规划

2014-07-25 18:14 477 查看
题目要求:

输入背包的容量v和物品的数量n;接下来n 行每行输入两个数字,第一个是物品质量,第二个是物品价值;

输出背包容纳物品的最大价值。

下面直接贴代码:

回溯法

#include<iostream>//之前必须知道背包容量和n个物品
#include<algorithm>
using namespace std;
class Property
{
public:
int weight,profit;
double average;
friend bool operator<(Property a,Property b)
{
return a.average>b.average;
}
};
class Pack
{
public:
Pack(int Q,int n)//构造函数,初始化
{
capcity=Q;
number=n;
property=new Property[n+1];
bestp=cw=cp=0;
}
~Pack()
{
delete []property;
}
void inputproperty()
{
for(int i=0;i<number;i++)
{
cin>>property[i].weight>>property[i].profit;
property[i].average=1.0*property[i].profit/property[i].weight;
}
sort(property,property+number);
}
int command()
{
int totalweight=0;
int totalvalue=0;
for(int i=0;i<number;i++)
{
totalweight+=property[i].weight;
totalvalue+=property[i].profit;
}
if(totalweight<capcity)return totalvalue;
backtrack(0);
return bestp;
}
bool bound(int i)
{
int currentp=cp;
int currentw=capcity-cw;
while(currentw>=property[i].weight&&i<number)
{
currentw-=property[i].weight;
currentp+=property[i].profit;
i++;
}
if(i<number)
currentp+=1.0*property[i].profit*currentw/property[i].weight;
return currentp>bestp;
}
void backtrack(int i)
{
if(i>number-1)
{
if(bestp<cp)
bestp=cp;
return;
}
if(cw+property[i].weight<=capcity)//此处必须用<=比较符号,不然会错
{
cw+=property[i].weight;
cp+=property[i].profit;
backtrack(i+1);
cw-=property[i].weight;
cp-=property[i].profit;
}
if(bound(i+1));
backtrack(i+1);
}
private:
int capcity,number;
Property *property;
int cw,cp,bestp;
};
int main()
{
int n,m;
while(cin>>n>>m)
{
Pack object(n,m);
object.inputproperty();
cout<<object.command()<<endl;
}
return 0;
}


输入:

20 5
4 7
5 8
2 10
5 10
8 16

输出:
44

[b]动态规划法[/b]

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int Capcity,weight;
int *w,*p;
int profit[200][200];
while(cin>>Capcity>>weight)
{
memset(profit,0,sizeof(profit));
w=new int[weight+1];
p=new int[weight+1];
for(int i=1;i<=weight;i++)
cin>>w[i]>>p[i];//输入重量和价值
for(int i=1;i<=weight;i++)
{
for(int j=1;j<=Capcity;j++)
{
if(w[i]>j)profit[i][j]=profit[i-1][j];
else if(profit[i-1][j]<profit[i-1][j-w[i]]+p[i])
profit[i][j]=profit[i-1][j-w[i]]+p[i];
else profit[i][j]=profit[i-1][j];
}
}
for(int i=1;i<=weight;i++)
{
for(int j=1;j<=Capcity;j++)
{
cout<<profit[i][j]<<" ";
}
cout<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: