Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. vector<ll> G[N];
  2. ll par[N][LOGN], h[N];
  3.  
  4. void dfs(int u, int p = -1) {
  5.     par[u][0] = p;
  6.     if (~p)
  7.         h[u] = h[p] + 1;
  8.     for (int i = 1; i < LOGN; ++i)
  9.         if (~par[u][i - 1])
  10.             par[u][i] = par[par[u][i - 1]][i - 1];
  11.  
  12.     for (auto to : G[u])
  13.         if (to != p)
  14.             dfs(to, u);
  15. }
  16.  
  17. int LCA(int u, int v) {
  18.     if (h[u] < h[v])
  19.         swap(u, v);
  20.  
  21.     for (int i = LOGN - 1; ~i; --i) // make them the same level
  22.         if (~par[u][i] && h[par[u][i]] >= h[v])
  23.             u = par[u][i];
  24.  
  25.     if (u == v)
  26.         return u;
  27.  
  28.     for (int i = LOGN - 1; ~i; --i)
  29.         if (par[u][i] != par[v][i])
  30.             u = par[u][i], v = par[v][i];
  31.  
  32.     return par[u][0];
  33. }
  34.  
  35. void clear() {
  36.         memset(par, -1, sizeof(par));
  37.         memset(h, 0, sizeof(h));
  38.  
  39.         for (int i = 0; i < n; ++i)
  40.             G[i].clear();
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement