From 1fe04a96cf1999054411ba183259a220f923ba97 Mon Sep 17 00:00:00 2001 From: Mayank Musaddi <32260560+mayankmusaddi@users.noreply.github.com> Date: Mon, 8 Oct 2018 02:56:27 +0530 Subject: [PATCH] Create lca.cpp --- lca.cpp | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 lca.cpp diff --git a/lca.cpp b/lca.cpp new file mode 100644 index 0000000..6ef5be6 --- /dev/null +++ b/lca.cpp @@ -0,0 +1,101 @@ +#include +using namespace std; +typedef long long int ll; +const ll lt=100005; +vector adj[lt]; +vector arr; +vector st(lt,0); +vector en(lt,0); +vector ht(lt,0); +vector par(lt,0); +int p[lt][25]; + +int tp=0; +bool visited[lt]; + +void dfs(int u,int l) +{ + ht[u]=l; + arr.push_back(u); + visited[u]=1; + st[u]=tp++; + for(int i=0;iht[b]) + { + a=par[a]; + return find_lca(a,b); + } + else + return find_lca(b,a); +} + +int find_lca2(int a,int b) +{ + if(ht[a]==ht[b]) + { + if(a==b) + return a; + else + return find_lca2(p[a][0],p[b][0]); + } + else if(ht[a]>ht[b]) + { + int diff=ht[a]-ht[b]; + + for(int i=0;i<21 && diff>0;i++) + { + if((diff>>i) & 1) + a=p[a][i]; + } + + return find_lca2(a,b); + } + else + return find_lca2(b,a); +} + +int main() +{ + int n; + cin >> n; + for(int i=0;i> u >> v; + adj[u].push_back(v); + adj[v].push_back(u); + } + dfs(1,0); + + p[1][0]=1; + + for(int j=1;j<=21;j++) + for(int i=1;i<=n;i++) + p[i][j]=p[p[i][j-1]][j-1]; + + int a,b; + cin >> a >> b; + cout << find_lca(a,b) << endl; + cout << find_lca2(a,b) << endl; +}