From c45683bb8cb4d4df1d4ddcd19c487cd63c1a6411 Mon Sep 17 00:00:00 2001 From: rohan Date: Fri, 4 Oct 2019 19:05:23 +0530 Subject: [PATCH] Added LCA binary Lifting O(nlogn) --- Graph/lca.cpp | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Graph/lca.cpp diff --git a/Graph/lca.cpp b/Graph/lca.cpp new file mode 100644 index 000000000..b0ff12750 --- /dev/null +++ b/Graph/lca.cpp @@ -0,0 +1,90 @@ +#include +using namespace std; +// Find the lowest common ancestor using binary lifting in O(nlogn) +// Zero based indexing +// Resource : https://cp-algorithms.com/graph/lca_binary_lifting.html +const int N = 1005; +const int LG = log2(N)+1; +struct lca{ + int n; + vector adj[N]; // Graph + int up[LG][N]; // build this table + int level[N]; // get the levels of all of them + + lca(int n_) : n(n_){ + memset(up,-1,sizeof(up)); + memset(level,0,sizeof(level)); + for(int i=0; i>a>>b; a--; b--; + adj[a].push_back(b); + adj[b].push_back(a); + } + level[0] = 0; + dfs(0,-1); + build(); + } + void verify(){ + for(int i=0; i level[u] ){ swap(u,v); } + // u is at the bottom. + int dist = level[u] - level[v]; + // Go up this much distance + for(int i=LG-1; i>=0; --i){ + if( dist & ( 1 << i) ){ + u = up[i][u]; + } + } + if( u == v ){ return u; } + assert(level[u] == level[v]); + for(int i=LG-1; i>=0; --i){ + if( up[i][u] != up[i][v] ){ + u = up[i][u]; + v = up[i][v]; + } + } + assert(up[0][u] == up[0][v]); + return up[0][u]; + } +}; + +int main(){ + int n; // number of nodes in the tree. + lca l(n); // will take the input in the format given + // n-1 edges of the form + // a b + // Use verify function to see. +}