c++ - 贝尔曼福特实现 C++

标签 c++ algorithm stl

我正在实现 Bellman Ford 算法,其中输入是有向加权图,输出是 1(有负循环)或 0(无负循环)。

我了解 Bellman Ford 算法,并在相当多的测试用例上运行了以下代码,但似乎无法通过我希望提交的平台上的所有测试用例。我看不到代码失败的特定测试用例。

关于问题可能出在哪里的任何指示都将非常有帮助

约束

1 ≤ n ≤ 10^3 , 0 ≤ m ≤ 10^4 ,边权重是绝对值最大为 10^3 的整数。 (n = 顶点,m = 边)

代码

#include <iostream>
#include <limits>
#include <vector>

using std::cout;
using std::vector;

int negative_cycle(vector<vector<int>> &adj, vector<vector<int>> &cost) {
  vector<int> dist(adj.size(), std::numeric_limits<int>::max());
  dist[0] = 0;
  for (int i = 0; i < adj.size() - 1; i++) {
    for (int j = 0; j < adj.size(); j++) {
      for (int k = 0; k < adj[j].size(); k++) {
        if (dist[j] != std::numeric_limits<int>::max()) {
          if ((dist[adj[j][k]] > dist[j] + cost[j][k])) {
            dist[adj[j][k]] = dist[j] + cost[j][k];
          }
        }
      }
    }
  }
  for (int j = 0; j < adj.size(); j++) {
    for (int k = 0; k < adj[j].size(); k++) {
      if (dist[j] != std::numeric_limits<int>::max()) {
        if ((dist[adj[j][k]] > dist[j] + cost[j][k])) {
          return 1;  // negative cycle
        }
      }
    }
  }
  return 0;  // no negative cycle
}

int main() {
  int n, m;
  std::cin >> n >> m;
  vector<vector<int>> adj(n, vector<int>());
  vector<vector<int>> cost(n, vector<int>());
  for (int i = 0; i < m; i++) {
    int x, y, w;
    std::cin >> x >> y >> w;
    adj[x - 1].push_back(y - 1);
    cost[x - 1].push_back(w);
  }
  std::cout << negative_cycle(adj, cost);
}

最佳答案

vector<int> dist(adj.size(), std::numeric_limits<int>::max());
dist[0] = 0;

在这一行中,您将顶点 #0 标记为起点,而将所有其他标记为不可到达。问题是,如果你的图被分成 >=2 个不同的部分,它不会为不包含顶点 #0 的部分找到负循环,因为来自其他部分的顶点仍然无法到达。

解决方案:将所有初始距离设置为零。

关于c++ - 贝尔曼福特实现 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55119060/

相关文章:

algorithm - 汉密尔顿路径和欧拉路径的区别

python - 如何从已知的关联中创建集群/组?

javascript - 有中点椭圆算法吗?

c++ - STL vector reserve() 和 copy()

c++ - 从子类的STL vector 到基类 vector 的转换

C++/OOP 关联模型和数据库

android - 使用 GCC ARM 调试时 END 枚举的问题

windows-7 - Windows现在必须重新启动,因为[我们的服务名称]服务意外终止

c++ - 用复利计算总返回

c++ - map 运算符 < 条件 - 无效比较器