Advertisement
DuongNhi99

LCA

Jan 18th, 2022
688
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3. using namespace std;
  4.  
  5. const int N = 1e5 + 5;
  6. const int M = log2(N) + 1;
  7.  
  8. int n, l;
  9. vector<int> a[N];
  10.  
  11. int timer;
  12. int t_in[N], t_out[N];
  13. int up[N][M];
  14.  
  15. void DFS(int v, int p) {
  16.     t_in[v] = ++timer;
  17.     up[v][0] = p;
  18.  
  19.     for(int i = 1; i <= l; ++i)
  20.         up[v][i] = up[up[v][i-1]][i-1];
  21.  
  22.     for(int u : a[v])
  23.         if(u != p) DFS(u, v);
  24.     t_out[v] = ++ timer;
  25. }
  26.  
  27. bool is_ancestor(int u, int v) {
  28.     return t_in[u] <= t_in[v] && t_out[u] >= t_out[v];
  29. }
  30.  
  31. int LCA(int u, int v) {
  32.     if(is_ancestor(u, v))
  33.         return u;
  34.  
  35.     if(is_ancestor(v, u))
  36.         return v;
  37.  
  38.     for(int i = l; i >= 0; --i)
  39.         if(!is_ancestor(up[u][i], v))
  40.             u = up[u][i];
  41.  
  42.     return up[u][0];
  43. }
  44.  
  45. int main() {
  46.     //freopen("LCA.inp", "r", stdin);
  47.     //freopen("LCA.out", "w", stdout);
  48.     ios_base::sync_with_stdio(false);
  49.     cin.tie(NULL); cout.tie(NULL);
  50.  
  51.     cin >> n;
  52.     for(int i = 1; i <= n-1; ++i){
  53.         int u, v; cin >> u >> v;
  54.         a[u].push_back(v);
  55.         a[v].push_back(u);
  56.     }
  57.     timer = 0;
  58.     l = log2(n);
  59.     DFS(1, 1);
  60.  
  61.     int t; cin >> t;
  62.     while(t--) {
  63.         int u, v; cin >> u >> v;
  64.         cout << LCA(u, v) << '\n';
  65.     }
  66.     return 0;
  67. }
  68. /*
  69. 8
  70. 1 2
  71. 2 4
  72. 4 3
  73. 6 3
  74. 8 3
  75. 5 4
  76. 7 4
  77. 3
  78. 6 4
  79. 6 8
  80. 8 7
  81.  
  82. -> 4 3 4
  83. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement