我正在寻找一种算法来实现以下行为。如果当前和后续元素的总和小于或等于先前元素,则将总和添加到新矢量。以下是示例:
Ex 1:
original vector: 17 | 10 | 6 | 3 | 2
new vector: 17 | 16 | 5
前2:
original vector: 41 | 15 | 10 | 5 | 2
new vector: 41 | 32
前3:
original vector: 1 | 1 | 1 | 1 | 1
new vector: 1 | 1 | 1 | 1 | 1
以下代码有效,但可能存在此代码失败的情况。我很确定,一个月后我会忘记自己代码的细节。我想使用可靠的代码。是否有标准算法可能在std或boost中执行我提到的内容?
#include<vector>
#include<iostream>
void augmented_sort(const std::vector<double>& invec, std::vector<double>& outvec)
{
if (invec.empty()) return;
outvec.push_back(invec[0]);
auto augment = [&invec](double& current, double previous, int& ai)
{
if (ai >= invec.size()) return false;
int start = ai;
current = invec[ai];
int ri = 1;
while(true)
{
current += invec[start+ri];
std::cout << "previous = " << previous << std::endl;
std::cout << "current = " << current << std::endl;
if (current <= previous)
{
++ri;
ai += 2;
std::cout << "ri = " << ri << std::endl;
std::cout << "ai = " << ai << std::endl;
if (start+ri >= invec.size())
return true;
}
else if (ai == start)
return false;
else
{
current -= invec[start+ri];
return true;
}
}
};
int ai = 1; // absolute index. start from second element.
double current;
double previous = invec[ai-1];
while (ai < invec.size())
{
bool success = augment(current, previous, ai);
if (success)
{
outvec.push_back(current);
previous = current;
}
else
{
outvec.push_back(invec[ai]);
previous = invec[ai];
ai += 1;
}
}
}
int main ()
{
//std::vector<double> invec = {17, 10, 6, 3, 2};
//std::vector<double> invec = {41, 15, 10, 5, 2};
std::vector<double> invec = {1, 1, 1, 1, 1};
std::vector<double> outvec;
augmented_sort(invec, outvec);
for (double d: outvec)
std::cout << "d = " << d << std::endl;
return 0;
}