当前位置:   article > 正文

0/1背包问题(蛮力法)_6-1 0/1背包问题(蛮力法)

6-1 0/1背包问题(蛮力法)

实验要求:

用蛮力法解决0/1背包问题

输入要求:

  • 第一行输入2个整数,分别代表物品数量n(1<=n<=10)和背包容量C(1<=C<=100);接下来输入n行,每行输入2个整数,分别代表物品的重量和价值。

输出要求:

  • 第1行输出一个整数,表示可行解的数量。可行解指的是物品可以放入背包中的解决方案。
  • 第2行输出最优解对应的物品重量和价值,用空格分隔。最有解指的是具有最大价值的可行解。

例子

输入:

4 6
5 4
3 4
2 3
1 1
  • 1
  • 2
  • 3
  • 4
  • 5

输出:

10
6 8
  • 1
  • 2

代码


#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;
 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号