#include<bits/stdc++.h>
using namespace std;
#define N 500010
int cont, head[N], next[N], val[N], d[N], f[N][25], t;
void add(int u, int v)
{
val[++ cont] = v;
next[cont] = head[u];
head[u] = cont;
}
int n, p, rt;
queue<int> q;
void bfs()
{
q.push(rt);
d[rt] = 1;
while(q.size())
{
int now = q.front();
q.pop();
for(int i = head[now];i;i = next[i])
{
int s = val[i];
if(d[s]) continue;
d[s] = d[now] + 1;
f[s][0] = now;
for(int j = 1;j <= 20;j ++) f[s][j] = f[f[s][j - 1]][j - 1];
q.push(s);
}
}
}
int lac(int x, int y)
{
if(d[x] > d[y]) swap(x, y);
for(int j = 20;j >= 0;j --)
if(d[f[y][j]] >= d[x]) y = f[y][j];
if(x == y) return y;
for(int j = 20;j >= 0;j --)
if(f[x][j] != f[y][j]) x = f[x][j], y = f[y][j];
return f[x][0];
}
int main()
{
cin >> n >> p >> rt;
int a, b;
for(int i = 1;i < n;i ++)
{
cin >> a >> b;
add(a, b);
add(b, a);
}
bfs();
for(int i = 1;i <= p;i ++)
{
cin >> a >> b;
int ans = lac(a, b);
cout << ans << "\n";
}
return 0;
}
为啥本地可以编译,洛谷失败啊