Advertisement
aakib_alam

Lowest_Common_Ancestor

Aug 15th, 2022
635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | Source Code | 0 0
  1. /*
  2.                                 Lowest Common Ancestor
  3.                             Time Complexity : O(nlogn) for preprocessing
  4.                                             :  O(1) for LCA
  5.                             Eulerian tour and sparse table is used.
  6. */
  7.  
  8. #include <bits/stdc++.h>
  9. using namespace std;
  10.  
  11. const int MAXN = 100005, LOGN = 20;
  12. vector<int> lev(MAXN), fst(MAXN), tour(4 * MAXN);
  13. vector<vector<int>> adj(MAXN), table(LOGN, vector<int>(4 * MAXN)), iter(LOGN, vector<int>(4 * MAXN));
  14. int idx_tour = 0;
  15.  
  16. void dfs_tour(int ch, int p)
  17. {
  18.     lev[ch] = lev[p] + 1;
  19.     fst[ch] = idx_tour;
  20.     tour[idx_tour++] = ch;
  21.     for (auto i : adj[ch])
  22.     {
  23.         if (i != p)
  24.             dfs_tour(i, ch);
  25.         tour[idx_tour++] = ch;
  26.     }
  27. }
  28.  
  29. void buildTable()
  30. {
  31.     for (int i = 0; i < idx_tour; i++)
  32.         table[0][i] = lev[tour[i]], iter[0][i] = tour[i];
  33.     for (int i = 1; i < LOGN; i++)
  34.     {
  35.         for (int j = 0; j + (1 << i) <= idx_tour; j++)
  36.         {
  37.             table[i][j] = min(table[i - 1][j], table[i - 1][j + (1 << (i - 1))]);
  38.             if (table[i - 1][j] <= table[i - 1][j + (1 << (i - 1))])
  39.                 iter[i][j] = iter[i - 1][j];
  40.             else
  41.                 iter[i][j] = iter[i - 1][j + (1 << (i - 1))];
  42.         }
  43.     }
  44. }
  45.  
  46. int LCA(int u, int v)
  47. {
  48.     int l = min(fst[u], fst[v]), r = max(fst[u], fst[v]), x;
  49.     x = log2(r - l + 1);
  50.     if (table[x][l] <= table[x][r - (1 << x) + 1])
  51.         return iter[x][l];
  52.     return iter[x][r - (1 << x) + 1];
  53. }
  54.  
  55. int main()
  56. {
  57.  
  58. #ifndef ONLINE_JUDGE
  59.     freopen("input1.txt", "r", stdin);
  60.     freopen("output1.txt", "w", stdout);
  61. #endif
  62.  
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement