From 9519fe7099eed3aec691b92d215b769cc1839e22 Mon Sep 17 00:00:00 2001 From: Anthony Wang Date: Thu, 21 Jan 2021 20:18:42 -0600 Subject: Update lca.cpp --- Graph/lca.cpp | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/Graph/lca.cpp b/Graph/lca.cpp index b6d695f..f45ee1c 100644 --- a/Graph/lca.cpp +++ b/Graph/lca.cpp @@ -1,18 +1,14 @@ -namespace lca { - int d[MX], L[MX][20]; - void dfs(vector * G, int u = 1, int p = 0) { - d[u] = d[p] + 1, L[u][0] = p; - for (int i = 0; i < 18 && L[u][i]; i++) L[u][i + 1] = L[L[u][i]][i]; - for (auto & v : G[u]) if (v != p) dfs(G, v, u); - } - int lca(vector * G, int u, int v) { - if (d[u] > d[v]) swap(u, v); - for (int i = 18; i >= 0; --i) if (d[v] - (1 << i) >= d[u]) v = L[v][i]; - if (u == v) return u; - for (int i = 18; i >= 0; --i) if (L[u][i] && L[u][i] != L[v][i]) u = L[u][i], v = L[v][i]; - return L[u][0]; - } - inline int dist(vector * G, int u, int v) { - return d[u]+d[v]-2*d[lca(G, u, v)]; - } +int d[MX], L[MX][20]; +void dfs(int u = 1, int p = 0) { + d[u] = d[p] + 1, L[u][0] = p; + for (int i = 0; i < 18 && L[u][i]; i++) L[u][i+1] = L[L[u][i]][i]; + for (auto & v : G[u]) if (v != p) dfs(v, u); } +int lca(int u, int v) { + if (d[u] > d[v]) swap(u, v); + for (int i = 18; i >= 0; --i) if (d[v] - (1<= d[u]) v = L[v][i]; + if (u == v) return u; + for (int i = 18; i >= 0; --i) if (L[u][i] && L[u][i] != L[v][i]) u = L[u][i], v = L[v][i]; + return L[u][0]; +} +inline int dist(int u, int v) { return d[u]+d[v]-2*d[lca(u, v)]; } -- cgit v1.2.3-70-g09d2