有没有解决方案而不是在C++中移动背包回溯算法
Is there a solution instead of move for knapsack backtracking algorithm in C++
我用C++使用了背包回溯解决方案的解决方案。我从这里再次有了解决方案。带有 C++ 中反向跟踪的背包解决方案我的编译器在行移动时出错。有没有不使用移动的解决方案?如何在不使用移动的情况下修改代码?
#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;
}
您可以使用
std::copy
更改std::move
。一般来说,它们不是等效的,但在这里你使用的是 int
向量(因此没有性能损失),并且源数组立即被清除(temp.clear()
)。
所以你可以写:
if (!vsol.empty()) vsol.clear();
std::copy(temp.begin(), temp.end(), std::back_inserter(vsol));
事实上,这是想多了。简单:
vsol = temp;
清晰,快速,并且也适用于C++98(取决于您的C++Builder版本,C++11兼容性可能是一个问题)。
修改后的版本:
#include <iostream>
#include <vector>
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)
{
vsol = temp;
issol = false;
}
temp.clear();
return;
}
}
else
{
if (issol)
{
vsol = temp;
issol = false;
}
temp.clear();
return;
}
}
}
int main()
{
Knapsack(0, 2, 0);
std::cout << "solution: " << solution << 'n';
for(std::vector<int>::iterator it = vsol.begin(); it != vsol.end(); ++it)
std::cout << *it << " ";
return 0;
}
相关文章:
- 将对象移动到std::shared_ptr
- 何时在引用或唯一指针上使用移动语义
- 如何从具有移动语义的类对象中生成共享指针
- 将shared_ptr移动到<StructA>shared_ptr<变体<结构A、结构 B>>
- C / C++ 移位/偏移/向左或向右移动位图?
- 0-1背包代码中的错误.我的代码中有什么错误
- MSVC将仅移动结构参数解释为指针
- 自定义先决条件对移动分配运算符有效吗
- 返回值优化:显式移动还是隐式
- 当有分配器意识的容器被复制/移动时,反弹分配器是否被复制/移走
- 为什么复制而不是移动数据元素?
- 可以使用移动语义更改或改进此C++代码吗?
- 使lambda不可复制/不可移动
- c++在使用指针时移动语义
- 将QGraphicsItem的移动区域限制在多边形区域内
- SendInput()鼠标移动计算
- 按值 C++ 返回时进行双倍移动
- 移动二维数组中的字符
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 有没有解决方案而不是在C++中移动背包回溯算法