Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4.  
  5. #define c_boost std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr)
  6.  
  7. using namespace std;
  8. using graph=vector <vector <int>>;
  9.  
  10. vector <bool> used;
  11. vector <int> reverseEdges;
  12.  
  13. graph g;
  14. graph gT;
  15.  
  16. void BFS(int start) {
  17.     queue <int> q;
  18.     q.push(start);
  19.     while (!q.empty()) {
  20.         int from = q.front();
  21.         q.pop();
  22.         used[from] = true;
  23.         for (int to: g[from]) {
  24.             reverseEdges[to] = min(reverseEdges[to], reverseEdges[from]);
  25.             if (!used[to]) {
  26.                 q.push(to);
  27.             }
  28.         }
  29.         for (int backTo : gT[from]) {
  30.             reverseEdges[backTo] = min(reverseEdges[backTo], reverseEdges[from] + 1);
  31.             if (!used[backTo]) {
  32.                 q.push(backTo);
  33.             }
  34.         }
  35.     }
  36. }
  37.  
  38. int main() {
  39.     c_boost;
  40.     int n, m, start, end;
  41.     cout << "Введите {n}, {m}, {start}, {end}\n";
  42.     cin >> n >> m >> start >> end;
  43.     used.assign(n, false);
  44.     reverseEdges.assign(n, 0);
  45.     g = graph(n);
  46.     gT = graph(n);
  47.     for (int i = 0; i < m; ++i) {
  48.         int from, to;
  49.         cin >> from >> to;
  50.         --from;
  51.         --to;
  52.         g[from].push_back(to);
  53.         gT[to].push_back(from);
  54.     }
  55.     BFS(start - 1);
  56.     cout << reverseEdges[end - 1];
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement