gpt4 book ai didi

c++ - C++ 中的 Bron Kerbosch 算法

转载 作者:搜寻专家 更新时间:2023-10-31 02:11:20 32 4
gpt4 key购买 nike

我一直在练习我的 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 的拷贝吗? (我在相关问题中看到过这个)

感谢您的帮助。

最佳答案

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

我会重铸成一个老式的for如果我是你,循环,使用 std::size_t 遍历 vector (super-pedants2 将使用 std::vector<int>::size_type )来索引您当前感兴趣的 vector 元素。当 P 的最后一个元素结束时终止。已阅读。


引用资料:

1 Iterator invalidation rules

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

关于c++ - C++ 中的 Bron Kerbosch 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43759341/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com