赞
踩
用蛮力法解决0/1背包问题
例子
输入:
4 6
5 4
3 4
2 3
1 1
输出:
10
6 8
#include<iostream> #include<math.h> using namespace std; int main() { int n,c; //n物品个数 ,c背包容量 cin >> n >> c; int w[10]; int v[10]; for(int i=0;i<n;i++){ //重量和价值 cin >> w[i]; cin >> v[i]; } // int w[5]={2,2,6,5,4},v[5]={6,3,5,4,6}; int max=0; //每轮最大价值 int max1=0; //最终最大价值 int weight=0; int weight1=0; int count = 0; //可行方案的数量 for(int i=0;i<pow((double)2,(double)n);i++) //遍历每一种情况 { int maxV[10]={0}; //物品是否放进,1放进,0不放 int temp =i; for(int j=0; j<n; j++) { if (temp%2 != 0) maxV[j]=1; temp=temp/2; } // cout<<"第"<<i+1<<"种情况:"<<endl; for(int i=0;i<n;i++) { // cout<<maxV[i]<<" "; max += v[i]*maxV[i]; weight+=w[i]*maxV[i]; } // cout<<endl<<"最大价值是:"<<max<<endl; // cout<<"重量是:"<<weight<<endl<<endl; if(weight<=c){ count++; } if(weight<= c && max >max1) { max1=max; weight1=weight; } max=0; weight=0; } cout << count << endl; cout << weight1 << " " << max1 << endl; // cout <<"可行 "<< count << endl; // cout<<endl<<endl<<"最大重量是:"<<weight1<<endl; // cout<<endl<<endl<<"最大价值是:"<<max1<<endl; return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。