Iamtui1010

bfs.cpp

Jul 9th, 2022
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. //#include <bits/stdc++.h>
  2. #include <iostream>
  3. #include <fstream>
  4. #include <vector>
  5. #include <queue>
  6. #include <algorithm>
  7. #include <stack>
  8.  
  9. #define nln "\n"
  10. #define long long long
  11.  
  12. const long N = 100010;
  13.  
  14. using namespace std;
  15.  
  16. fstream f1, f2;
  17.  
  18. inline void openf()
  19. {
  20.     f1.open("bfs.inp", ios:: in);
  21.     f2.open("bfs.out", ios:: out);
  22. }
  23.  
  24. static vector<vector<long>> a(N);
  25. long n, m, s, f;
  26.  
  27. void data()
  28. {
  29.     f1.tie(0)->sync_with_stdio(0);
  30.     f2.tie(0)->sync_with_stdio(0);
  31.  
  32.     f1 >> n >> m >> s >> f;
  33.     for (size_t i = 0; i != m; ++i)
  34.     {
  35.         long x, y;
  36.         f1 >> x >> y;
  37.         a[x].push_back(y);
  38.     }
  39.  
  40.     for (size_t i = 1; i-1 != n; ++i)
  41.         sort(a[i].begin(), a[i].end());
  42. }
  43.  
  44. static vector<bool> busy(N, 0);
  45. static vector<long> road(N, 0);
  46. static queue<long> que;
  47.  
  48.  
  49. void process()
  50. {
  51.     // Breadth-First Searching
  52.     que.push(s);
  53.     busy[s] = 1;
  54.     while (!que.empty())
  55.     {
  56.         long u = que.front();
  57.         que.pop();
  58.         for (const auto &i : a[u])
  59.         {
  60.             if (!busy[i])
  61.             {
  62.                 road[i] = u;
  63.                 que.push(i);
  64.                 busy[i] = 1;
  65.             }          
  66.         }
  67.     }
  68. }
  69.  
  70. void view()
  71. {
  72.  
  73.     // Trace
  74.     stack<long> rs;
  75.     long co = 1;
  76.  
  77.     while (f != s && f != 0)
  78.     {
  79.         ++co;
  80.         rs.push(f);
  81.         f = road[f];
  82.     }
  83.  
  84.     if (f != 0)
  85.     {
  86.         f2 << co << nln;
  87.         rs.push(s);
  88.         while (!rs.empty())
  89.         {
  90.             f2 << rs.top() << " ";
  91.             rs.pop();
  92.         }
  93.     }
  94.     else
  95.         f2 << "0";
  96. }
  97.  
  98. inline void closef()
  99. {
  100.     f1.close();
  101.     f2.close();
  102. }
  103.  
  104. int main()
  105. {
  106.     openf();
  107.     data();
  108.     process();
  109.     view();
  110.     closef();
  111.     return 0;
  112. }
Advertisement
Add Comment
Please, Sign In to add comment