我正在编写一个程序,需要根据对象的权重总和对对象进行分组。每个对象都有一个权重(int);我需要制作一组对象,其中每个组的权重总和在一个范围内,例如在800-900之间。
这是我最近的尝试:
std::vector<std::vector<int>> segmentate(std::map<int, int>* nodeMap)
{
int sumWeight = 0;
int nodeWeight = 0;
std::vector<int> copyVector;
std::vector<int> groupVector;
std::vector<std::vector<int>> groups;
for (auto& c_it = nodeMap->begin(); c_it != nodeMap->end(); ++c_it)
{
copyVector.push_back(c_it->second);
}
for (auto& n_it = copyVector.begin(); n_it != copyVector.end(); ++n_it)
{
nodeWeight = *n_it;
if (nodeWeight > 800)
{
groupVector.push_back(*n_it);
groups.push_back(groupVector);
groupVector.clear();
}
else
{
sumWeight += nodeWeight;
if (sumWeight < 800)
{
groupVector.push_back(*n_it);
}
else
{
if (sumWeight > 900)
{
if (nodeWeight > 200)
{
sumWeight -= nodeWeight;
copyVector.push_back(*n_it);
copyVector.erase(n_it);
--n_it;
}
else
{
groupVector.push_back(*n_it);
groups.push_back(groupVector);
groupVector.clear();
}
}
}
}
}
return groups;
}
显然,在大多数情况下,此代码将进入无限循环,但它只是尝试解释问题的方法。有没有已知的算法来完成这项任务?如果没有,有人可以帮助我提供解决方案吗?