Link to this code:
https://cses.fi/paste/ed06a14e2417edb1f48fbd//*
* Author:Jx07
* Created:Friday, 23.01.2026 04:57 PM (GMT+5:30)
*/
#include<bits/stdc++.h>
#ifdef JAI
#include "algo/debug.cpp"
#else
#define debug(...)
#endif
using namespace std;
mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
#define int long long
#define all(v) v.begin(), v.end()
#define peace
const int tt=0;
int MOD=1e9+7;//998244353;
int LOG,n;
vector<vector<int>> graph(n);
vector<int> depth(n, 0);
vector<vector<int>> binl(n, vector<int>(LOG));
void dfs(int node, int par) {
for(auto child : graph[node]) {
if(child == par) {
continue;
}
depth[child] = depth[node] + 1;
binl[child][0] = node;
for(int i = 1; i < LOG; i++) {
binl[child][i] = binl[binl[child][i - 1]][i - 1];
}
dfs(child, node);
}
}
int get_lca(int u, int v) {
if(depth[u] < depth[v]) {
swap(u, v);
}
int k = depth[u] - depth[v];
for(int j = LOG - 1; j >= 0; j--) {
if(k & (1LL << j)) {
u = binl[u][j];
k^=(1LL<<j);
}
if(k==0)break;
}
if(u == v) {
return u;
}
for(int j = LOG - 1; j >= 0; j--) {
if(binl[u][j] != binl[v][j]) {
u = binl[u][j];
v = binl[v][j];
if(u==v)break;
}
}
return binl[u][0];
}
void solve(int tc){
int q;
cin >> n >> q;
LOG = log2(n) + 1;
graph.resize(n,vector<int>());
depth.resize(n,0);
binl.resize(n,vector<int>(LOG));
for(int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
u--; v--;
graph[u].push_back(v);
graph[v].push_back(u);
}
// debug(n);
dfs(0, -1);
while(q--) {
int u, v;
cin >> u >> v;
u--; v--;
int x = get_lca(u, v);
int dist = depth[u] + depth[v] - (2 * depth[x]);
cout << dist << endl;
}
}
signed main() {
#if defined(JAI) && defined(peace)
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
clock_t T = clock();
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t=1;
if(tt)cin>>t;
for(int i=1;i<=t;i++){
solve(i);
}
#if defined(JAI) && defined(peace)
cout << "\nTime : " << ((float)(clock() - T)*1000) / CLOCKS_PER_SEC << " ms";
#endif
return 0;
}