Advertisement
Alex_tz307

Bellman-Ford

Sep 11th, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. ifstream fin ("bellmanford.in");
  6. ofstream fout ("bellmanford.out");
  7.  
  8. int N, M, x, y, c;
  9. const int maxn = 50005;
  10. const int INF = 0x3f3f3f3f;
  11. vector < pair < int , int > > G[maxn];
  12.  
  13. int main () {
  14.     fin >> N >> M;
  15.     while (M --) {
  16.         fin >> x >> y >> c;
  17.         G[x].push_back ({y, c});
  18.     }
  19.     queue < int > Q;
  20.     bitset < maxn > inQ (false);
  21.     vector < int > dist (maxn, INF), cntinQ (maxn, 0);
  22.     bool ciclu_negativ = false;
  23.     dist[1] = 0, Q.push (1), inQ[1] = true;
  24.     while (!Q.empty() && !ciclu_negativ) {
  25.         int x = Q.front ();
  26.         Q.pop ();
  27.         inQ[x] = false;
  28.         vector < pair < int , int > > :: iterator it;
  29.         for (it = G[x].begin(); it != G[x].end(); ++it)
  30.         if (dist[x] < INF)
  31.         if (dist[it -> first] > dist[x] + it -> second) {
  32.             dist[it -> first] = dist[x] + it -> second;
  33.             if (!inQ[it -> first]) {
  34.                 if (cntinQ[it -> first] > N) ciclu_negativ = true;
  35.                 else {
  36.                     Q.push (it -> first);
  37.                     inQ[it -> first] = true;
  38.                     cntinQ[it -> first] ++;
  39.                 }
  40.             }
  41.         }
  42.     }
  43.     if (!ciclu_negativ) for (int i = 2; i <= N; i ++) fout << dist[i] << ' ';
  44.     else fout << "Ciclu negativ!\n";
  45.     fin.close ();
  46.     fout.close ();
  47.     return 0;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement