【问题标题】:Bron Kerbosch algorithm in c++C++ 中的 Bron Kerbosch 算法
【发布时间】:2017-05-03 11:54:57
【问题描述】:

我一直在练习我的 C++ 算法知识,但被标准 BK 实现所困。该算法输出的派系太多,我似乎不明白为什么。我将图表示为邻接表:

vector< list<int> > adjacency_list;

我的 BK 函数如下所示:

void graph::BronKerbosch(vector<int> R, vector<int> P, vector<int> X){

  if (P.empty() && X.empty()){
    result_cliques.insert(R);
  }

  for (int node : P){

    vector<int> intersection = {}, intersectionX = {};

    //N(P)
    for (int nodeP : adjacency_list[node]){
      for (int node2 : P){
        if (nodeP == node2){
          intersection.push_back(nodeP);
        }   
      }

      //N(X)
      for (int node3 : X){
        if (nodeP == node3){
          intersectionX.push_back(nodeP);
        }
      }
    }

    R.push_back(node);
    BronKerbosch(R,intersection,intersectionX);
    P.erase(remove(P.begin(),P.end(),node),P.end());
    X.push_back(node);    

  }
}

我称之为:

void graph::run_BronKerbosch(){

  vector<int> R,P,X;

  for (int i=1; i < adjacency_list.size(); i++) {
    P.push_back(i);
  }

  BronKerbosch(R,P,X);

  cout << "................\nClassic: " << result_cliques.size() << endl;
  for (auto clique : result_cliques){
    cout << "(";
    for (int node : clique){
      cout << node <<" ";
    }    
    cout << ")\n";    
  } 

}

我正在尝试实现该算法的基本版本,但我似乎在这里遗漏了一个细节。问题出在:

for (int node : P){

我应该以某种方式在第一个循环中使用 P 的副本吗? (我在相关问题中看到了这一点)

感谢您的帮助。

【问题讨论】:

  • 你最后是怎么解决的?你在哪里添加了这个 P 副本?

标签: c++ algorithm


【解决方案1】:

是的,您应该复制一份,除非您提前保留空间,以便保证不会重新分配1。 (请注意,C++ foreach 实现归结为底层的一堆迭代器。)

如果我是你,我会改写为老式的 for 循环,使用 std::size_t 迭代向量(超级学究2 将使用 std::vector&lt;int&gt;::size_type)为您当前感兴趣的向量元素编制索引。在读取P 的最后一个元素时终止。


参考资料:

1Iterator invalidation rules

2C++ for-loop - size_type vs. size_t

【讨论】:

  • 感谢您的富有洞察力的评论,如果我理解正确的话,请参阅以下内容:for(std::vector::size_type i = 0; i != v.size(); i++) { /* std::cout
  • 应该没问题。 push_back 不会使i 失效。即使i 在最后一个元素上。
  • 像魅力一样工作!谢谢。
  • @Bathsheba 为什么要使用副本?我遇到了类似的问题,但不明白为什么需要副本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-22
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多