CSES - Shared codeLink to this code:
https://cses.fi/paste/82855b2d36cb16e78d8697/
//based on lowest common ancestor
//problem link https://cses.fi/problemset/task/1135
#include<bits/stdc++.h>
using namespace std;
const int LOG=20;
#define int long long
vector<vector<int>> up;
vector<int> depth;
void dfs(int node ,int parent, vector<int>tree[]){
for(int nbr:tree[node]){
if(nbr==parent ) continue;
up[nbr][0]=node;
depth[nbr]= depth[node]+1;
for(int j=1;j<LOG;j++){
up[nbr][j]= up[ up[nbr][j-1] ][j-1];
}
dfs(nbr,node,tree);
}
return ;
}
int get_LCA(int u,int v){
if(depth[u]< depth[v])
swap(u,v);
int k=depth[u]-depth[v];
if (k!=0){
for(int i=LOG-1;i>=0;i--){
if(k >= (1<<i)){
u=up[u][i];
k=k-(1<<i);
}
}
}
if(u==v) return u;
for(int j=LOG-1;j>=0;j--){
if(up[u][j]!= up[v][j]){
u=up[u][j];
v=up[v][j];
}
}
return up[u][0];
}
signed main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n,q;
cin>>n>>q;
up.resize(n+1,vector<int>(LOG,0));
depth.resize(n+1,0);
vector<int> tree[n+1];
for(int i=0;i<n-1;i++){
int a,b;
cin>>a>>b;
tree[a].push_back(b);
tree[b].push_back(a);
}
dfs(1,0,tree);
while(q--){
int a,b;
cin>>a>>b;
int LCA= get_LCA(a,b);
cout<< abs(depth[a]+ depth[b]- 2* depth[LCA] )<<endl;
}
}