DuongNhi99

LEXIPATH (lqdoj) - DFS

Mar 11th, 2021 (edited)
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. // https://lqdoj.edu.vn/problem/lexipath
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. const int N = 1e5 + 5;
  6.  
  7. vector<int> g[N];
  8. bool visited[N];
  9.  
  10. int n, m, s, t;
  11. vector<int> path;
  12.  
  13. // DFS(x) == true nếu x == t hoặc DFS(con của x) == t
  14. bool DFS(int u) {
  15.     visited[u] = true;
  16.  
  17.     if (u == t) {
  18.         path.push_back(u);
  19.         return true;
  20.     }
  21.  
  22.     for (int v : g[u]) {
  23.         if (!visited[v] && DFS(v) == true) {
  24.             path.push_back(u);
  25.             return true;
  26.         }
  27.     }
  28.  
  29.     return false;
  30. }
  31.  
  32. int main() {
  33. #ifdef LOCAL
  34.     freopen("in.txt", "r", stdin);
  35. #else
  36.     freopen("LEXIPATH.inp", "r", stdin);
  37.     freopen("LEXIPATH.out", "w", stdout);
  38. #endif
  39.     ios_base::sync_with_stdio(false);
  40.     cin.tie(nullptr);
  41.  
  42.     cin >> n >> m >> s >> t;
  43.  
  44.     for (int i = 1; i <= m; i++) {
  45.         int u, v;
  46.         cin >> u >> v;
  47.         g[u].push_back(v);
  48.     }
  49.  
  50.     for (int i = 1; i <= n; i++) {
  51.         sort(g[i].begin(), g[i].end());
  52.     }
  53.  
  54.     DFS(s);
  55.  
  56.     for (int i = (int) path.size() - 1; i >= 0; i--) {
  57.         cout << path[i] << ' ';
  58.     }
  59.  
  60.     return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment