Ford Bellman algorithm

mail@pastecode.io avatar
unknown
c_cpp
3 years ago
959 B
3
Indexable
Never
class FordBellman{
  vector<tuple<int, int, int> > edges;
  vector<int> dist, pred;
  const int INF = INT_MAX;
  int MAXN;
  FordBellman(int MAXN){
    this->MAXN = MAXN;
    dist.resize(MAXN);
    pred.resize(MAXN);
  }
  void add_edge(int from, int to, int cost){
    edges.push_back({from, to, cost});
  }

bool bellman_ford(int n, int m, int source)
{
    for(int i = 0; i<MAXN; i++)
    {
        dist[i] = INF;
    }
    dist[source] = 0;
    for(int i = 0; i<n; i++)
    {
        for(auto e : edges)
        {
            int u, v, d;
            tie(u, v, d) = e;
            if(dist[u] + d < dist[v])
            {
                dist[v] = dist[u] + d;
                pred[v] = u;
            }
        }
    }

    // to check for negative cycle
    for(auto e : edges)
    {
        int u, v, d;
        tie(u, v, d) = e;
        if(dist[u] + d < dist[v]) return true;
    }

    return false;

}
};