合并索引对的最佳算法

Best algorithm to merge pair of connected indices

本文关键字:最佳 算法 索引 合并      更新时间:2023-10-16

我有以下问题的定义和搜索的有效方式(肮脏的方式已经找到):

我有一组与整数id的对应,例如:

(0, 9)(1、5)(9日2)(2、3)

我想要的是一组包含有连接对应的数组,在我的例子中是

(0、9、2、3)(1、5)

我的数据集真的很大,所以我需要它非常高效,最好在c++和tbb。我目前所做的和工作的(但实际上是缓慢和单线程):

struct point
{
  std::set<size_t> others;
};
std::map<size_t, point> globalList;
//globalList is filled with input data set, for my example:
globalList[0].others.insert(0);
globalList[0].others.insert(9);
globalList[1].others.insert(1);
globalList[1].others.insert(5);
globalList[9].others.insert(9);
globalList[9].others.insert(2);
globalList[2].others.insert(2);
globalList[2].others.insert(3);
bool changed;
do
{
changed = false;
for (auto it1 = globalList.begin(); it1 != globalList.end(); ++it1 )
{
   for (auto it2 = it1 ; it2 != globalList.end(); ++it2 )
   {
      if (it2 == it1 )
        continue;
      auto findIt = it2->second.others.find(it1->first);
      bool merge = false;
      if( findIt != it2->second.others.end())
      {
        merge = true;
      }
      else
      {
        for( auto otherIt = it1->second.others.begin(); otherIt != it1->second.others.end(); ++otherIt )
        {
          findIt = it2->second.others.find(*otherIt );
          if (findIt != it2->second.others.end())
          {
            merge = true;
            break;
          }
        }
      }
      if(merge )
      {
         it1->second.others.insert(it2->second.others.begin(), it2->second.others.end());
         auto it2remove = it2;
         --it2;
         globalList.erase(it2remove );
         changed= true;
       }
     }
   }
  } while (changed);
}`

任何建议,提示(链接到算法,例如在boost)或实现将是伟大的....

你要做的基本上是在一个图中找到连接的组件。在你的例子中,你从一组边开始(每对边是一条边)。

有一个boost图形库,它有一个实现。

这看起来像是在树中寻找最长的路径。你用循环做什么?我会尝试用树形或图形存储你的项目

您正在寻找Union FindDisjoint Set Data Structure

一个有效的实现沿着和一个伟大的教程可以在这里找到。