【发布时间】:2015-09-02 18:29:37
【问题描述】:
我需要一种方法将大量连接(目前为 300k)快速分组到组中,其中每个组具有允许的最大元素数(当前为 14k),并且同一组中的所有连接不能连接到同一组观点。基本上,每个连接都在两点之间,我需要将它们分组到存储桶中,其中存储桶中的连接不共享一个点。希望这是有道理的。
这是我目前所拥有的,虽然有效,但速度相当慢:
for (size_t i = 0; i < ConnectionGroups.size(); i++)
{
auto& group = ConnectionGroups[i];
if (group.size() < MaxConnectionGroupSize) // Has room for us...
{
int validGroupIdx = i;
for (size_t gIdx = 0; gIdx < group.size(); gIdx++)
{
const auto groupConnection = ConnectionsQuickAccess[group[gIdx]];
// Are we directly connected to one of the Connections in this group by one degree...
if (Connection.Point1 == groupConnection->Point1 || Connection.Point1 == groupConnection->Point2 ||
Connection.Point2 == groupConnection->Point1 || Connection.Point2 == groupConnection->Point2)
{
validGroupIdx = -1;
break; // We are, check the next group
}
}
if (validGroupIdx != -1)
{
ConnectionGroups[i].push_back(Connection.Slot);
Connection.Group = i;
return;
}
else
continue;
}
}
// All groups are full, create a new group
vector<int> newGroup;
newGroup.push_back(Connection.Slot);
ConnectionGroups.push_back(newGroup);
这段代码需要 29.68 秒才能完成 30 万个连接,有没有更快的方法呢?或者可能有不同的方法?
谢谢!
【问题讨论】:
-
ConnectionGroups、Connection的类型。ConnectionQuickAccess是什么? -
ConnectionGroups是一个vector<vector<int>>int指的是ConnectionQuickAccess中的indecis,Connection仅包含2 个指向它连接的点的指针和其他数据,例如它的组索引而ConnectionQuickAccess是vector<Connection*>充当访问所有已创建连接的快速方法。实际的 Connection 对象在其他地方进行管理。 -
我认为,如果你有一个容器而不是
vector<Connection*>来保存按照Point1和/或Point2排序的数据,如set或map,那么搜索将采用 4*log(n) 而不是 4*n 并且整个算法将是 n*log(n) 而不是 n^2。 -
... 甚至是 C++11 的
unordered_map或undordered_set,其中的搜索复杂度为 O(1)...
标签: c++ algorithm c++11 optimization