您的位置:首页 > 其它

暴力搜索解0-1背包问题

2015-06-06 11:29 561 查看
背包问题是算法中的经典问题,可以用许多种方法来求解。本处详细阐述一下基于暴力搜索的背包求解。
假设有n个物体,价值和重量分别用vi和wi来表示,用暴力搜索,我们将最终的解用一个向量来表示,因此所有的解空间可以用00...00到11...11来表示。而这些数恰对应0至2^n-1的二进制转换。因此可以基于该思想,利用二进制转换进行暴力搜索。

参考代码如:

#include <stdio.h>
#include <math.h>

int main()
{
int num,maxv=0;
int n, c, *w, *v, tempw, tempv;
int i,j,k;

printf("input the number and the volume:");
scanf("%d%d",&n,&c);

w=new int
;
v=new int
;

printf("input the weights:");
for(i=0;i<n;i++)
scanf("%d",&w[i]);

printf("input the values:");
for(i=0;i<n;i++)
scanf("%d",&v[i]);

for(num=0;num<pow(2,n);num++) //每一个num对应一个解
{
k=num; tempw=tempv=0;
for(i=0;i<n;i++) //n位二进制
{
if(k%2==1){     //如果相应的位等于1,则代表物体放进去,如果是0,就不用放了
tempw+=w[i];
tempv+=v[i];
}
k=k/2;          //二进制转换的规则
}
//循环结束后,一个解空间生成,
//判断是否超过了背包的容积,
//如果没有超,判断当前解是否比最优解更好
if(tempw<=c){
if(tempv>maxv)
maxv=tempv;
}
}

printf("the result is %d.\n",maxv);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: