Advertisement
GrandtherAzaMarks

Bellman Ford

Mar 21st, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.     int N = 0, M = 0;
  10.     cin >> N >> M;
  11.     vector <vector <pair <int, int> > > G(N);
  12.     for (int i = 0; i < M; i++)
  13.     {
  14.         int from = 0, to = 0, w = 0;
  15.         cin >> from >> to >> w;
  16.         G[from].push_back(make_pair(to, w));
  17.     }
  18.     vector <int> R(N, (1 << 31 - 1));
  19.     vector <int> P(N, -1);
  20.     R[0] = 0;// 0 - starting peak
  21.     queue <int> q;
  22.     q.push(0);
  23.     while (!q.empty())
  24.     {
  25.         int curent = q.front();
  26.         q.pop();
  27.         for (int i = 0; i < G[curent].size(); i++)
  28.         {
  29.             int to = G[curent][i].first;
  30.             int w = G[curent][i].second;
  31.             if (R[curent] + w < R[to])
  32.             {
  33.                 R[to] = R[curent] + w;
  34.                 q.push(to);
  35.                 P[to] = curent;
  36.             }
  37.         }
  38.     }
  39.    
  40.     for (int i = 0; i < P.size(); i++)
  41.         cout << P[i] << " ";
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement