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

本文介绍了一种使用动态规划解决背包问题的方法,通过计算所有物品的不同组合方式来找到不超过指定重量下能获得的最大价值。通过递归计算字符串表示的二进制数对应的物品价值,实现了一个GetMaxValue函数来寻找最优解。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<string>
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;
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值