Alex_tz307

LCA BINARY LIFTING

Aug 16th, 2021
735
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.55 KB | None | 0 0
  1. void dfs(int u, int p) {
  2.   anc[u][0] = parent;
  3.   for (int i = 1; i <= lg; ++i)
  4.     anc[u][i] = anc[anc[u][i - 1]][i - 1];
  5.   for (int v : G[u])
  6.     if (v != p) {
  7.       level[v] = level[u] + 1;
  8.       dfs(v, u);
  9.     }
  10. }
  11.  
  12. int lca(int u, int v) {
  13.   if (level[u] < level[v])
  14.     swap(u, v);
  15.   for (int i = lg; i >= 0; --i)
  16.     if (level[u] - (1 << i) >= level[v])
  17.       u = anc[u][i];
  18.   if (u == v)
  19.     return u;
  20.   for (int i = lg; i >= 0; --i)
  21.     if (anc[u][i] != anc[v][i]) {
  22.       u = anc[u][i];
  23.       v = anc[v][i];
  24.     }
  25.   return anc[u][0];
  26. }
Advertisement
Add Comment
Please, Sign In to add comment