Advertisement
Hamoudi30

Untitled

Aug 5th, 2021
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. #define SZ(v) ((int)(v).size())
  5. #define pb push_back
  6. const int N = 2e5+9;
  7. const int inf = 1e9+9;
  8.  
  9. vector<int> adj[N];
  10.  
  11. vector<int> BFSPath (int st_node, int target) {
  12.     queue<int> q;
  13.     q.push(st_node);
  14.     vector<int> level(N, -1);
  15.     vector<int> parent(N, -1);
  16.     level[st_node] = 0;
  17.     int cur_node, depth = 0, sz_q = SZ(q);
  18.     bool found = false;
  19.     for (; !q.empty() && not found; ++depth, sz_q = SZ(q)) {
  20.         while (sz_q--) {
  21.             cur_node = q.front();
  22.             q.pop();
  23.             for (int child : adj[cur_node]) {
  24.  
  25.                 if (level[child] == -1) {
  26.                     level[child] = depth + 1;
  27.                     q.push(child);
  28.  
  29.                     parent[child] = cur_node;
  30.  
  31.                     // check parent
  32.                     if (child == target) {
  33.                         // found
  34.                         found = true;
  35.                         break;
  36.                     }
  37.                 }
  38.  
  39.             }
  40.         }
  41.     }
  42.     // get_path
  43.     vector<int> path;
  44.     while (target != -1) { // fail -> target = -1
  45.         path.push_back(target);
  46.         target = parent[target];
  47.     }
  48.     // 5 4 3 1
  49.     reverse(path.begin(), path.end());
  50.     return path;
  51.  
  52. }
  53.  
  54.  
  55. void run () {
  56.     int n, m;
  57.     cin >> n >> m;
  58.     for (int i = 0; i < m; ++i) {
  59.         int u, v;
  60.         cin >> u >> v;
  61.         adj[u].push_back(v);
  62.         adj[v].push_back(u);
  63.     }
  64.     vector<int> dist;
  65.     dist = BFSPath(1, 5);
  66.     for (int i = 0; i < SZ(dist); ++i)
  67.         cout << dist[i] << " ";
  68. }
  69. int main () {
  70.     ios_base::sync_with_stdio(false);
  71.     cin.tie(nullptr);
  72.     cout.tie(nullptr);
  73.     freopen("/home/hamoudi/clion/hello.in", "rt", stdin);
  74.     int tt;
  75.     tt = 1;
  76.     //    cin >> tt;
  77.     while (tt--)
  78.         run();
  79.     return 0;
  80. }
  81. /*
  82.       1     -> 0
  83.     2   3   -> 1
  84.         4   -> 2
  85.         5   -> 3
  86.  
  87.         1 3 4 5
  88.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement