栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

蛮力法求解01背包问题(C++实现)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

蛮力法求解01背包问题(C++实现)

#include
#include
using namespace std;

int Pow(const int& base,const int& n)
{
	int result = 1;
	for (int i = 0; i < n; i++)
	{
		result *= base;
	}
	return result;
}

string getString(int i)
{
	string result;
	while (i != 0)
	{
		char c = i % 2 +'0';
		result += c;
		i = i / 2;
	}
    result.reserve();
	return result;
}

int GetMaxValue(int* weights, int* values, const int& n,const int& weight)
{
	int maxValue = 0;
	for (int i = 0; i < Pow(2, n); i++)
	{
		int tempValue = 0;
		int tempWeight = 0;
		string str = getString(i);
		for (int i = 0; i < str.length(); i++)
		{
			if (str[i] == '1')
			{
				tempValue += values[i+n-str.length()];
				tempWeight += weights[i + n - str.length() ];
			}
		}
		if (tempWeight <= weight)
		{
			if (maxValue < tempValue)
			{
				maxValue = tempValue;
			}
		}
	}
	return maxValue;
}

int main(void)
{
	int n;
	cout << "请输入物品的数量:";
	cin >> n;
	int maxWeight;
	cout << "请输入包的最大承重:";
	cin >> maxWeight;
	int* weights = new int[n];
	int* values = new int[n];
	cout << "请输入每件物品的重量:";
	for (int i = 0; i < n; i++)
	{
		cin >> weights[i];
	}
	cout << "请输入每件物品的价值:";
	for (int i = 0; i < n; i++)
	{
		cin >> values[i];
	}
	int maxValue = GetMaxValue(weights, values, n, maxWeight);
	cout << "最大价值是:" << maxValue << endl;
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/892956.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号