Advertisement
Guest User

Negative Cycle Finding (Bellman Ford Algorithm)

a guest
Feb 24th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. /**
  2.  * Author     : Dipu Kumar Mohanto (Dip)
  3.  *              BRUR
  4.  * Problem    : 558 - Wormholes
  5.  * Category   : Negative Cycle Finding (Bellman Ford Algorithm)
  6.  * OJ         : UVA
  7.  * Verdict    : Accepted
  8.  * Date       : 06-10-2016
  9.  **/
  10.  
  11. #include <bits/stdc++.h>
  12.  
  13. using namespace std;
  14.  
  15. #define N 10000
  16. const int INF = 0x3f3f3f;
  17.  
  18. struct Edge {
  19.     int u, v, w;
  20. };
  21.  
  22. vector<Edge> G;
  23. int dis[N];
  24. int node, ver;
  25.  
  26. bool NegCycle(int s) {
  27.     memset(dis, INF, sizeof(dis));
  28.  
  29.     dis[s] = 0;
  30.  
  31.     for (int i=0; i<node-1; i++) {
  32.         for (Edge e : G) {
  33.             int u = e.u;
  34.             int v = e.v;
  35.             int w = e.w;
  36.  
  37.             if (dis[v] > dis[u] + w) {
  38.                 dis[v] = dis[u] + w;
  39.             }
  40.         }
  41.     }
  42.     for (int i=0; i<ver; i++) {
  43.         int u = G[i].u;
  44.         int v = G[i].v;
  45.         int w = G[i].w;
  46.  
  47.         if (dis[v] > dis[u] + w)
  48.             return 1;
  49.     }
  50.     return 0;
  51. }
  52.  
  53. int main()
  54. {
  55.     //freopen("in.txt", "r", stdin);
  56.     //freopen("out.txt", "w", stdout);
  57.  
  58.     int tc;
  59.     cin >> tc;
  60.  
  61.     while (tc--) {
  62.         cin >> node >> ver;
  63.  
  64.         for (int i=0; i<ver; i++) {
  65.             int x, y, z;
  66.  
  67.             cin >> x >> y >> z;
  68.  
  69.             Edge get;
  70.  
  71.             get.u = x;
  72.             get.v = y;
  73.             get.w = z;
  74.  
  75.             G.push_back(get);
  76.         }
  77.  
  78.         bool f = NegCycle(0);
  79.  
  80.         if (f == 1)
  81.             cout << "possible\n";
  82.         else
  83.             cout << "not possible\n";
  84.  
  85.         G.clear();
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement