c++ - 如何在贝尔曼福特算法中检测负循环?
问题描述
以下是我用于实现用于检测图中负循环的贝尔曼福特算法的函数:
int d[V]; // V is number of vertices in the graph, d[V] is the distance of the vertices from the source vertex
vector<tuple<int,int,int>> edges; // defines edges as (u,v,w), where u and v are vertices and w is the weight b/w u and v
int u,v,w;
bool negativecycle_BF(int x){
// x is the source vertex
for(int i=1;i<=V;i++) d[i] = INF;
d[x] = 0;
for(int i=1;i<=V-1;i++){
for(auto e:edges){
tie(u,v,w) = e;
d[v] = min(d[v], d[u]+w);
}
}
for(auto e: edges){
tie(u,v,w) = e;
if(d[v]>d[u]+w)
return true;
}
return false;
}
无论我是否有负循环,我的代码都只返回 0。有人可以指出我做错了什么吗?
解决方案
您已经分配d[v]
了min(d[v], d[u]+w)
,然后您检查了其中一个(d[v]>d[u]+w)
,这永远不会是真的。因此,您总是会得到cpp中的return false
哪个。0
顺便说一句,for(auto e: edges){...}
缩进是错误的,所以如果你更正了,这将有助于更容易理解代码。
推荐阅读
- powershell - Microsoft.TeamFoundation.Client.TfsConfigurationServerFactory
- ios - 我应该重构以便能够使用 XCTests 进行模拟吗?
- groovy - 为什么Groovy不执行程序中的类,如果在类之外有一行代码?
- matlab - 在 Matlab 或 Mathematica 中处理未知数量的变量
- javascript - 试图通过 API 导航,无法通过第一层
- python - 脚本不会将标题写入 csv
- java - 使用@Mock 注释的对象是否应该设置详细值?
- pysimplegui - PysimpleGUI while 真正循环?
- r - 如何在 R 的团队云端硬盘中读取 Google 电子表格?
- amazon-web-services - Dynomodb 的 Amazon Api Gateway 服务代理