tien_noob

BFS ( Adj List )

Feb 22nd, 2021 (edited)
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <numeric>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <vector>
  8. #include <climits>
  9. #include <string>
  10. #include <cstdio>
  11. #include <cmath>
  12. #define task "TESTCODE"
  13. using namespace std;
  14. const int N = 1e5;
  15. int x, y, n, s, m, f, Trace[N+1];
  16. vector<vector<int>> Adj;
  17. queue<int> q;
  18. void read()
  19. {
  20.    cin >> n >> m >> s >> f;
  21.    Adj.resize(n + 1);
  22.    for (int i = 1; i <= m; ++ i)
  23.    {
  24.        cin >> x >> y;
  25.        Adj[x].push_back(y);
  26.    }
  27.    fill (Trace, Trace + n + 1, 0);
  28. }
  29. void BFS(int s)
  30. {
  31.     q.push(s);
  32.     Trace[s] = -1;
  33.     while (!q.empty())
  34.     {
  35.         int u = q.front();
  36.         q.pop();
  37.         for (int v : Adj[u])
  38.         {
  39.             if (Trace[v] == 0)
  40.             {
  41.                 Trace[v] = u;
  42.                 q.push(v);
  43.             }
  44.         }
  45.     }
  46. }
  47. void solve()
  48. {
  49.    BFS(s);
  50.    for (int i = 1; i <= n; ++ i)
  51.    {
  52.        if (Trace[i] != 0)
  53.        {
  54.            cout << i << ' ';
  55.        }
  56.    }
  57.    cout << '\n';
  58.    while (f != s)
  59.    {
  60.        cout << f << "<- ";
  61.        f = Trace[f];
  62.    }
  63.    cout << s;
  64. }
  65. int main()
  66. {
  67.    ios_base::sync_with_stdio(false);
  68.    cin.tie(nullptr);
  69.    //freopen(task".INP", "r", stdin);
  70.    //freopen(task".OUT", "w", stdout);
  71.    read();
  72.    solve();
  73. }
  74.  
Add Comment
Please, Sign In to add comment