Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <bits/stdc++.

h>
using namespace std;
const int MAX_N = 1e5 + 10;
const int height = 20;
vector<int> adj[MAX_N];
int up[MAX_N][height];
int lvl[MAX_N];
void sparse(int node,int par)
{
up[node][0]=par;

for(int i = 1;i<=height;i++)
{
up[node][i] = up[up[node][i-1]][i-1];
if(up[node][i]==0) return;
}
}
int move_up(int node, int k)
{
for(int i = height;i>=0;i--)
{
if(k & (1<<i))
{
node = up[node][i];
if(node == 0)
{
return 0;
}
}
}
return node;
}
void dfs(int node, int par,int d)
{
lvl[node] = d;
sparse(node,par);
for(auto it: adj[node])
{
if(it == par) continue;
dfs(it,node,d+1);
}
}
int LCA(int x,int y)
{
if(lvl[x]>lvl[y])
{
swap(x,y);
}

y = move_up(y,lvl[y]-lvl[x]);
if(x == y) return x;

for(int i = height-1;i>=0;i--)
{
if(up[x][i]==up[y][i])
{
continue;
}
x = up[x][i];
y = up[y][i];
}
return up[x][0];
}
vector<int> lca(int n, vector<vector<int>> edge, vector<vector<int>> query)
{
for(int i = 0;i<=n;i++)
{
adj[i].clear();
lvl[i]=0;
for(int j = 0;j<height;j++)
{
up[i][j]=0;
}
}
for(auto e: edge)
{
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
dfs(1,0,1);
vector<int> ans;
for(auto q: query)
{
ans.push_back(LCA(q[0],q[1]));
}
return ans;
}

You might also like