C++ 遍历 vector 拷贝

标签 c++ algorithm graph

我正在尝试实现 Bron-Kerbosch 算法,这是一种用于查找派系的递归算法。我设法达到了一个点,它返回了正确数量的派系,但是当我打印它们时,它们不正确 - 添加了额外的节点。我在这里遗漏了什么明显的东西吗?

我正在使用邻接表结构:

vector< list<int> > adjacency_list;

我按以下方式添加边的位置:

void graph::addEdge(int i1,int i2){

  //as this is an undirected graph  
  adjacency_list[i1].push_back(i2);
  adjacency_list[i2].push_back(i1);

}

主要算法如下:

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

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

  //  vector <int> tmpVerts = P;
  for(std::vector<int>::iterator it = P.begin(); it != P.end();) {

    vector<int> intersection = {}, intersectionX = {};
    int node = *it;

    //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());
    P.erase(it); 
    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";    
  } 

}

以下图形输入的输出问题:

1 2
1 3
2 3

是,这段代码返回:

(1 2 3 )
(1 2 3 4 )
(1 2 3 4 5 )

而它应该返回(为此使用 python):

(1 2 3 )
(2 4 )
(2 5 )

非常感谢您的帮助。

最佳答案

wikipedia page ,递归调用如下所示:

for each vertex v in P:
    BronKerbosch1(R ⋃ {v}, P ⋂ N(v), X ⋂ N(v))
    ...

在问题的代码中,您在递归调用之前执行了 R.push_back(node),但该节点将在所有后续迭代中包含在 R 中循环,这是不正确的。

即如下指令:

R.push_back(node);
BronKerbosch(R,intersection,intersectionX);

可能应该在递归调用之后紧跟一个 R.pop_back(node)

关于C++ 遍历 vector 拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44005413/

相关文章:

algorithm - 检测偶数循环的图形算法

c++ - 使用重叠 IO 写入文件与在单独线程中写入文件

c# - 扩展 ArrayList 和实现 IEnumerable - 有更好的方法吗?

javascript - 具有奇数个顶点的 D3.js 树,未显示边

在加权有向图中寻找权重最低的路径权重的算法

algorithm - 如何以编程方式计算不定积分

return 语句中的 C++11 显式转换运算符/构造函数

c++ - 读取二进制文件到整数数组

c++ - 为什么允许 C++ 类具有零数据成员?

algorithm - C#中DCT、DFT的简洁实现?