Finding Negative Cycles in a graph

I was exploring the algorithm for finding negative edge cycles in a Directed Graph using bellman-ford algorithm and came across this implementation in cp-algorithms.

struct Edge {
    int a, b, cost;
};

int n, m;
vector<Edge> edges;
const int INF = 1000000000;

void solve()
{
    vector<int> d(n);
    vector<int> p(n, -1);
    int x;
    for (int i = 0; i < n; ++i) {
        x = -1;
        for (Edge e : edges) {
            if (d[e.a] + e.cost < d[e.b]) {
                d[e.b] = d[e.a] + e.cost;
                p[e.b] = e.a;
                x = e.b;
            }
        }
    }

    if (x == -1) {
        cout << "No negative cycle found.";
    } else {
        for (int i = 0; i < n; ++i)
            x = p[x];

        vector<int> cycle;
        for (int v = x;; v = p[v]) {
            cycle.push_back(v);
            if (v == x && cycle.size() > 1)
                break;
        }
        reverse(cycle.begin(), cycle.end());

        cout << "Negative cycle: ";
        for (int v : cycle)
            cout << v << ' ';
        cout << endl;
    }
}

Can someone tell me, what is the significance of this for-loop?

for (int i = 0; i < n; ++i)
            x = p[x];

Ig, the algorithm could print the negative cycle correctly even without it, or am I missing something here?

Thanks in advance!

This is the heart of retrieving the cycle. This loop ensures that your start node is one that is present in a cycle and not a node that just got changed from the nth iteration.
For ex:
Consider the graph with arbitrary weights
[1] → 2 → 3 → 4
Where node 1 has a negative weighted self loop.

In the nth iteration, x will be 3.
To ensure that we end back up in the cycle, we need at max N parent iteration. (The above example is the worst case hence N.)

Hope this helps :slight_smile:

2 Likes

Thanks, @rogue_raven for the explanation and amazing example, it cleared the idea for me.

1 Like