Advertisement
Oppenheimer

Neg cycle detection bellmanford

Aug 19th, 2022
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. // 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
  2.  
  3. int n, m;
  4. vector<vector<int>> edges;
  5. const int INF = 1000000000;
  6.  
  7. void solve()
  8. {
  9.     vector<int> d(n);
  10.     vector<int> p(n, -1);
  11.     int x;
  12.     for (int i = 0; i < n; ++i) {
  13.         x = -1;
  14.         for (vector<int> e : edges) {
  15.             if (d[e[0]] + e[2] < d[e[1]]) {
  16.                 d[e[1]] = d[e[0]] + e[2];
  17.                 p[e[1]] = e[0];
  18.                 x = e[1];
  19.             }
  20.         }
  21.     }
  22.  
  23.     if (x == -1) {
  24.         cout << "No negative cycle found.";
  25.     } else {
  26.         for (int i = 0; i < n; ++i)
  27.             x = p[x]; // finding the parent of x after un relaxing n times
  28.  
  29.         vector<int> cycle;
  30.         for (int v = x;; v = p[v]) {
  31.             cycle.push_back(v); // as it is a cycle it will go back itself
  32.             if (v == x && cycle.size() > 1)
  33.                 break;
  34.         }
  35.         reverse(cycle.begin(), cycle.end());
  36.  
  37.         cout << "Negative cycle: ";
  38.         for (int v : cycle)
  39.             cout << v << ' ';
  40.         cout << endl;
  41.     }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement