暴力搜索解0-1背包问题 【转载】

背包问题是算法中的经典问题,可以用许多种方法来求解。本处详细阐述一下基于暴力搜索的背包求解。

假设有n个物体,价值和重量分别用vi和wi来表示,用暴力搜索,我们将最终的解用一个向量来表示,因此所有的解空间可以用00...00到11...11来表示。而这些数恰对应0至2^n-1的二进制转换。因此可以基于该思想,利用二进制转换进行暴力搜索。

参考代码如下:

  1. #include <stdio.h>
  2. #include <math.h>
  3. int main()
  4. {
  5. int num,maxv=0;
  6. int n, c, *w, *v, tempw, tempv;
  7. int i,j,k;
  8. printf("input the number and the volume:");
  9. scanf("%d%d",&n,&c);
  10. w=new int [n];
  11. v=new int [n];
  12. printf("input the weights:");
  13. for(i=0;i<n;i++)
  14. scanf("%d",&w[i]);
  15. printf("input the values:");
  16. for(i=0;i<n;i++)
  17. scanf("%d",&v[i]);
  18. for(num=0;num<pow(2,n);num++) //每一个num对应一个解
  19. {
  20. k=num; tempw=tempv=0;
  21. for(i=0;i<n;i++) //n位二进制
  22. {
  23. if(k%2==1){ //如果相应的位等于1,则代表物体放进去,如果是0,就不用放了
  24. tempw+=w[i];
  25. tempv+=v[i];
  26. }
  27. k=k/2; //二进制转换的规则
  28. }
  29. //循环结束后,一个解空间生成,
  30. //判断是否超过了背包的容积,
  31. //如果没有超,判断当前解是否比最优解更好
  32. if(tempw<=c){
  33. if(tempv>maxv)
  34. maxv=tempv;
  35. }
  36. }
  37. printf("the result is %d. ",maxv);
  38. return 0;
  39. }
                                    </div>
                                        </div>
无欲则刚 关心则乱
原文地址:https://www.cnblogs.com/xjyxp/p/11338769.html