gpt4 book ai didi

c++ - 在 C++ 中使用回溯的背包解决方案

转载 作者:行者123 更新时间:2023-11-28 00:27:27 24 4
gpt4 key购买 nike

我在尝试使用回溯法解决背包问题时遇到了麻烦。

例如,对于以下值,Knapsack 函数将返回 14 作为解,但正确的结果应该是 7。

int n = 3, weights[] = {2, 3, 1}, values[] = {6, 15, 7};

int solution = 0, max = 2;


void Knapsack (int i, int max, int value, int *solution)
{
int k;

for (k = i; k < n; k++) {
if (weights[k] <= max) {
Knapsack (k, max - weights[k], value + values[k], solution);

if (value+ values[k] > *solution)
*solution= value + values[k];
}
}
}

这里有什么问题?

最佳答案

#include<iostream>
#include<vector>

using namespace std;

int weights[] = {2, 3, 1}, values[] = {6, 15, 7};

int solution = 0, n = 3;

std::vector<int> vsol;
std::vector<int> temp;

bool issol;


void Knapsack (int i, int max, int value)
{
for (int k = i; k < n; k++) {
if ( max > 0)
{
if (weights[k] <= max)
{
temp.push_back(k);
if (value+ values[k] >= solution)
{
solution = value + values[k];
issol = true;
}
}
if ( (k+1) < n)
{
Knapsack (k+1, max - weights[k], value + values[k]);
}
else
{
if (issol == true)
{
if (! vsol.empty()) vsol.clear();
std::move(temp.begin(), temp.end(), std::back_inserter(vsol));
temp.clear();
issol = false;
} else temp.clear();
return;
}
}
else
{
if (issol == true)
{
if (! vsol.empty()) vsol.clear();
std::move(temp.begin(), temp.end(), std::back_inserter(vsol));
temp.clear();
issol = false;
} else temp.clear();
return;
}
}
}

int main()
{
Knapsack(0, 2, 0);
cout << "solution: " << solution << endl;
for(vector<int>::iterator it = vsol.begin(); it != vsol.end(); it++)
cout << *it << " ";
return 0;
}

再次调用Knapsack函数时需要将k加1,索引向前移动。

添加了代码以打印出解决方案的索引位置。如果存在多个解决方案(即相同总数),将只打印出最后一个解决方案的位置。

关于c++ - 在 C++ 中使用回溯的背包解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24255082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com