RT,T了7个点......
求大佬答疑qwq
#include<cstdio>
#include<vector>
#define maxn 500020
using namespace std;
int n,m,s;
int fa[maxn],dep[maxn],cnt[maxn],hson[maxn],top[maxn];
vector<int> tree[maxn];
inline void swap(int &x,int &y){x^=y,y^=x,x^=y;}
void dfs1(int x,int d){
// printf("%d ",x);
cnt[x] = 1;
dep[x] = d;
for(int i=0;i<tree[x].size();i++){
int y = tree[x][i];
if(y == fa[x]) continue;
fa[y] = x;
dfs1(y,d+1);
cnt[x] += cnt[y];
if(cnt[hson[x]] < cnt[y]) hson[x] = y;
}
}
void dfs2(int x,int tp){
top[x] = tp;
if(hson[x]) dfs2(hson[x],tp);
for(int i=0;i<tree[x].size();i++){
int y = tree[x][i];
if(y==fa[x]) continue;
dfs2(y,y);
}
}
int lca(int x,int y){
while(top[x] != top[y]){
if(dep[top[x]] < dep[top[y]]) swap(x,y);
x = fa[top[x]];
// printf("%d %d\n",x,y);
}
return dep[x] < dep[y]?x:y;
}
int read(){
int num=0;
char c=getchar();
while(c<'0'||c>'9') c=getchar();
while('0'<=c&&c<='9') num=num*10+c-'0',c=getchar();
return num;
}
int main(){
n=read(),m=read(),s=read();
for(int i=1;i<n;i++){
int x=read(),y=read();
tree[x].push_back(y);
tree[y].push_back(x);
}
// printf("1");
fa[s]=s;
dfs1(s,1);
dfs2(s,s);
while(m--){
int x=read(),y=read();
printf("%d\n",lca(x,y));
}
return 0;
}