Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // we run bellman ford n times if there is any change that means neg cycle exists and the vertex at which change occurs is noted
- int n, m;
- vector<vector<int>> 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 (vector<int> e : edges) {
- if (d[e[0]] + e[2] < d[e[1]]) {
- d[e[1]] = d[e[0]] + e[2];
- p[e[1]] = e[0];
- x = e[1];
- }
- }
- }
- if (x == -1) {
- cout << "No negative cycle found.";
- } else {
- for (int i = 0; i < n; ++i)
- x = p[x]; // finding the parent of x after un relaxing n times
- vector<int> cycle;
- for (int v = x;; v = p[v]) {
- cycle.push_back(v); // as it is a cycle it will go back itself
- if (v == x && cycle.size() > 1)
- break;
- }
- reverse(cycle.begin(), cycle.end());
- cout << "Negative cycle: ";
- for (int v : cycle)
- cout << v << ' ';
- cout << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement