步骤如下:
1. 将当前查询需要的根makeroot, 表示为当前根下的lca
2. 将x Access到根, 此时x到根的路径是一棵平衡树
3. 将y Access, 中途遇到了与根一棵平衡树的点就记录下来(即与x到根的路径相遇), 返回即可
#include<bits/stdc++.h>
#define N 500050
#define ls t[x].ch[0]
#define rs t[x].ch[1]
using namespace std;
int n,m,rt;
struct LCT{int ch[2],fa,tag;}t[N];
int read(){
int cnt=0,f=1;char ch=0;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch))cnt=cnt*10+(ch-'0'),ch=getchar();
return cnt*f;
}
bool isRoot(int x){
int fa = t[x].fa; if(!fa) return true;
return t[fa].ch[0] != x && t[fa].ch[1] != x;
}
void Pushdown(int x){
if(t[x].tag){
swap(ls,rs);
t[ls].tag ^= 1; t[rs].tag ^= 1;
t[x].tag = 0;
}
}
void Pushpath(int x){
if(!isRoot(x)) Pushpath(t[x].fa);
Pushdown(x);
}
void rotate(int x){
int y = t[x].fa, z = t[y].fa;
int k = (t[y].ch[1]==x);
if(!isRoot(y)) t[z].ch[t[z].ch[1]==y] = x;
t[x].fa = z;
t[y].ch[k] = t[x].ch[k^1];
t[t[x].ch[k^1]].fa = y;
t[x].ch[k^1] = y; t[y].fa = x;
}
void Splay(int x){
Pushpath(x);
while(!isRoot(x)){
int y = t[x].fa, z = t[y].fa;
if(!isRoot(y))
(t[y].ch[0]==x) ^ (t[z].ch[0]==y) ? rotate(x) : rotate(y);
rotate(x);
}
}
int Access(int x){
int tmp = 0;
for(int y=0;x;y=x,x=t[x].fa)
Splay(x), rs = y, tmp = x;
return tmp;
}
void Makeroot(int x){ Access(x); Splay(x); t[x].tag ^= 1;}
void Link(int x,int y){ Makeroot(x); t[x].fa = y;}
int main(){
n = read(), m = read(), rt = read();
for(int i=1;i<n;i++){
int x = read(), y = read();
Link(x,y);
}
Makeroot(rt);
while(m--){
int x = read(), y = read();
Access(x); printf("%d\n",Access(y));
} return 0;
}