Advertisement
keverman

LCA [Binary Lifting]

Feb 10th, 2020
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. int n, h, timer;
  2. vector<vector<int>> edges, up;
  3. vector<int> tin, tout;
  4.  
  5. void lca_dfs(int u, int p)
  6. {
  7.     tin[u] = ++timer;
  8.     up[u][0] = p;
  9.     for (int i = 1; i <= h; i++)
  10.         up[u][i] = up[up[u][i - 1]][i - 1];
  11.     for (int v : edges[u])
  12.         if (v != p)
  13.             lca_dfs(v, u);
  14.     tout[u] = ++timer;
  15. }
  16.  
  17. void preprocess(int root)
  18. {
  19.     timer = 0;
  20.     for (h = 1; h < n; h *= 2);
  21.     tin.resize(n, 0), tout.resize(n, 0);
  22.     up.resize(n, vector<int>(h + 1, -1));
  23.     lca_dfs(root, root);
  24. }
  25.  
  26. bool is_ancestor(int u, int v)
  27. {
  28.     return tin[u] <= tin[v] && tout[u] >= tout[v];
  29. }
  30.  
  31. int lca(int u, int v)
  32. {
  33.     if (is_ancestor(u, v)) return u;
  34.     if (is_ancestor(v, u)) return v;
  35.  
  36.     for (int i = h; i >= 0; i--)
  37.         if (!is_ancestor(up[u][i], v))
  38.             u = up[u][i];
  39.  
  40.     return up[u][0];
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement